Answers for "how ajax works"

5

ajax call

$.ajax({
        url: "Url",
        dataType: "json",
        type: "Post",
        async: true,
        data: {"Key":value,"Key2":value2},
        success: function (data) {
                
        },
        error: function (xhr, exception, thrownError) {
            var msg = "";
            if (xhr.status === 0) {
                msg = "Not connect.\n Verify Network.";
            } else if (xhr.status == 404) {
                msg = "Requested page not found. [404]";
            } else if (xhr.status == 500) {
                msg = "Internal Server Error [500].";
            } else if (exception === "parsererror") {
                msg = "Requested JSON parse failed.";
            } else if (exception === "timeout") {
                msg = "Time out error.";
            } else if (exception === "abort") {
                msg = "Ajax request aborted.";
            } else {
                msg = "Error:" + xhr.status + " " + xhr.responseText;
            }
            if (callbackError) {
                callbackError(msg);
            }
           
        }
    });
Posted by: Guest on January-06-2021
0

ajax programming

// BEGIN
// JavaScript example
// An example of a simple Ajax request using the GET method, written in JavaScript.

// get-ajax-data.js:

// This is the client-side script.
// Initialize the HTTP request.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'send-ajax-data.php');

// Track the state changes of the request.
xhr.onreadystatechange = function () {
	var DONE = 4; // readyState 4 means the request is done.
	var OK = 200; // status 200 is a successful return.
	if (xhr.readyState === DONE) {
		if (xhr.status === OK) {
			console.log(xhr.responseText); // 'This is the output.'
		} else {
			console.log('Error: ' + xhr.status); // An error occurred during the request.
		}
	}
};

// Send the request to send-ajax-data.php
xhr.send(null);
// END

// BEGIN
// send-ajax-data.php:
<?php
// This is the server-side script.
// Set the content type.
header('Content-Type: text/plain');

// Send the data back.
echo "This is the output."; ?>
// END 
  
// BEGIN  
// Fetch is a new native JavaScript API  
fetch('send-ajax-data.php')
    .then(data => console.log(data))
    .catch (error => console.log('Error:' + error));
// END

// BEGIN
// ES7 async/await example:  
async function doAjax() {
    try {
        const res = await fetch('send-ajax-data.php');
        const data = await res.text();
        console.log(data);
    } catch (error) {
        console.log('Error:' + error);
    }
}

doAjax();
// END
Posted by: Guest on December-19-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language