-1

How can I send json in body request with ajax? Only use Javascript and do not use jQuery !!! Someone can help I remind you not to use jQuery!!!

Mario.Ds
  • 23
  • 3

3 Answers3

0

You can create function that work like jquery ajax request.

function AJAX(url, success, async) {
    if (window.XMLHttpRequest) {
        var request = new XMLHttpRequest;
    } else {
        // IE6 and IE5 (unnecessary)
        var request = new ActiveXObject("Microsoft.XMLHttp");
    }
    if (async) request.onReadyStateChange = function() {
        if (request.readyState == 4) {
            success(request.status, request.responseText);
        }
    };
    request.open("GET", url, async);
    request.send();
    if (!async) success(request.status, request.responseText);
}
Maksym Sivash
  • 63
  • 1
  • 6
0

I don't got the point. If all you need is to request an URL and send JSON body, you can achieve it simply with XMLHttpRequest :

var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log('RESPONSE');
    }
};
var data = {"email": "hey@mail.com", "password": "101010"}; // JSON YOU SEND
xhr.send(JSON.stringify(data));

Original answer here : Sending a JSON to server and retrieving a JSON in return, without JQuery

Robin Michay
  • 679
  • 3
  • 4
0

You can try something like that

var xhr = new XMLHttpRequest;
xhr.open('POST', '/your_url');
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.status == 200) {
    // success
    console.log(xhr.responseText); 
  } else {
    // other
    console.log('Error, status code = ' + xhr.status + ', response = '+xhr.responseText);
  }
};
var payload = JSON.stringify({param1: 1, param2: 'hello'});
xhr.send(payload);
Reflective
  • 3,854
  • 1
  • 13
  • 25