How to get Ajax URL in Javascript

To get the URL of an Ajax request in JavaScript, you can use the `XMLHttpRequest` object's `responseURL` property. Here is an example:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      console.log('Ajax request URL:', xhr.responseURL);
      // handle successful response
    } else {
      console.error('Ajax request failed with status', xhr.status);
      // handle error
    }
  }
};
xhr.open('GET', '/api/data', true);

xhr.send();

In this example, the `XMLHttpRequest` object is created and an `onreadystatechange` event handler is assigned. The handler function checks if the `readyState` property is 4, which means the request is complete. If the `status` property is 200, the response was successful, and the `responseURL` property is logged to the console. Otherwise, an error is logged.

You can use this code as a starting point and modify it to suit your specific Ajax request. Keep in mind that the `responseURL` property is only available after the request is complete, so make sure to access it inside the `onreadystatechange` event handler function.

Previous Post Next Post