I have some div tags which onchange I want to insert the new value into my database. As people suggest, I'm using $.ajax POST
to insert. Since I'm new to JQuery and Ajax, I don't what actually that data and msg in $.ajax()..Please explain how to insert my value into a database asynchronously (on the Fly)
$(".div"+increment).change(function(){
$.ajax({
type: "POST",
url: "./server",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg);
}
})
});
The data attribute should be an object
$(".div"+increment).change(function(){
$.ajax({
type: "POST",
url: "./server",
data: {name:"John", location:"Boston"},
success: function(msg){
alert( "Data Saved: " + msg);
}
})
});
On the server-side simply retrieve post parameters as usual. For example, in php you would do something like $_POST("name") and $_POST("location"). Response generated by PHP would appear as msg. So you can just echo "Save operation succeeded" in your PHP script after executing your insert.
You might consider using $.post instead. It is easier to handle. The drawback is that it doesn't offer error notification.
When you say "insert my value to database asynchronously....(on the Fly)", I hope you mean "insert into the database, period".
The POST request (either by $.ajax() or by $.post() ) can only send your data from the client to you server.
You will need to write server side code to do the insertion.
Lets say you have a script called "do-insertion.php" on your server that can insert data into a database, if the POST variables "name" and "location" are submitted to it.
So you would write (I guess you already know this):
$.post( "do-insertion.php", {"name":"John", "location":"SF"}, function(data){alert("got response="+data);} );
The important thing is what you write on the server side code. I assume PHP, so you would use the mysql API for php and insert your data into your database.
ofcourse, you can read the submited data as
$name=$_POST['name'];
$location=$_POST['location'];
This applies only to PHP; other languages will have other methods to do everything.
By the way, did you mean anything special by the "asynchronously .... (on the fly)" in your question?