Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
Can't find difference between Fetch and JQuery Ajax

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);
    }
  );
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!