AJAX Post form Variables to PHP Page

ajax, javascript, php

Solution

ajaxRequest.open("POST", "process.php?name="+name+"&email="+email, true);
ajaxRequest.send(null);

That's not posting the variables. Here you're sending them as GET parameters, with an empty body for your POST request. Instead, use

ajaxRequest.open("POST", "process.php", true);
ajaxRequest.send("name="+name+"&email="+email);

or even better

ajaxRequest.open("POST", "process.php", true);
ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxRequest.send("name="+encodeURIComponent(name)+"&email="+encodeURIComponent(email));

Problem

I have a form that executes an AJAX function to submit form values to a PHP page. The PHP page just responds by echoing out the variables in a DIV. It works with GET method, but I can't get it working with POST. ``` <html> <body> <script language="javascript" type="text/javascript"> <!-- //Browser Support Code function ajaxFunction(){ var ajaxRequest; try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Browser Not Supported"); return false; } } } // Get Response ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ document.getElementById("response").innerHTML = ajaxRequest.responseText; } } var name=document.getElementById("name").value var email=document.getElementById("email").value ajaxRequest.open("POST", "process.php?name="+name+"&email="+email, true); ajaxRequest.send(null); } //--> </script> <form name='Form1'> Name: <input type='text' name='name' id="name"/> <br /> Email: <input type='text' name='email' id="email"/> <br /> <input type="button" value="Submit" onClick="ajaxFunction();"> </form> <div id="response"> </div> </body> </html> ``` And the php page, process.php ``` <?php echo date("H:i:s"); echo "<br/>"; // echo "Post Variables: ".$_POST['name']." ".$POST['email']; old code echo "Post Variables: ".$_POST['name']." ".$_POST['email']; echo "<br/>"; echo "Get Variables: ".$_GET['name']." ".$_GET['email']; ?> ``` The response I get is: 11:32:05 Post Variables: Get Variables: name entered email entered So i'm pretty sure it's to do with the variable being passed from PHP to Javascript. Many thanks.

Original source