Ajax posting to PHP
Posted
by
JQonfused
on Stack Overflow
See other posts from Stack Overflow
or by JQonfused
Published on 2011-02-14T07:16:08Z
Indexed on
2011/02/14
7:25 UTC
Read the original article
Hit count: 129
Hi guys,
I'm testing a jQuery ajax post method on a local Apache 2.2 server with PHP 5.3 (totally new at this). Here are the files, all in the same folder.
html body (jQuery library included in head):
<form id="postForm" method="post">
<label for="name">Input Name</label>
<input type="text" name="name" id="name" /><br />
<label for="age">Input Age</label>
<input type="text" name="age" id="age" /><br />
<input type="submit" value="Submit" id="submitBtn" />
</form>
<div id="resultDisplay"></div>
<script src="queryRequest.js"></script>
queryRequest.js
$(document).ready(function(){
$('#s').focus();
$('#postForm').submit(function(){
var name = $('#name').val();
var age = $('#age').val();
var URL = "post.php";
$.ajax({
type:'POST',
url: URL,
datatype:'json',
data:{'name': name ,'age': age},
success: function(data){
$('#resultDisplay').append("Value returned.<br />name: "+data.name+" age: "+data.age);
},
error: function() {
$('resultDisplay').append("ERROR!")
}
});
});
});
post.php
<?php
$name = $_POST['name'];
$age = $_POST['age'];
$return = array('name' => $name, 'age' => $age);
echo json_encode($return);
?>
After inputting the two fields and pressing 'Submit', the success method is called, text appended, but the values returned from ajax post are undefined.
And then after less than a second, the text fields are emptied, and the text appended to the div is gone. Doesn't seem like it's a page refresh, though, since there's no empty page flash.
What's going on here? I'm sure it's a silly mistake but Firebug isn't telling me anything.
© Stack Overflow or respective owner