0

Due to some reason, I don't want to use jQuery in this JavaScript code:

$(function() {
  var url = ; //webhook URL here
  var content = "Hiii";
  var username = "Hi";
  $.post(url, {"content": content, "username": username});
  });

Is there any way to convert this into a code that doesn't require jQuery?

Adit Luhadia
  • 414
  • 8
  • 18

2 Answers2

2

First off, you can replace the $() with something like

document.addEventListener('DOMContentLoaded', (e) => {})

Secondly if you're only targeting newer browsers you can make use of fetch.

document.addEventListener('DOMContentLoaded', (e) => {
    var url = ; //webhook URL here
    var content = "Hiii";
    var username = "Hi";
    fetch(url, {
        method: 'POST',
        body: JSON.stringify({
            content: content,
            username: username,
        })
    });
});

or fallback to using plain XHR

var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.send({
        content: content,
        username: username,
});
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
  • Even if you aren't targeting only newer browsers, it's good to use the modern `fetch` method anyway, because Promises are wonderful - just use a polyfill. – CertainPerformance May 07 '18 at 04:44
  • Yeah, I'm assuming that OP want's to get rid of dependencies and if targeting older browsers then OP would need to add a polyfill. – Henrik Andersson May 07 '18 at 04:47
1
var content = "Hiii";
var username = "Hi";
var http = new XMLHttpRequest();
var url = "your API url";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send({"content": content, "username": username});

You can use XMLHttpRequest to make AJAX call like above.

Sagar Kharche
  • 2,577
  • 2
  • 24
  • 34