473,405 Members | 2,185 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

XMLHttpRequest.Open not working

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
8 2124
Dormilich
8,658 Expert Mod 8TB
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
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
8,658 Expert Mod 8TB
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
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
8,658 Expert Mod 8TB
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
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
8,658 Expert Mod 8TB
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
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

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

Similar topics

2
by: Unknown User | last post by:
I am trying to implement XMLHttpRequest to a new website, but when I include HTML, the code appears as is, instead of the formated HTML. Please have a look and click the 1st link ("L'Association")...
8
by: jason.lucey | last post by:
Hi, I need some help figuring this out. I cannot get the xmlhttprequest object to return responseXML or getAllResponseHeaders. responseText works fine, but i'd rather use xPath than regular...
1
by: vikas.khengare | last post by:
Hi Friends.... I have AJAX code which giving "Permission denied to call method XMLHttpRequest.open" error. This error fired by FireFox 1.0 and IE 6 and with Tomacat 5.x. This code work very...
1
by: Charlie | last post by:
I am trying to make an XMLHttpRequest which violates the default "same- origin"policy in Firefox. I checked the archives and found a method that should work but it does not. Below is the test code...
1
by: shotokan99 | last post by:
i have this function: function doit(){ if (dow.cpmake.selectedIndex==1 && dow.cpmodel.selectedIndex==0){ window.open('http://www.mysite.com/mycab.cab'); } } using ie this using will...
2
by: johnnyb1726 | last post by:
Can someone please tell me why I get a "Permission denied to call method XMLHttpRequest.open" error? Here is my script: var xmlHttp function runSearch(element){ xmlHttp=GetXmlHttpObject();...
8
by: sbettadpur | last post by:
hello I am using xmlHttpRequest method in my application, this method is giving problem in the following browsers 1) Internet Explorer 7 2) Mozila Firefox(2.0.0.16) I got solution for...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.