출처 : http://hayageek.com/jquery-ajax-post/
1.JQuery Ajax POST example using $.ajax method
Sample POST request look like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | var formData = "name=ravi&age=31" ; //Name value Pair or var formData = {name: "ravi" ,age: "31" }; //Array $.ajax({ url : "AJAX_POST_URL" , type: "POST" , data : formData, success: function (data, textStatus, jqXHR) { //data - response from server }, error: function (jqXHR, textStatus, errorThrown) { } }); |
To send, POST request you need to set type = “POST” in AJAX settings.
formData: can be an array or name value pairs.
success: callback function is called when the AJAX POST is successful
error: callback function is called when the AJAX POST is failed
Note: To handle JSON data, set dataType=”json”
2.jQuery Ajax POST example using $.post method
$.post() method is shortcut of .ajax() method, so using $.post() method we can send AJAX POST requests.
jQuery.post() Syntax:
1 | var jqXHR = jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] ); |
Valid AJAX POST Requests are:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | //request with URL,data,success callback $.post( "AJAX_POST_URL" , {name: "ravi" ,age: "31" }, function (data, textStatus, jqXHR) { //data: Received from server }); //request with URL,success callback $.post( "AJAX_POST_URL" , function (data) { //data: Received from server }); //request with only URL $.post( "AJAX_POST_URL" ); |
$.post method is not having any callback method to handle errors. But we can use jqXHR fail() callback method to handle the error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | $.post( "AJAX_POST_URL" , {username: "ravi" ,pass: "124" ,submit: true }, function (data, textStatus, jqXHR) { //data - response from server }).fail( function (jqXHR, textStatus, errorThrown) { alert(textStatus); }); //With jqXHR callbacks .done() and .fail() $.post( "AJAX_POST_URL" , {username: "ravi" ,pass: "124" ,submit: true }).done( function (data, textStatus, jqXHR) { }).fail( function (jqXHR, textStatus, errorThrown) { alert(textStatus); }); |
3.AJAX Form POST Example
Below is the sample Form used for POST.
1 2 3 4 5 6 7 | < form name = "myform" id = "myform" action = "ajax-post.php" > User: < input type = "text" value = "Ravishanker" name = "user" /> < br /> Password: < input type = "password" name = "password" value = "abcdefgh" /> < input type = "hidden" name = "xyz" value = "123" /> < input type = "hidden" name = "submit" value = "true" /> </ form > |
Using jQuery.serialize() or jQuery.serializeArray() API, Form data can be serialized. Below example shows how to POST Form data asynchronously.
1 2 3 4 5 6 7 8 9 10 11 12 | //var formData = $("#myform").serialize(); //or var formData = $( "#myform" ).serializeArray(); var URL = $( "#myform" ).attr( "action" ); $.post(URL, formData, function (data, textStatus, jqXHR) { //data: Data from server. }).fail( function (jqXHR, textStatus, errorThrown) { }); |