I'm trying to do an ajax call with POST method, but the PHP only return an empty array. What am i doing wrong?
JAVASCRIPT
// ajax call
function makeRequest(){
var http_request = false;
// example data
var fileObjectInfo = 'bla';
var url = 'archivo.php';
if (window.XMLHttpRequest){
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
}else if(window.ActiveXObject){
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
if (!http_request) {
console.log('Falla :( No es posible crear una instancia XMLHTTP');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('POST', url, true);
http_request.send(fileObjectInfo);
function alertContents(){
if (http_request.readyState == 4) {
if (http_request.status == 200) {
console.log(http_request.responseText);
} else {
console.log('Hubo problemas con la petición.');
}
}
}
}
My php only do: <?php print_r($_POST); ?>
(i tried with request too), but always return an emty array. (so the call works but javascrip doesn't send the information, no?)
I get examples code from internet but never works the ajax call with POST method and i don't know why.
thank you in advance for all the help they can lend.
If You request post method you must be pass header data with request like
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", fileObjectInfo.length);
http_request.setRequestHeader("Connection", "close");
put this data before http_request.send(fileObjectInfo);
I hope this will help you
To send a POST request you need a form data object containing key value pairs for PHP to interpret post values
var fileObjectInfo = new FormData();
fileObjectInfo.append("key", "value");
fileObjectInfo.append("name", "prince");
// ajax code
http_request.send(fileObjectInfo);
In PHP then do this
echo $_POST["key"];
echo $_POST["name"];
Be sure to check if the post params exist using isset()