I'm attempting to send and receive data from an input
to PHP through an XHR request. I have successfully managed to create a connection to PHP without passing data as a parameter within the send
method.
However, if I attempt it, I receive the error.
Here is the JavaScript (updated!):
function serialize(obj, prefix) {
var str = [],
p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p,
v = obj[p];
str.push((v !== null && typeof v === "object") ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
}
function xhrRequest(data, method, url, callback){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
callback(xhr.responseText);
} else {
callback(null);
console.log("XHR Request Failed");
}
}
}
xhr.open(method, url, true);
xhr.send(JSON.stringify(data));
}
// Calling xhrRequest
xhrRequest({ valueA: input.value }, "POST", "post.php", function(data){
alert(data);
});
PHP is just an echo of the value to make sure it was passed (updated!):
if(isset($_POST["value"])){
echo $_POST["value"];
} else {
echo "no value set";
}
I am aware that you can pass parameters like this "valueA=" + input.value
within the send
method, but it seems really unnecessary (especially if there are multiple values).
So, how would I get this to work? What are some improvements / changes I might be able? to make.
Apologies if it seems very obvious, but I learnt jQuery before vanilla JavaScript, unfortunately. So I am trying to learn the vanilla way, and am used to how jQuery works.
Thanks! :)
EDIT:
Using @adeneo's technique does in fact semi-work! However, using the updated PHP, I alwasy receive "No value set"
. Why is the value not passing, even when I use "valueA=" + input.value
?