Wilker
Wilker

Reputation: 651

What is different between Fetch and jQuery Ajax post?

I tried it as jQuery Ajax for post it work correctly.

Data will be hardcoded, but the code is one dynamic value.

const data = {
  "retrieve": {
   "header": {
    "userID": 'xxx',
   },
   "body": {
     "code": code,
     "channel" : []  
   }
  }
}

I use web fetch API to post, it failed.

const response = await fetch('https://api', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
const result = await response.json();

Worked if I use $.ajax

const response = await $.ajax({
  method: 'POST',
  url: 'https://api',
  data: JSON.stringify(data),
  contentType: 'application/json'
})

Upvotes: 1

Views: 452

Answers (1)

Carsten Massmann
Carsten Massmann

Reputation: 28206

Both methods work, as you can see below. You forgot to add the .then(r=>r.json()) decoding bit after the fetch request:

const api="https://jsonplaceholder.typicode.com/users";
const data = {
  "retrieve": {
   "header": {
"userID": 'xxx',
   },
   "body": {
 "code": 4711,
 "channel" : [7,2,8,3]  
   }
  }
};

(async function(){
const res1 = await fetch(api, {
  method: 'POST',
  headers: {
'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
}).then(r=>r.json());
console.log("fetch:",res1);

const res2 = await $.ajax({
  method: 'POST',
  url: api,
  data: JSON.stringify(data),
  contentType: 'application/json'
});
console.log("jQuery Post:",res2);
})()
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

It is important, however, that your backend implements these steps in order to make the fetch POST work:

  • $json=file_get_contents(php://input); to receive the data in php
  • decode it using $data=json_decode($json);

Upvotes: 1

Related Questions