Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST from XMLHttp with parameters

I'm trying to post data to a PHP page and check the response. Here is an example. What is wrong with this code?

index.html

<html>
<head>
    <title>Post Ajax</title>
    <script type="text/javascript">
        function post(foo, bar) {
            var xmlhttp = new XMLHttpRequest();

            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    alert(xmlhttp.responseText);
                }
            }

            xmlhttp.open("POST", "ajax.php", true);
            xmlhttp.send("foo=" + foo + "&bar=" + bar);
        }
    </script>
</head>
<body>
    <input type="button" value="Click me" onclick="post('one','two');" />
</body>
</html>

ajax.php

<?php
if (array_key_exists('foo', $_POST) && array_key_exists('bar', $_POST)) {

    $foo = $_POST['foo'];
    $bar = ($_POST['bar']);
    // do stuff with params

    echo 'Yes, it works!';

} else {
    echo 'Invalid parameters!';
}
?>

Either I have a stupid typo or I am not using the send() method correctly.

like image 878
styfle Avatar asked Aug 15 '11 22:08

styfle


People also ask

How do I post in XMLHttpRequest?

The XMLHttpRequest method send() sends the request to the server. If the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events. If the request is synchronous, this method doesn't return until the response has arrived.

How do I get the response from XMLHttpRequest?

It works by creating an XMLHttpRequest object and creating a listener for readystatechange events such that when readyState changes to DONE (4), the response is obtained and passed into the callback function provided to load() .

How do I send a post request using JavaScript?

To send an HTTP POST request, we need to first create the object by calling new XMLHttpRequest() and then use the open() and send() methods of XMLHttpRequest. To receive notifications when the status of a request has changed, we need to subscribe to the onreadystatechange event.

Is XHR a post or get?

The XHR specification says that GET is used without sending data to the server by the send method, and that you use POST in the other case: If stored method is GET act as if the data argument is null. So practically we use GET to load a document or run a script, and POST to pass parameters to a script on the server.


1 Answers

I figured it out. I needed to set the request header.

xmlhttp.open("POST", "ajax.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("foo=" + foo + "&bar=" + bar);

source1

source2

like image 198
styfle Avatar answered Oct 24 '22 12:10

styfle