$ajax jquery code example
Example 1: jquery ajax
$.ajax({
url: url,
dataType: "json",
type: "Post",
async: true,
data: { },
success: function (data) {
},
error: function (xhr, exception) {
var msg = "";
if (xhr.status === 0) {
msg = "Not connect.\n Verify Network." + xhr.responseText;
} else if (xhr.status == 404) {
msg = "Requested page not found. [404]" + xhr.responseText;
} else if (xhr.status == 500) {
msg = "Internal Server Error [500]." + xhr.responseText;
} else if (exception === "parsererror") {
msg = "Requested JSON parse failed.";
} else if (exception === "timeout") {
msg = "Time out error." + xhr.responseText;
} else if (exception === "abort") {
msg = "Ajax request aborted.";
} else {
msg = "Error:" + xhr.status + " " + xhr.responseText;
}
}
});
Example 2: $.ajax javascript
$.ajax({
url: 'https://example.com/your-page',
success:function(data){
},
error:function(){
alert('An error was encountered.');
}
});
Example 3: jquery ajax
$.ajax({
url : "file.php",
method : "POST",
data: {
action : action ,
key_1 : value_key_1,
key_2 : value_key_2
}
})
.fail(function() { return false; })
.done(function(data) {
console.log(data);
});
Example 4: ajax jquery php
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
</head>
<body>
<form id="loginform" method="post">
<div>
Username:
<input type="text" name="username" id="username" />
Password:
<input type="password" name="password" id="password" />
<input type="submit" name="loginBtn" id="loginBtn" value="Login" />
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#loginform').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'login.php',
data: $(this).serialize(),
success: function(response)
{
var jsonData = JSON.parse(response);
if (jsonData.success == "1")
{
location.href = 'my_profile.php';
}
else
{
alert('Invalid Credentials!');
}
}
});
});
});
</script>
</body>
</html>
Example 5: $.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>