-2

I have this ajax request currently written in Jquery which I’d like to rewrite in pure javascript.

$.ajax({
    url: 'assets/php/sendToTelegram.php',
    type: 'POST',
    data: {
        myJson : localStorage.getItem('sendCart'),
        myFormJson : localStorage.getItem('arrayForm')
    }
});

Could anyone head me in the right direction?

Igor
  • 1
  • 1
    Use the `fetch` API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API – AKX Aug 23 '20 at 21:13
  • 1
    What have you tried? Have you looked into how jQuery `$.ajax` works, and how AJAX in javascript in general functions? – defines Aug 23 '20 at 21:15

1 Answers1

-2

Try this:

var xmlHttp = new XMLHttpRequest();
var json = {
    myJson: localStorage.getItem("sendCart"),
    myFormJson: localStorage.getItem("arrayForm")
}
xmlhttp.open("POST", "assets/php/sendToTelegram.php");
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify(json));

var json = {
    myJson: localStorage.getItem("sendCart"),
    myFormJson: localStorage.getItem("arrayForm")
}

Or with the Fetch API:

fetch("assets/php/sendToTelegram.php", {
    method: "POST",
    headers: {
        "Accept": "application/json, text/plain, */*",
        "Content-Type": "application/json;charset=UTF-8"
    },
    body: JSON.stringify(json)
});

The Fetch API is built in, so you don't need any libraries.

Nanoo
  • 1
  • 1
  • Nothing works. You made a small typo in the variable, but that's not the point. I do not understand why. "data" in jquery converts the data' to a query string, so does JSON using JSON.stringify. But still, something is not right – Igor Aug 24 '20 at 11:51