0

I want to convert an ajax function from jquery to plain javascript

I have tried this but it doesn't react the same way as the url doesn't receieve the response when i try with my plain js

Here is my jquery

(function ($){
try{
        var event_category = 'a';
        var event_name = 'b';
        var page_url = 'c';
        var url = "myurl";
        var data = {
                event_category: event_category,
                event_name: event_name,
                page_url: page_url
        };
        $.ajax({
                crossDomain: true,
                type: "POST",
                url: "myurl",
                data : {event_category: event_category, 
                        event_name: event_name, 
                        page_url: page_url
                        }
        });
  } catch(e){console.log(e)};  
})(jQuery);

And here is what i tried

var event_category = 'action';
var event_name = 'click';
var page_url = 'test';
var request = new XMLHttpRequest();
request.open('POST', 'myurl');
request.setRequestHeader("Content-Type", "application/json; utf-8");
          params = {
              event_category: event_category, 
              event_name: event_name, 
              page_url: page_url
              } 
request.send(JSON.stringify(params));

not sure what i should change

Edit:

Base on one of the comments i check the network data on the developer tools The jquery is having a response on the header of this format enter image description here enter image description here

But the javascript is sending the data is this format

enter image description here

Basically the javascript is not sending it on a url params format. Not sure how to force it on how to send it on the same format

5
  • are you getting any error? Commented Aug 4, 2019 at 4:07
  • no error, in fact i have a nodejs server that receive the information when I do it on jquery but if I do it in plain javascript it doesn't receive it, so I am wondering if the conversion i have done is missing something. Commented Aug 4, 2019 at 4:11
  • so basically the network call itself is not triggering isn't Commented Aug 4, 2019 at 4:18
  • Open the Network tab in your browser's developer tools. Run the working jQuery code and see what shows up for the request URL and headers. Copy them into a text editor or visual compare program. Now do the same thing with your new JavaScript code. You should be able to see right away what is different between the two. Commented Aug 4, 2019 at 4:31
  • @MichaelGeary thanks that is putting me on the good path. The jquery gives this data back format event_category=a&event_name=b&page_url=c but the javascript gives this {"event_category":"d","event_name":"e","page_url":"f"} Commented Aug 4, 2019 at 4:36

1 Answer 1

1

Is there any reason not to use the fetch API (it can be polyfilled in crappy browsers...)?

const ajax = async function(url, data) {
  try {

    const response = await fetch(url, {
      credentials: 'include', // like jQuery $.ajax's `crossDomain`
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      // this mimics how jQuery sends POST data as querystring by default
      body: Object.entries(data).map(([key, val]) => `${key}=${val}`).join('&'),
    });

    data = await (
      response.headers.get('content-type').includes('json')
      ? response.json()
      : response.text()
    );

    console.log(data);

    return data;
  } catch(err) { console.log(err) };
}

ajax('myurl', {
  event_category: 'a', 
  event_name: 'b', 
  page_url: 'c',
});
Sign up to request clarification or add additional context in comments.

2 Comments

No @exside I am ok to use the fetch API and your solution is elegant. But it still doesn't fix the problem. I edited with some images, If we look at the network data the header response from the jquery and the javascript is not the same but I cannot see how to make it similar
@I need data check the updated snippet above, the part with Object.entries(), it should mimic the way jQuery sends POST data by default (as querystring) and replaces the JSON.stringify() that was there before! If you can't use Object.entries() there are a bit less concise ways of doing the same with Object.keys() which has better browser support.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.