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.

4
  • 2
    If jQuery is an option, I'd recommend using it. It makes making ajax calls much simpler. Commented Apr 17, 2013 at 0:47
  • 2
    when you are using post , you can not send the data as querystring. Commented Apr 17, 2013 at 0:48
  • Well, you're not sending any POST data in the request body... Commented Apr 17, 2013 at 0:52
  • 1
    Note that POST doesn't protect sensitive data. You may also want to use HTTPS (SSL). Commented Apr 17, 2013 at 0:54

3 Answers 3

2

This might help:

 ajaxRequest.open("POST","dat.php", true);
 ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 ajaxRequest.send("q="+str);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.