Ajax – codewindow.in

Related Topics

AJAX

In this example, we first create a new XMLHttpRequest object and set the URL for the request. We then set the HTTP method to “GET” and the response type to “json”. We define the onload function to handle the response when it arrives.

When the request is sent with xhr.send(), the server will respond with JSON data, which will be automatically parsed by the browser due to the response type being set to “json”. In the onload function, we check the status of the response and handle any errors that may have occurred. If the response was successful, we can access the parsed JSON data using xhr.response and do something with it.

In this example, we’ve added an onerror function that handles network errors. If there’s a network error, the onerror function will be called, and we can handle the error by logging a message to the console.

In addition to handling network errors, we also handle HTTP errors in the onload function using a conditional statement. If the status is not 200, we log an error message to the console.

By handling errors or failed requests, we can ensure that our application behaves gracefully and provides useful feedback to the user when something goes wrong.

In this example, we use jQuery’s ajax() method to make a JSONP request to a different domain. We specify the URL for the request, the data type as “jsonp”, and the callback function name as “myCallback”. We define a success callback function to handle the response, which logs the JSON data to the console. We also define an error callback function to handle any errors that may occur during the request.

When the request is sent, the server responds with the JSON data wrapped in a function call to the callback function specified in the jsonpCallback parameter. The client-side JavaScript code then executes the callback function, passing the JSON data as an argument.

Overall, JSONP requests are a workaround for the same-origin policy enforced by modern browsers. However, they have some limitations, such as the inability to send POST requests and the potential security risks associated with executing remote code. As such, it is recommended to use JSONP only when necessary and to take appropriate security measures to protect against any potential security threats.

In this example, we retrieve data from the server in JSON format using AJAX and parse the response using the xhr.response property. We then update the relevant part of the web page by setting the innerHTML property of the HTML element with the id of “myDiv” to the value of the message property of the JSON data.

By using JSON with AJAX to update parts of a web page, we can create a more responsive and dynamic user interface without requiring the entire page to be reloaded, which can improve the user experience and reduce server load.

      

Popular Category

Topics for You

Go through our study material. Your Job is awaiting.

Categories