Jump to content

switching from GET request to POST in AJAX


gamblor01

Recommended Posts

Hi everyone,

 

I have been learning AJAX lately and found that all of the examples I looked at used GET requests to invoke the backend script.  Sometimes, one may find it useful to execute a POST instead, so I wanted to share this link:

 

http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

 

 

The instructions are all there.  Basically you need to:

 

1. Change the "GET" string to "POST" when you call the open() function

2. Remove the '?' character from the end of your URL and put your arguments inside of another string instead

3. Add in some header information that will be sent as well

4. Send the params using the send function instead of appending them to the end of the URL

 

 

Here is a simple, yet clear example of AJAX with a GET request from w3schools.com:

 

http://www.w3schools.com/php/php_ajax_database.asp

 

 

The relevant code for the GET request looks like this:

 

var url="getuser.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);

 

 

To transform this into a POST request instead, we would simply change those lines above to be:

 

var url = "getuser.php";
var params = "q=" + str + "&sid=" + Math.random();
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.send(params);

 

 

Viola!  Your code will perform a POST instead of a GET.  Hope this helps.

Link to comment
Share on other sites

  • 3 weeks later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.