Make a POST with AJAX and JSON with pure Javascript

Asked

Viewed 2,865 times

2

I have the following code on jQuery

$.post('/privmsg?', {
    folder: 'inbox',
    mode: 'post',
    post: '1',
    username: 'Wagner',
    subject: 'Título',
    message: 'Mensagem'
});

I am studying Javascript, and would like to do the same effect with pure Javascript.

I did some research and learned to make requests with GET with AJAX, now I would like to know, how do this POST with pure Javascript?

1 answer

2


According to the website You Might Not Need jQuery, the syntax is this:

var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);

Have this site on your favorites forever you want to do something without jQuery. High up you choose whether you want to see version IE8+, IE9+ or IE10+.

The above version is IE8 compatible+.

  • I understand, but one thing I haven’t learned yet, is to pass the data (date) with JSON, you would have some example of how to do it?

  • 2

    What do you mean don’t use jQuery? Heresy! See: When is "use jQuery" not a Valid Answer to a Javascript Question? and this illustrative image. ;)

  • @waghcwb Simply create an array with {} like you did with jQuery

  • 2

    @Anthony So It Is. Benchmarks show that jQuery is slow, the problem is running out of browser compatibility and the ton of plugins that require jQuery.

  • I agree with Andrey, jQuery is not always feasible. Some projects are interesting to use, but others I myself do not see the need.. @Andrey, I did it this way, but no results: http://pastebin.com/TQd90hyw

  • @waghcwb Strange, I thought it was supposed to work.

  • @Andrey, I got a satisfactory result as follows: http://pastebin.com/AWyQqRq7 But I couldn’t do it with JSON. Weird..

  • I think as follows, in programmers we are masters, we have to know how to use the maximum resources and safely and efficiently. Work with both, run tests, check processes, look for forms you’ve already created. ’s website is also very rich with java script and other derivatives. = D

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.