Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ajax POST to php

I can't seem to figure out how to use ajax to post. I made a silly form to try it out and even after having cut it all the way down to just two values, still can't get anything to work. My html is this:

<html>
<head>
<script type="text/javascript" src="j.js"></script>
<title>Test this<
<body>/title>
</head>
<form name="testForm" onsubmit="postStuff()" method="post">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="submit" value="Submit Form" />
</form>
<div id="status"></div>
</body>
</html>

Then, my external javascript is just a single function so far:

function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "processForm.php";
var fn = document.getElementById("fname").value;
var ln = document.getElementById("lname").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
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 PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}

While my php just echoes the stuff back:

<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo $firstname ." - ". $lastname ."<br />";
?>

I can't find anything wrong in firebug or in chrome's toolsy thingies.. Can anybody who me what I'm doing wrong?

like image 749
include 'breakDance' Avatar asked Sep 19 '13 23:09

include 'breakDance'


People also ask

Can you use AJAX with PHP?

Start Using AJAX Today In our PHP tutorial, we will demonstrate how AJAX can update parts of a web page, without reloading the whole page. The server script will be written in PHP. If you want to learn more about AJAX, visit our AJAX tutorial.

Can AJAX use post?

post() makes Ajax requests using the HTTP POST method. The basic syntax of these methods can be given with: $. get(URL, data, success); —Or— $.

How pass data from JavaScript to PHP using AJAX?

ajax({ type: "POST", url: 'logtime. php', data: "userID=" + userID, success: function(data) { alert("success!"); } }); }); }); <? php //logtime. php $uid = isset($_POST['userID']); //rest of code that uses $uid ?>

What is AJAX post method?

post() method requests data from the server using an HTTP POST request. Syntax: $. post(URL,data,callback);


1 Answers

The whole problem is caused by the fact that you are both submitting the form and performing an AJAX call! status is for sure updated, but in the same moment the page is refreshed (notice that the <input>-values disappear)

Simply avoid the form submit by altering the markup,

<form name="testForm" action="" method="">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="button" value="Submit Form" onclick="postStuff();" />

and your code works. Or dont use a form at all. It is to no use when you are AJAXing anyway.


update

I reproduced the whole scenario before answering :

xhr.html

<html>
<head>
<title>Test this</title>
</head>
<body>
<form name="testForm" action="" method="">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="button" value="Submit Form" onclick="postStuff();" />
</form>
<div id="status"></div>

<script>
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "xhr.php";
var fn = document.getElementById("fname").value;
var ln = document.getElementById("lname").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
    console.log(hr);

    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
        document.getElementById("status").innerHTML = return_data;
    }
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</body>
</html>

xhr.php

<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo $firstname ." - ". $lastname ."<br />";
?>
like image 73
davidkonrad Avatar answered Sep 20 '22 22:09

davidkonrad