AJAX - using POST instead of GET

So far I have used:

xmlhttp.open("GET","server_script.php?q="+str,true); 

thanks

Edit: I provide a solution for anyone who may come across this page to demonstrate how to use POST instead of GET. If you are new to AJAX, I would recommend this tutorial http://www.w3schools.com/PHP/php_ajax_php.asp using the GET method.

Decision -

JavaScript:

 xmlhttp.open("POST","script.php",true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send('var_name='+str); 

PHP:

 $var_name = GET['var_name']; echo $var_name; 

For reasons related to using POST and GET - see the comment.

+1
source share
2 answers

The request you requested is probably great for a GET request. No need to change it.

There are reasons to use one above the other: requests that change state on the server side (i.e. change data) should usually use POST; "read" requests must be GET.

This is due to the implicit security advantage, because you cannot harm by smuggling the URL to the user’s page (for example, displaying an image whose URL is listed on the admin page named deleteall.php ).

If your request simply retrieves data, you can stay perfectly with GET.

See this question for a detailed discussion of when to use it. GET vs POST in AJAX?

+4
source

this is how you would use the post:

 var url = "server_script.php"; var params = "q="+str; xmlhttp.open("POST", url, true); //Send the proper header information along with the request xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.setRequestHeader("Content-length", params.length); xmlhttp.setRequestHeader("Connection", "close"); xmlhttp.onreadystatechange = function() {//Call a function when the state changes. if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { alert(xmlhttp.responseText); } } xmlhttp.send(params); 

a source

+6
source

Source: https://habr.com/ru/post/895110/


All Articles