Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
127
rated 0 times [  129] [ 2]  / answers: 1 / hits: 39378  / 13 Years ago, mon, august 15, 2011, 12:00:00

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.


More From » php

 Answers
58

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


[#90595] Sunday, August 14, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
madelyn

Total Points: 449
Total Questions: 100
Total Answers: 100

Location: Seychelles
Member since Fri, May 7, 2021
3 Years ago
madelyn questions
Wed, Jul 28, 21, 00:00, 3 Years ago
Wed, Jul 14, 21, 00:00, 3 Years ago
Sat, Nov 7, 20, 00:00, 4 Years ago
Thu, Sep 3, 20, 00:00, 4 Years ago
;