I have a problem with an Ajax request . I don't know if I'm doing it correctly, the fact is that I've always done it with the Jquery library , but now I want to do it only with Javascript .
Code
var enviarObjeto={'titulo': 'hola','usuario': 'Pier'};
var objeto = "json_name=" + JSON.stringify(JSON.stringify(enviarObjeto));
var xhr = new XMLHttpRequest();
xhr.open('POST', "guardar.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
if (xhr.status == 200) {
xhr.send(objeto);
xhr.onload = function () {
alert(this.responseText);
};
alert('enviado ok');
}
else {
alert('error');
}
Can you tell me what I have done wrong? It is the first time that I do it with Javascript and I would be grateful if you tell me where my errors are.
If you want to send an object
Json
, try adding the following:On the other hand, you are not sending the values, for example with
xhr.send({});
At this URL is an example similar to what you want to do.
Cheers
I recommend that you use FormData to send data. Here I leave you an example.
This is the file in php that receives the data.