Thursday, April 9, 2009

Jquery ajax post form

How to post some data using jquery and ajax, and get the response in a div.

First you'll need jquery library.

Then you'll need a html form:


<script type="text/javascript" src="jquery.js></script>
<script type="text/javascript">

$(document).ready(function() {

$("#btn").click(function(){

$.post("ajax.php",{
myfield: $("#myfield").val(),
action: "check"
}, function(msg) {
$("#msg").empty();
$("#msg").html(msg);
});

});

});

</script>

<form action="" method="post">
<input type="text" name="myfield" id="myfield" />
<input type="button" name="btn" id="btn" value="Submit" />
</form>

<div id="msg"></div>

This file it's called index.html


And then the file ajax.php, will take the parameters sent through ajax, and echo the response:

$myfield = $_POST['myfield'];
echo $myfield;

This line returns the value in #msg div.

So there you go, ajax with jquery is pretty simple, you can see here how to send parameters through ajax, and how to get the response into a div. This code can be used to validate user input, emails, number, etc. Instead of $myfield you can echo an error message, or a success message, your choice.

No comments: