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: how to make ajax request javascript
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
<html>
<body>
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();
}
</script>
</body>
</html>
Example 5: js ajax
function _GET_REQUEST(url, response) {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
response(this.responseText);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function _POST_REQUEST(url, params, response) {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
response(this.responseText);
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(params);
}
_GET_REQUEST('http://someurl', (response) => {
});
_POST_REQUEST('http://someurl', 'paramx=y', (response) => {
});
Example 6: JS ajax
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));