Home > Back-end >  Can't find difference between Fetch and JQuery Ajax
Can't find difference between Fetch and JQuery Ajax

Time:05-17

I'm trying to do API request to a private API (hosted Itop), there's an example in the doc with JQuery Ajax but I did all my others calls with fetch and I wanted to do this one too but I don't get the right response.

The fetch method returns me a code 200 but with HTML instead of JSON (with a totally different content from the jQuery AJAX JSON one).

Here's the 2 functions:

// Code made by myself - don't get the right response
fetch(url, {
  method: "POST",
  headers: {
    "accept": "application/json",
  },
  mode: "cors",
  accept: "application/json, text/javascript, *!/!*; q=0.01",
  body: JSON.stringify({
    auth_user: user,
    auth_pwd: password,
    json_data: JSON.stringify({
      "operation": "list_operations",
    })
  })
})
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
// Code from the doc example - working
$.ajax({
  type: "POST",
  url: url,
  dataType: "json",
  data: {
    auth_user: user,
    auth_pwd: password,
    json_data: JSON.stringify({
      "operation": "list_operations"
    })
  },
  crossDomain: 'true'
})
  .then(
    function(data, textStatus, jqXHR) {
      console.log(data);
      console.log(textStatus);
      console.log(jqXHR);
    },
    function(jqXHR, textStatus, errorThrown) {
      console.debug(jqXHR);
      console.log("ERROR !!\n"  
        "status: "   textStatus   " ("   jqXHR.status   ")\n"  
        "error: "   errorThrown);
    }
  );

CodePudding user response:

In jQuery.ajax, when you pass data an object:

  • it will be encoded as application/x-www-form-urlencoded data
  • jQuery will include a Content-Type: application/x-www-form-urlencoded header

In fetch, you are passing body a string of JSON and fetch will be including a Content-Type: text/plain header.

So:

  • You are passing the wrong encoding of data
  • You are passing a Content-Type that doesn't match what the server expects or what your data actually is

Pass fetch a URLSearchParams object.

This will be encoded with the correct format and fetch will infer the correct content type from it.

  • Related