SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Thread: AJAX Post

  1. #1
    SitePoint Enthusiast
    Join Date
    Jan 2008
    Posts
    37
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    AJAX Post

    Hey all, I can't seem to figure out how to send parameters over to my PHP file using JS.

    Heres the code I use:
    Code:
    var params = 'param1=test&param2=test2'
    xmlhttp=new XMLHttpRequest()
    xmlhttp.open("POST",url,true)
    xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlhttp.setRequestHeader("Content-length", params.length);
    xmlhttp.setRequestHeader("Connection", "close");
    xmlhttp.onreadystatechange= function() { alert(xmlhttp.responseText) };
    xmlhttp.send(params)
    It sends the POST with no errors, but my PHP file is not able to get it. I'm using $_POST['param1'] and $_POST['param2']...
    Help?

  2. #2
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,578
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Try changing the content type header:

    Code:
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  3. #3
    SitePoint Enthusiast
    Join Date
    Jan 2008
    Posts
    37
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Already did... Its sending the data but my script just isn't receiving it...

    I use Firebug to monitor my xmlhttpRequests and its sending correctly and everything. Not sure why its not working...

  4. #4
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here is a test page made out of your script, which works:
    Code:
    <html>
    <head>
    <script type="text/javascript">
    var xmlhttp;
    function doajax(theURL) {
    	var params = 'param1=test&param2=test2'
    	xmlhttp=new XMLHttpRequest()
    	xmlhttp.open("POST",theURL,true)
    	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    	xmlhttp.setRequestHeader("Content-length", params.length);
    	xmlhttp.setRequestHeader("Connection", "close");
    	xmlhttp.onreadystatechange= function() {
    		if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    			alert(xmlhttp.responseText) 
    	};
    	xmlhttp.send(params)
    }
    </script>
    </head>
    <body>
    <button onclick="doajax('ajtest1.php');">ajax text</button>
    </body>
    </html>
    Code:
    <?php
    echo "response: param1=" . $_POST['param1'] . ", param2=" . $_POST['param2'];
    ?>


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •