czupe
czupe

Reputation: 4919

Is there a possibility to use POST in an Ajax call instead of GET (Only Javascript solution)

In this JavaScript example and all of what i could found in the web:

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();

The JavaScript example codes using always GET...

I know JQuery can simplicate things very much, and i know it can be a one liner with JQuery, but probably i do not want to use JQuery for this (because of the size overhead of jquery.js)

So the question is easy, is there an option to use POST vs GET? (POST has a lot more advantages than GET) And if so, why would anybody use GET?

Upvotes: 0

Views: 167

Answers (4)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76405

Yes, there is... here's an example

Basically, you'll have to open the connection like so:

xmlhttp.open('post','script/url',true);
xmlhttp.send('data=foo&bar=foobar');//data here

Of course, you'll best set a couple of headers:

xmlhttp.open('post','script/ur',true);
xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.onreadystatechange = function()
{
    if (this.readyState === 4 && this.status === 200)
    {
        console.log(this.responseText);//do whatever
    }
};
xmlhttp.send('data=foo&bar=foobar');//data here

Upvotes: 1

netvision73
netvision73

Reputation: 4921

Use xmlhttp.open("POST","ajax_info.txt",true);

Upvotes: 2

Kemal Dağ
Kemal Dağ

Reputation: 2763

Yes there is,

var r = new XMLHttpRequest(); 
r.open("POST", "path/to/api", true); 
r.onreadystatechange = function () { 
   if (r.readyState != 4 || r.status != 200) 
      return; 

    alert("Success: " + r.responseText); 
}; 
r.send("banana=yellow");

Example taken from vanilla-js. Use vanillajs, it is only 0kb and free :)

Upvotes: 1

schlingel
schlingel

Reputation: 8575

Yes, there is. See specification. (I don't post code because I think you can handle it yourself changing 'GET' to 'POST' ...)

Why would you use GET? Because of SOP issues (JSONP = GET) or because you using a very strict REST metapher where POST is only create, GET is receiving, PUT is updating, and DELETE is used to remove items.

Upvotes: 2

Related Questions