0

I am trying to convert an ajax request to vanilla JavaScript

$.ajax({
    url: 'http://foo.bar/hi',
    type: 'post',
    data: {args: params},
    success: function(data){
    },
});

I have tried the following

var xhr = new XMLHttpRequest();
var data = {args: params};
xhr.open("POST", 'http://foo.bar/hi', true);
xhr.send(data);

I am connecting to an external device with a web based interface and not getting any response on the device. It is as if I never sent a request

Theoretically, the original ajax request will perform the action, however, there is a problem with the jQuery portion of my program so I am trying to convert it to vanilla javascript and bypass the jQuery

14
  • What is the response you're getting ? Commented Jul 17, 2018 at 22:39
  • Please read the help, and especially how to create a minimal reproducible example - "not getting the response I am expecting" is not a clear problem statement. Commented Jul 17, 2018 at 22:41
  • You have not designated an event handler for onreadystatechange so how are you getting any sort of response? Commented Jul 17, 2018 at 22:42
  • Please read the docs on XMLHttpRequest. You don’t have anything in your jQuery success handler, and you don’t have the equivalent of the success callback in your XHR approach. Commented Jul 17, 2018 at 22:44
  • 1
    ajax and jquery are not the same thing - you are not "tearing out the ajax" you are still using ajax, just doing it with vanilla javascript instead of with jquery. Do you get any response attaching to the device with a web browser? How about a command-line curl? - since you have no response handlers defined, either in your jquery or your vanilla version, you can't even accurately say that you aren't getting a response. Commented Jul 17, 2018 at 22:50

1 Answer 1

3

Using fetch:

function json(response) {
  return response.json();
}

function handleErrors(response) {
  if(!response.ok) {
    throw new Error("Request failed " + response.statusText);
  }
  return response;
}

fetch("http://url.com/endpoint", {
  method: "POST",
  body: {
    myKey: "my value",
    another: "hihihi"
  }
}).then(handleErrors).then(json).then(function(data) {
  console.log(JSON.stringify(data));
}).catch(function(err){
  console.log("err" + err);
})
Sign up to request clarification or add additional context in comments.

1 Comment

It is giving me alot of hate about using those =>. Plus, I assume that I put the {args: params} in the commented section?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.