XMLHTTPrequest sending empty post - javascript

I've done a lot of times before, so I'm honestly confused why this is failing to pass anything. I've tried printing results (script gets a response and prints the file).
function submit_form_inpage(path, data, watchForChange){
alert(data);
watchForChange = watchForChange || false;
var request = new XMLHttpRequest();
request.open('POST', path, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
if (watchForChange == true) {
request.onreadystatechange = function () {
if (request.readyState == 4) {
document.write(request);
if (request.status==200 && request.status < 400){
var xmldata=request.responseText //retrieve result as an XML object
alert("XML:" + xmldata);
}
else{
alert("An error has occured making the request:" + request.status );
}
}
}
}
var temp_string = array_to_string_for_post(data);
var temp = JSON.stringify(data);
alert(temp);
request.send(temp);
}
My php is
print_r($_POST);
and my result is
XML: Array ()
Despite the fact that data passed in (which is double-checked right before being sent by my alert) is
{"reason":"get_stuff","build_name":"test"}

You said you were sending form encoded data.
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
Then you sent:
temp = JSON.stringify(data);
JSON is application/json not application/x-www-form-urlencoded (and isn't natively supported by PHP anyway).
Either encode your data as application/x-www-form-urlencoded or correct your content-type and parse it manually in PHP.

Related

I can't get a response from the server

I followed some guides on how to send json objects to the server(written using node.js) and it doesn't work, I have no idea what is wrong. I know that my server works fine since I tested it on postman so it's my js code that's the problem, all the tutorials I see follow a similar XMLHttpRequest format.
this is my code
var ing = new Ingredient(name, date, qty, rp);
var url = "http://localhost:8081/addIngredient";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
// application/json is sending json format data
xhr.setRequestHeader("Content-type", "application/json");
// Create a state change callback
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
result.innerHTML = this.responseText;
}
};
// Converting JSON data to string
var data = JSON.stringify(ing);
document.write(data);
// Sending data with the request
xhr.send(data);
I used document.write to check where the code stops working but everything passes (since the document.write prints something), I suspect that there is something wrong/missing from xhr.send(data) but I can't tell what. Finally, nothing gets printed from the callback.
It's better to use onload instead of onreadystatechange
xhr.onload = function() {
if (xhr.status == 200) {
console.log(`Response length = ${xhr.response.length}`);
// store xhr.response here somewhere
}
};

How to capture json data on php that is sent with ajax (no jquery)

I am sending a json data to the server using ajax and pure javascript. How do I get the $_POST index that will display the json content on the php page?
ajax send a request as key=value to the server, meanwhile, by using the content-type 'application/json', I got an example on the link below as the json data (stringfy) was sent directly with no key=value.
Sending a JSON to server and retrieving a JSON in return, without JQuery
On the php side for post request, the example below was given.
$v = json_decode(stripslashes(file_get_contents("php://input")))
Now i don't understand what php://input signifies here since the json data was sent to the same page. I tried file_get_contents('https://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']); but it returned nothing.
I tried using var_dump($_POST) to view all the content as an array, but all i get is array(0){}.
So how do i actually catch the ajax (json) request i sent to a php page?
Here is an example of the code:
var data = {
name : "john",
Friend : "Jonny",
Bestie : "johnson",
neighbour: "john doe"
};
json = JSON.stringify(data);
var ajax = new XMLHttpRequest(), url = '../handler.php';
ajax.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
};
};
ajax.open('POST', url, true);
ajax.setRequestHeader('content-type', 'application/json');
ajax.send(json);
PHP
header("Content-Type: application/json");
var_dump($_POST);
file_get_contents('https://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']);
I expected the json string to be present in the $_POST variable and accessible by it's index after decoding the json string, but i get array(0){}, null or nothing displayed at all
To get an array, add the true argument to json_decode().
In your code:
$body = json_decode(file_get_contents("php://input"), true);
var_export($body);
To add the JSON data in $_POST, you can use this code.
In JS:
json = JSON.stringify(data);
var ajax = new XMLHttpRequest(), url = '../handler.php';
ajax.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
};
};
ajax.open('POST', url, true);
ajax.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
ajax.send('jsn='+json);
In PHP:
$arr = isset($_POST['jsn']) ? json_decode($_POST['jsn'], true) :[];
var_export($arr);
Source: https://coursesweb.net/ajax/json-from-javascript-php

AJAX POST request with response

As the title states, I'm looking to make a POST request using JavaScript and also get a response. Here's my current code:
var request = new XMLHttpRequest();
request.open('POST', 'test.php', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success
console.log(request.responseText)
} else {
// Server-side Error
console.log("Server-side Error")
}
};
request.onerror = function() {
// Connection Error
console.log("Connection Error")
};
request.send({
'color':'red',
'food': 'carrot',
'animal': 'crow'
});
With test.php being:
<?php
echo $_POST['color'];
?>
This should return 'red' but instead returns nothing.
This seems like a simple problem but I could only find solutions for people using jQuery. I'd like a solution that does not rely on and libraries.
The send method takes a string rather than an object, perhaps more like:
var request = new XMLHttpRequest();
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
console.log(request.response)
} else {
console.log("Server-side Error")
}
};
request.onerror = function() {
console.log("Connection Error")
};
request.open('POST', 'test.php', true);
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
request.send('color=red&food=carrot&animal=crow');
The JavaScript problem
You are trying to send a generic Object, so it gets converted to a String ("[Object object]"), and the data is lost.
Convert the data to a FormData object instead.
var data = {
'color':'red',
'food': 'carrot',
'animal': 'crow'
};
var formData = new FormData();
Object.keys(data).forEach(function (key) {
formData.append(key, data[key]);
})
request.send(formData);
The PHP problem
All of the current solutions simply log the source code of "test.php" to the console as opposed to logging 'red' to the console
This is an issue unrelated to your code. It is also a FAQ. See: PHP code is not being executed, instead code shows on the page

String replace not working with value returned from a XMLHttpRequest request

I have a (Laravel) PHP code that returns a long string in this way:
echo json_encode([
'created' => $count,
'total' => $num_stores,
'progressValue' => round((100 / $num_stores) * $count, 2),
'token' => str_repeat('|',1024*64)
]);
I need to get this string in javascript and clean it, removing all "|" character. But it seems not working.
This is my javascript code:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
try {
if (xhr.readyState == 4) {
alert('[XHR] Done');
} else if (xhr.readyState > 2) {
var new_response = xhr.responseText.substring(xhr.previous_text.length);
var cleanedResponse = new_response.replace(/[|]/g, '');
console.log('CLEANED RESPONSE: ' + cleanedResponse);
var result = JSON.parse( cleanedResponse );
console.log('AFTER THE PARSE');
xhr.previous_text = xhr.responseText;
}
} catch (e) {
console.log(xhr.responseText);
alert("[XHR STATECHANGE] Exception: " + e);
}
};
xhr.open("POST", "...", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("X-CSRF-TOKEN", jQuery('meta[name="csrf-token"]').attr('content'));
xhr.send(params);
I always get the exception when I try to parse JSON, and in the console I still see the "|" characters in the "cleanedResponse" variable.
How is it possible if I replace them?
When xhr.readyState == 3, then xhr.responseText holds only partial data - 3 means that the response has not yet been fully downloaded. You probably try to parse only partial JSON string that is not complete and therefore not valid and parsable. Wait for downloading complete response (xhr.readyState == 4) and then try to clean and parse JSON.
See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState for further explanation of XHR states.

Sending a JSON to server and retrieving a JSON in return, without JQuery

I need to send a JSON (which I can stringify) to the server and to retrieve the resulting JSON on the user side, without using JQuery.
If I should use a GET, how do I pass the JSON as a parameter? Is there a risk it would be too long?
If I should use a POST, how do I set the equivalent of an onload function in GET?
Or should I use a different method?
REMARK
This question is not about sending a simple AJAX. It should not be closed as duplicate.
Sending and receiving data in JSON format using POST method
// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
var data = JSON.stringify({"email": "hey#mail.com", "password": "101010"});
xhr.send(data);
Sending and receiving data in JSON format using GET method
// Sending a receiving data in JSON format using GET method
//
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "hey#mail.com", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
xhr.send();
Handling data in JSON format on the server-side using PHP
<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>
The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.
Note Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE instead of xhr.readyState === 4 The problem is that Internet Explorer uses different state names so it's better to use state values.
Using new api fetch:
const dataToSend = JSON.stringify({"email": "hey#mail.com", "password": "101010"});
let dataReceived = "";
fetch("", {
credentials: "same-origin",
mode: "same-origin",
method: "post",
headers: { "Content-Type": "application/json" },
body: dataToSend
})
.then(resp => {
if (resp.status === 200) {
return resp.json()
} else {
console.log("Status: " + resp.status)
return Promise.reject("server")
}
})
.then(dataJson => {
dataReceived = JSON.parse(dataJson)
})
.catch(err => {
if (err === "server") return
console.log(err)
})
console.log(`Received: ${dataReceived}`)
You need to handle when server sends other status rather than 200(ok), you should reject that result because if you were to left it in blank, it will try to parse the json but there isn't, so it will throw an error

Categories

Resources