By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,852 Members | 2,116 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,852 IT Pros & Developers. It's quick & easy.

XMLHttpRequest.Open not working

P: 72
Hi, I need help to understand how to send data from javascript client to php server.

I want to save some data (a large table) from a web page to a mysql database. I thought the following js and php codes will do that. But it doesn't work so may be I don't understand the concept at all.

The way I understand it is the javascript sends the string "555" to the file 'test.txt' on the server, and the php reads the string from the same file where I can do something with it, eg save to database.

I know the php part works because if I manually create the file test.txt then its content is displayed on the web page. But the javascript code is not updating the file test.txt

javascript
Expand|Select|Wrap|Line Numbers
  1. request = new XMLHttpRequest();
  2. request.open("POST", "./test.txt", true);
  3. request.setRequestHeader("Content-type", "application/json");
  4. request.send("555");
  5.  
php
Expand|Select|Wrap|Line Numbers
  1. $arr = file_get_contents("./test.txt");
  2. var_dump($arr);
  3.  
I am new to the interaction between javascript and php, so any help would be greatly appreciated.

I am using localhost to test this code
Jun 19 '15 #1
Share this Question
Share on Google+
8 Replies


Dormilich
Expert Mod 5K+
P: 8,639
The way I understand it is the javascript sends the string "555" to the file 'test.txt' on the server, and the php reads the string from the same file where I can do something with it
the only correct part here is that JavaScript sends something to the destination file. every other assumption is plain wrong.

- files are read-only over HTTP
- PHP doesn’t automatically know if some file has changed
- you declare your sent data to be JSON, but it’s plain text (a number)

if you want to send data to PHP, then you have to send the data to a PHP script file.
Jun 19 '15 #2

P: 72
Hi Dormilich,

Thanks for your reply.

I am not sure what you are telling me. What do you mean php script? The 'file_get_contents' bit is in php code. See below.

From my debugging, the php can read the content of the file 'test.txt' but the javascript is not updating it. I thought that is where the problem is. The file is actually on my pc because I am using the localhost server.

May be I need to give you more of my code. The data I need to save to the database is a table of checkboxes. That is why I use js to gather the data into a json object. But it is the mechanism of sending data (any data) from js to php that I need to sort out.

Basically when the button btnSave is clicked the js function xx() is executed sending data off and the php function temp() (part of Attendance class) is also executed getting the data and save it to the db. That is what I am trying to achieve.

html markup
Expand|Select|Wrap|Line Numbers
  1. <form id="attend" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
  2. <?php
  3.     if (isset($_POST["btnSave"])) {
  4.         $attend = new AttendanceClass();
  5.         $attend->temp();
  6.     }
  7. ?>
  8.     <input type="submit" name="btnSave" value="Save" onclick="xx()"/>
  9. </form>
  10.  
  11. <script src="script.js"></script>
  12.  

php code
Expand|Select|Wrap|Line Numbers
  1. class AttendanceClass
  2. {
  3.     public function temp()
  4.     {
  5.         $arr = file_get_contents("./test.txt");
  6.         var_dump($arr);
  7.     }
  8. }
  9.  

javascript
Expand|Select|Wrap|Line Numbers
  1. function xx() {
  2.     var car = { type: "Fiat", model: 500 };
  3.     var str_json = JSON.stringify(car);
  4.  
  5.     request = new XMLHttpRequest();
  6.     request.open("POST", "./test.txt", true);
  7.     request.setRequestHeader("Content-type", "application/json");
  8.     request.send("555");
  9. }
  10.  
in the request.send() function I can use the json object str_json instead of "555" but I am trying to make things easier to follow.

Hope I have made myself clearer.

Thank you so much for you time!!
Jun 19 '15 #3

Dormilich
Expert Mod 5K+
P: 8,639
What do you mean php script?
a file that is run through PHP. test.txt is a simple text file, which 1) does not get written (forbidden by webserver) and 2) it does not trigger a PHP script that could process the text file’s content.

the least you should change is
Expand|Select|Wrap|Line Numbers
  1. request.open("POST", "./test.php", true);
  2.  
additionally, for your case JSON is not suitable because you would have to read it off the input stream, instead of the usual $_POST variable.

so the least working code should look like
Expand|Select|Wrap|Line Numbers
  1. var request = new XMLHttpRequest();
  2. request.open("POST", "./test.php", true);
  3. request.send('type=FIAT&model=500');
  4.  
and test.php
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. if (!isset($_POST['type'], $_POST['model'])) {
  3.     header('HTTP/1.0 400 Bad Request');
  4.     echo 'Missing "type" and/or "model".';
  5.     exit(0);
  6. }
  7. // do something with the passed data
  8.  
Jun 19 '15 #4

P: 72
Hi Dormilich,

Can you help me further? I can't get it to work.

I have made changes as you have suggested. It doesn't seem to be going through the php script.

It doesn't crash, it doesn't give me an error. I can't tell what it is doing.

The javascript part seems to be working ok because I can see the console.log() traces. If I deliberately use the wrong php file name in the .open() then it tells me that file is not found which is as it should be, for example

Expand|Select|Wrap|Line Numbers
  1.     request.open("POST", "./xxtest.php", true);
  2.  
Other than that I can't tell what it is doing inside the php script. To debug, I have tried to log it. I have tried to write to db. I have tried to write to html local storage. Can't see a thing from the php script!

How do I debug this?

this is the javascript
Expand|Select|Wrap|Line Numbers
  1. function xx()
  2. {
  3.     var request = new XMLHttpRequest();
  4.     console.log("11");
  5.     request.open("POST", "./test.php", true);
  6.     console.log("22");
  7.     console.log("33");
  8.     request.send('type=FIAT&model=500');
  9.     console.log("44");
  10. }
  11.  
this is the php script
Expand|Select|Wrap|Line Numbers
  1. localStorage.setItem("lastname", "wow");
  2. error_log("Big trouble!", 1,  "xx@yahoo.com.au");
  3.  
  4. if (!isset($_POST['type'],$_POST['model'])) {
  5.     header('HTTP/1.0 400 Bad Request');
  6.     echo 'Missing "type" and/or "model".';
  7.     exit(0);
  8. }
  9.  
  10. //here I write text to db.
  11.  
Jun 20 '15 #5

Dormilich
Expert Mod 5K+
P: 8,639
if there is no opening php tag (<?php) it will be treated as text, not as PHP script.

besides that JS console calls don’t make sense in a non-JS environment such as PHP.
Jun 20 '15 #6

P: 72
I did have the <?php ?> tags but haven't shown it to you and the console.log() are in javascript.

When I run this all I can see are the console.log() traces in js. Nothing else happens. Any other suggestions?


HTML
Expand|Select|Wrap|Line Numbers
  1. <input type="submit" name="btnSave" value="Save" onclick="xx()" />
  2.  

javascript
Expand|Select|Wrap|Line Numbers
  1. function xx()
  2. {
  3.     var request = new XMLHttpRequest();
  4.     console.log("11");
  5.     request.open("POST", "./test.php", true);
  6.     console.log("22");
  7.     console.log("33");
  8.     request.send('type=FIAT&model=500');
  9.     console.log("44");
  10. }
  11.  

test.php script
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. if (!isset($_POST['type'],$_POST['model'])) {
  4.     header('HTTP/1.0 400 Bad Request');
  5.     echo 'Missing "type" and/or "model".';
  6.     exit(0);
  7. }
  8.  
  9. // code to write some data to db which does not work
  10.  
  11. ?>
  12.  
Jun 21 '15 #7

Dormilich
Expert Mod 5K+
P: 8,639
since your AJAX code does not process the response (i.e. it only sends off the data) there is nothing further to happen.
Jun 21 '15 #8

P: 72
Hi Dormilich,

I have solved the problem. I have you to thank for pointing me in the right direction.

Here are the codes, in case someone else wants to do something similar.

javascript

Expand|Select|Wrap|Line Numbers
  1. //str_json = string in json format
  2. //e.g. str_json = '{"persons":[{"name":"xxx"},{"name":"yyy"}]}'
  3.  
  4. var request = new XMLHttpRequest();
  5. request.open("POST", "./test.php", true);
  6. request.setRequestHeader("Content-type", "application/json");
  7. request.send(str_json);
  8.  

test.php script
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. //retrieve json string
  4. $str_json = file_get_contents('php://input');
  5.  
  6. //convert string to json object
  7. $json = json_decode($str_json);
  8.  
  9. //loop through records in object
  10. foreach ($json->persons as $obj) {
  11.     //do something with the data
  12.     // eg save $obj->name to database
  13. };
  14. ?>
  15.  
Jun 23 '15 #9

Post your reply

Sign in to post your reply or Sign up for a free account.