$ .Ajax () data
I have div tags which onchange I want to insert a new value into my database. As people say I use $.ajax POST
to insert. Since I am new to JQuery and Ajax, I don’t know what actually this data and msg in $ .ajax () .. Please explain how to insert my value into the 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);
}
})
});
a source to share
When you say "Insert my value into the database asynchronously .... (on the fly)" I hope you mean "insert into database, period".
A POST request (either $ .ajax () or $ .post ()) can only send your data to the client on your server.
You will need to write server side code to perform the insert.
Suppose you have a script on your server called do-insertion.php that can insert data into the database if the POST "name" and "location" variables are sent to it.
So, you should write (I think you already know this):
$.post( "do-insertion.php",
{"name":"John", "location":"SF"},
function(data){alert("got response="+data);} );
What matters is that you write in server-side code. I am assuming PHP, so you would use the mysql API for php and insert your data into your database.
You can of course read the sent data as
$name=$_POST['name'];
$location=$_POST['location'];
This only applies to PHP; other languages will have other ways of doing everything.
By the way, did you mean something special "asynchronously .... (on the fly)" in your question?
a source to share
The data attribute must 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, just fetch the message parameters as usual. For example, in php you would do something like $ _POST ("name") and $ _POST ("location"). The PHP generated response will display as msg. This way, you can simply echo "Save operation successfully" to your PHP script after your insert is done.
a source to share