XMLHttpRequest Posting empty body - javascript

When I try to post some data to my backend API service I use the XMLHttpRequest object, but when I try to send the data with ajax.send it sent nothing to the server
Code snipper:
ajax = new XMLHttpRequest();
ajax.open("POST", "https://someapi.com",true);
ajax.send({
name: "Name",
phone: "123468375698563897569575863"
});
ajax.onreadystatechange = function(){
if(ajax.readyState==4){
JSONback = JSON.parse(ajax.response);
console.log(JSONback);
}
};

You need to:
Say you are sending JSON
Convert your JavaScript data structure into JSON
Such:
var data = {
name: "Name",
phone: "123468375698563897569575863"
};
var json = JSON.stringify(data);
var ajax = new XMLHttpRequest();
ajax.open("POST", "https://balbalbal.com", true);
ajax.setRequestHeader("Content-Type", "application/json");
ajax.send(json);

You cannot directly send a JS object over the wire.
You need to convert it to a string first, just like you need to parse it when you're getting it back.
ajax = new XMLHttpRequest();
ajax.open("POST", "https://balbalbal.com", true);
ajax.send(
JSON.stringify({
name: "Name",
phone: "123468375698563897569575863"
})
);
ajax.onreadystatechange = function(){
if(ajax.readyState==4){
JSONback = JSON.parse(ajax.response);
console.log(JSONback);
}
};
The simplest PHP test code on the server side would be:
<?php
echo file_get_contents('php://input');
?>
And here is a slightly more advanced example that will decode it, add a new field and send it back:
<?php
$json = file_get_contents('php://input');
$object = json_decode($json);
$object->id = 123;
echo json_encode($object);
?>

Related

Sending FormData to PHP file not working as expected

I have a XMLHttpRequest to send a courseName to php file on the server like this:
const xhr = new XMLHttpRequest();
xhr.onload = function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
const fd = new FormData();
fd.append("courseName", 'Math');
xhr.open("POST", "upload.php", true);
xhr.send(fd);
PHP:
<?php
echo $_FILES['courseName']
?>
But nothing is returned, I'm confused please help... it should return Math, Doesn't it?
The network doesn't show any data sent over.
How to use FormData for AJAX file upload?
Shows you how to send files using FormData ...
Best,
Smith

How do I get value from SQL using AJAX

I know how to pass data from JS to PHP using AJAX, but have no idea how to select data to JS from db using AJAX+php.
I tried to find examples of it but nothing clear found.
Could anyone show me how can I get data from SQL? How I tried:
js function
getdata() {
// ?
var result // I want result to store here
var data = new FormData();
data.append('somekey', 'somevalue');
// AJAX CALL
var xhr = new XMLHttpRequest();
// query for getting some data from SQL
xhr.open('POST', "../php/get_answer.php", true);
xhr.onload = function(){
result = this.response // I presume that I can get result here
};
xhr.send(data);
console.log("RESULT GETTING JSON")
console.log(result)
}
get_answer.php
<?php
include("config.php");
$con = setConnection();
$id = $_COOKIE["id"];
$query = "SELECT results FROM `survey_results` WHERE user_id='$id'";
$n = mysqli_query($con, $query);
$results = 0;
while ($row = mysqli_fetch_assoc($n)) {
$results = $row['results'];
}
// return results ?
$con->close();
?>
In your php file, you can return your data as JSON string.
To do this, tell the client it's json by settings the response header to
header('Content-Type: application/json');
and return the results or data with
echo json_encode($data);
For the Javascript part, XMLHttpRequest is now an old way to make Ajax request but it's a good start to learn.
Fisrt, in your code you have to check if XMLHttpRequest is available in the navigator and try to use the old IE fashion way if not. To do this:
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
now you have your object so you have to set a listener witch listen for change in the state of XMLHttpRequest. If all seems ok the result go there:
xhr.onreadystatechange = function()
{
console.log("Wait server...");
if(xhr.readyState == 4) // 4 : request finished and response is ready
{
if(xhr.status == 200) // HTTP OK
{
console.log("Got data!");
result=xhr.responseText; // or result = JSON.parse(xhr.responseText) to have your data as js object
//It's here you have to modify your dom to show your data, change a variable, etc...
} ;
else // bad http response header like forbiden, not found, ...
{
console.log("Error: returned status code", xhr.status, xhr.statusText);
}
}
};
now you can set the URI and send your request:
xhr.open("GET", "../php/get_answer.php", true);
xhr.send(null)
;
If you want more informations about states and status, have a look at XMLHttpRequest Object Methods

Sending multiple values with JavaScript

I have two values I want to send but I couldn't figure it out.
Im currently sending 1 value like that:
JS:
req.open('POST', '../Ajax/doc.php?id=' + id, true);
req.send();
PHP:
$id = $_REQUEST["id"];
And now I have another value id2 which I want to send in the same way..
Thanks
Since you are using post, the SEND function accepts the query string as a parameter. Then just replace my var2 with what it is you are trying to send and use POST in PHP to make it easier for you to know the array to use for POST submissions.
const data = {
id: 123,
var2: 987,
foo: 'bar',
}
req.open('POST', '../Ajax/doc.php', true)
req.send(
Object.keys(data)
.map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
.join('&')
)
PHP
$id = $_POST["id"];
$var2 = $_POST["var2"];
You can send multiple value using FormData.
function send() {
var uri = "your_url";
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", uri, true);
fd.append('title', 'Hello World');
fd.append('content', 'Just Hello World');
// Initiate a multipart/form-data upload
xhr.send(fd);
}
window.onload = function () {
btn_send = document.querySelector('#btn-click');
btn_send.addEventListener('click', function () {
send();
})
}

Accessing JSON.stringify variable in PHP

I have trouble in accessing the JSON string being sent from my client side Javascript code to my PHP code. This is what I have done until now.
var formatted;
fr.onload = function(e) {
var result = JSON.parse(e.target.result);
formatted = JSON.stringify(result, null, 2);
console.log(formatted);
//send formatted as post to write2share.php and write that in a file in share folder
xhr = new XMLHttpRequest();
var url = "write2share.php";
var nametime = gettime();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", 'application/json; charset=UTF-8');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.content);
}
}
var data = JSON.stringify({"content":formatted, "name": nametime});
xhr.send(data);
//GenerateShare(nametime);
}
Here formatted is a JSON string and nametime is an integer
The below is my php script
$decoded = json_decode(file_get_contents("php://input"),true);
$error = json_last_error();
var_dump($decoded);
echo $error;
The output of my $error is 0 and var_dump of $decoded is Null. Why?
Help is appreciated! Thanks

Writing JSON to a file

I wont create a JSON file and save this with a php script. I got this error message (Firefox)
NS_ERROR_XPC_JSOBJECT_HAS_NO_FUNCTION_NAMED: JavaScript component does not have a method named: "available"'JavaScript component does not have a method named: "available"' when calling method: [nsIInputStream::available]
When i use Chrome I didn't get the error message but it doesn't work too.
JavaScript:
var jsonString = '{ "foo": 1, "bar": { "baz" : 1 } }';
var data = JSON.parse( jsonString );
var xhr = new XMLHttpRequest();
xhr.open('POST', './php/upload.php', true);
xhr.send(data);
PHP:
$dateiname = "test12345.json";
if (isset($_POST) && count($_GET)==0) {
$jsonObj = $_POST;
$fh = fopen($dateiname, 'w');
$input = json_encode($jsonObj);
fwrite($fh, $input);
fclose($fh);
}
The Javascript should use:
xhr.send(jsonString);
because the data being sent must be a string, not an object.
In PHP, to read the raw post data, you should use:
$rawjson = file_get_contents("php://stdin");
$jsonObj = json_decode($rawjson);
$_POST can only be used for form data that's formatted using URL-encoding or multipart/form-data encoding.

Categories