S
S
Sergey2020-05-11 14:44:01
JavaScript
Sergey, 2020-05-11 14:44:01

How to rewrite ajax request to pure js (XMLHttpRequest)?

How to rewrite this code to vanilla js? In particular, I'm interested in how and in what form to transfer the data object using XMLHttpRequest with the POST method.

$.ajax({
  method: 'POST',
  url: url,
  dataType: 'json',
  data: {
    search: value
  },
  success: function(data) {
    console.log(data);
  }
});

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ivan Ivanov, 2020-05-11
@maksim_fix

https://good-code.ru/ajax-zapros/
Well, yes, of course, we are not too lazy to google for you

A
abberati, 2020-05-11
@abberati

Use fetch, forget about xhr

D
Dima Polos, 2020-05-11
@dimovich85

var data = JSON.stringify({ search: value });
var xhr = new XMLHttpRequest();
xhr.open( 'POST', url );
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.send( data );
xhr.addEventListener( 'readystatechange', function(){
  if( xhr.readyState !== 4 ) return;
  if( xhr.status === 200 ){
    console.log( xhr.responsetext ); // ответ в консоль
  } else {
    console.log( xhr.statusText );
  }
});

||
async () => {
const req = await fetch( url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  },
  body: JSON.stringify({ search: value })
});
if(  req.ok){
  const res = await req.json(); // .text(), .blob()...
  console.log( res ); // ответ в консоль
}
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question