ajax methods jquery code example
Example 1: make ajax calls with jQuery
$.ajax({
url: "example.php?firstParam=Hello&secondParam=World",
dataType: 'json',
timeout: 2000
}).done(function (data, textStatus, jqXHR) {
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log("jqXHR:" + jqXHR);
console.log("TestStatus: " + textStatus);
console.log("ErrorThrown: " + errorThrown);
});
var formData = {name: "John", surname: "Doe", age: "31"};
$.ajax({
url: "example.php",
type: "POST",
data: formData,
timeout: 2000,
async: false,
success: function (data, textStatus, jqXHR) {
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("jqXHR:" + jqXHR);
console.log("TestStatus: " + textStatus);
console.log("ErrorThrown: " + errorThrown);
}
});
$.ajax({
url: "api.php?action=getCategories",
dataType: 'json',
timeout: 2000,
success: function (result, textStatus, jqXHR) {
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("jqXHR:" + jqXHR);
console.log("TestStatus: " + textStatus);
console.log("ErrorThrown: " + errorThrown);
}
});
Example 2: $.ajax({
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.post demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form action="/" id="searchForm">
<input type="text" name="s" placeholder="Search...">
<input type="submit" value="Search">
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
$( "#searchForm" ).submit(function( event ) {
event.preventDefault();
var $form = $( this ),
term = $form.find( "input[name='s']" ).val(),
url = $form.attr( "action" );
var posting = $.post( url, { s: term } );
posting.done(function( data ) {
var content = $( data ).find( "#content" );
$( "#result" ).empty().append( content );
});
});
</script>
</body>
</html>