0

Using Ajax to communicate with server,

I am trying to pass a value to dat.php using AJAX and get another value from dat.php back. The below code works fine when I use GET but doesn't work work with POST. I need to use POST as this is sensitive information I am trying to pass. Any idea hwy this is happening.

This is my code on test.php

<html>
<body>

<form action="<?php echo $_SERVER['$PHP_SELF'];?>" method="post">

<input type="text" name="value" onchange="ch_email1(this.value)"></input>

</form>



<script>
function ch_email1(str){
    var ajaxRequest;    
    try{
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        try{
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
        try{
        ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
        // Something went wrong
                var xl=xmlhttp.responseText
        alert("Something Went wrong");
        return false;
            }
        }
    }
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            var xl=ajaxRequest.responseText;
alert (xl);


        }
    }
    ajaxRequest.open("POST","dat.php?q="+str, true);
    ajaxRequest.send(null); 
}


</script> 
</body>
</html>

This is dat.php

<?php


$q=$_POST['q'];

echo $q;

?>

Please note that above code works fine when I replace POST with GET. Any ides why this is happening.

random_user_name
  • 25,694
  • 7
  • 76
  • 115
user2288650
  • 412
  • 1
  • 6
  • 23

3 Answers3

2

This might help:

 ajaxRequest.open("POST","dat.php", true);
 ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 ajaxRequest.send("q="+str);
jeremysawesome
  • 7,033
  • 5
  • 33
  • 37
1

Take a look at this page.
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

Right now, you're sending a post request with nothing in it. Appending to the url just changes the $_GET variables.

Trenton Trama
  • 4,890
  • 1
  • 22
  • 27
0

You are mixing POST Ajax call with GET way

When you send an AJAX call with POST, you don't have to put parameter on the URL, but you must send parameters using the .send() method.

exemple:

ajaxRequest.open("POST","dat.php",true);
ajaxRequest.send("q=" + str);

You should use a JS librairy like jQuery or other, that will make it for you, instead of re-inventing the wheel and have common problems.

MatRt
  • 3,494
  • 1
  • 19
  • 14