Jump to content

JS, PHP Communication via Ajax


j.silver

Recommended Posts

Dear all, some help will be highly appreciated. I have a JS code that has a form for first name and last name. Ajax then communicates with a PHP script and gets back a message from PHP that thanks the user by stating the first and last names of user. The PHP message will show at the bottom of the form without having the page to refresh. The PHP message ensures a successful communication between JS and PHP via Ajax. The JS script:<!DOCTYPE html><html lang="en"><head><script>function ajax_post() {//create our XMLHttpRequest objectvar hr = new XMLHttpRequest();//create some variables we need to send to our PHP filevar url = "my_parse_file.php"; //name of the PHP parsing script.var fn = document.getElementById("first_name").value;var ln = document.getElementById("last_name").value;var vars = "firstname="+fn+"&lastname="+ln; //variables to be sent to PHP scritp.hr.open("post", url, true); //using the open method on XMLHttpRequest object.hr.setRequestHeader("Content_type", "application/x-www-form-urlencoded");// access the onreadystatechange event for the XMLHttpRequest object.hr.onreadystatechange = function() {if (hr.readyState == 4 && hr.status == 200) {var return_data = hr.responseText;document.getElementById("status").innerHTML = return_data;}}// send the data to PHPhr.send(vars);document.getElementById("status").innerHTML = "processing...";}</script></head><body><h2>Ajax Post to PHP and Get Return Data</h2>Your First Name: <input id="first_name" name="first_name" type="text" /><br /><br />Your Last Name: <input id="last_name" name="last_name" type="text" /><br /><br /><input name="myBtn" type="submit" value="Submit Data" onClick="javascript:ajax_post();" /><br /><br /><div id="status"></id></script></body></html>The PHP script:<?phpecho 'Thank you ' . $_POST['firstname'] . ' ' . $_POST['lastname'] . ',says the PHP file.';?>I receive no message back from the PHP script as desired, only the word "processing...".As part of the debugging, I inserted:document.write("Ready State = "+hr.readyState + " Ready Status = "+hr.status);after: hr.onreadystatechange = function() {The message I got was: Ready State = 4 Ready Status = 0.I thought it meant changing the 200 to 0, but still didn't work.My system: Apache, PHP 5.5.9, Windows 64-bit OS, Windows 7

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...