Reputation: 3951
I am writing some functionality using jQuery that i normally handle with a page refresh/form submission.
Basically I am submitting a form using jQuery's ajax.
<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#show-comment-form").click(function(event){
var ret = $.post("post.php", $("#comment-form").serialize(), "", "html");
$("#theComment").html("<strong>" + ret +"</strong>");
});
});
</script>
</head>
<body>
Testing Stuff
<br /><a href="#" id="show-comment-form">Insert New Message</a><br />
<div id="comment-form">
<form name="form" id="form">
<span>Enter Your Question Here</span>
<textarea id="comment" name="comment"></textarea>
</form>
</div>
<p id="theComment">
avsailable
</p>
</body>
</html>
The object returned is an XMLHttpRequest. Do I manipulate this object or is it something that I probably do not need.
My problem is I want to have a user post a response using a form on a webpage but do it without a page reload and prepend html onto the beginning of all the other user responses. The page the form is posted to prints out some HTML but I cannot get that HTML to appear on the page because the response is a XMLHttpRequest object. I'm kind of lost. Can someone point me in the right direction?
Upvotes: 0
Views: 126
Reputation: 828170
You have to use the callback function parameter:
$("#show-comment-form").click(function(event){
$.post("post.php", $("#comment-form").serialize(), function(ret){
$("#theComment").html("<strong>" + ret +"</strong>");
}, "html");
});
That function will be executed when the asynchronous request ends, and its first parameter is the data returned from the server.
Upvotes: 2
Reputation: 186762
Specify a function as a third parameter and the data should be returned in a callback:
var ret = $.post("post.php", $("#comment-form").serialize(), function(data) { $(data).appendTo('body'); });
You shouldn't need to interact with the XHR object. For more info:
http://docs.jquery.com/Ajax/jQuery.post
Upvotes: 2