gamblor01 Posted February 16, 2010 Share Posted February 16, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/192297-switching-from-get-request-to-post-in-ajax/ Share on other sites More sharing options...
Avocado Posted March 5, 2010 Share Posted March 5, 2010 Thanks gamblor very helpful information. Quote Link to comment https://forums.phpfreaks.com/topic/192297-switching-from-get-request-to-post-in-ajax/#findComment-1021751 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.