0

Does someone knows jquery and can help me convert this ajax to js fetch ? Unfortunately, I don't know jquery and I need to convert this into js fetch.

function ajaxLogoutDetailsApi() {
  $.ajax({
    type: "GET",
    url: "OIDCGetLogoutDetails",
    async: false,
    cache: false,
    data: "json",
    success: function (data, status, xhr) {
      data = data.replace('\/\*', '');
      data = data.replace('\*\/', '');
      var dataJson = JSON.parse(data);
      if (dataJson.logoutUrl != null) {
        document.location.href = dataJson.logoutUrl;
      }
    },
    error: function (xhr, status, err) {
      console.log("error in ajaxLogoutDetailsApi");
    }
  });
}

Appreciate every hint.

Christian
  • 53
  • 1
  • 8
  • 1
    Have you [looked at the Fetch API documentation](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)? If you know what the code is meant to do you should be able to extrapolate that into some fetch code (maybe also have a look at [`async/await`](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises#async_and_await) too. – Andy Jul 04 '22 at 15:05
  • @Andy the problem is that I don't know Jquery, not fetch.. that's why I'm asking. If you know jquery, can you convert this into fetch ? – Christian Jul 04 '22 at 15:41
  • What is the JSON sent from the server? Can you add that to the question? I don't really understand what those `replace` lines are doing. – Andy Jul 04 '22 at 15:53
  • @Andy Unfortunately, I don't have the JSON.. it's a big script and I have only this part of the script that I need to convert from Jquery ajax to Fetch – Christian Jul 04 '22 at 16:56

1 Answers1

1

I was going to use async/await but since there's that odd replacing before the JSON gets parsed I've reverted to old-school fetch with "thenables".

function ajaxLogoutDetailsApi() {
  
  const endpoint = 'OIDCGetLogoutDetails';
  
  // Fetch the JSON
  fetch(endpoint)

    // This is returned as the first argument
    // of "then"
    .then(json => {

      // Weird replacement stuff
      const updated = json
        .replace('\/\*', '')
        .replace('\*\/', '');

      // Parse the JSON
      const data = JSON.parse(updated);

      // Set the new page if the condition is met
      if (data.logoutUrl) {
        window.location.href = data.logoutUrl;
      }

    })

    // Catch any errors
    .catch(error => {
      console.error('Error:', error);
    });

}
Andy
  • 61,948
  • 13
  • 68
  • 95
  • regarding ```async: false```, I've seen that is deprecated anyway on ajax, but for ```cache: false``` Do I need to change something here on the fetch? Do I need to put a header or something like this? – Christian Jul 06 '22 at 10:14
  • 1
    https://stackoverflow.com/questions/29246444/fetch-how-do-you-make-a-non-cached-request @Christian10 – Andy Jul 06 '22 at 10:16