Can't send data from JavaScript to PHP [duplicate] - javascript

This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 1 year ago.
I am trying to make a simple JavaScript game, and as a user, I will get a score.
I want to send this score to a PHP server, but in my case, I can't get this data in the PHP file.
Here my JavaScript code:
var obj = {
"note": 0,
};
obj.note = score;
console.log(obj.note)
var data, xml, txt = "", mydata;
data = JSON.stringify(obj.note);
xml = new XMLHttpRequest();
xml.onreadystatechange = function() {
if (this.readystate == 4 && this.status == 200) {
mydata = JSON.parse(this.responseText);
for (x in mydata) {
txt += mydata[x];
}
// document.getElementsByClassName("pEl").innerHTML = txt;
}
};
xml.open("POST", "getnote.php", true);
console.log("true");
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.send("x=" + data);
Here my PHP code:
<?php
// Takes raw data from the request
$json = file_get_contents('application/x-www-form-urlencoded');
// Converts it into a PHP object
$data = json_decode($json);
echo $data
?>

Many people tried to help you, you used a valid sample which you linked, anyway still using the wrong code, which you modified with no reason and all you had to do was to follow suggestions from GeeksForGeeks page you linked.
Short
You can not use anything you want when you trying to access php://input stream (you used application/x-www-form-urlencoded, which is wrong, and I have no even idea why?)
Working, minified sample
test.html
<script>
let obj = {
"note": 123,
"foo": "bar"
};
let data, xml;
data = JSON.stringify(obj);
xml = new XMLHttpRequest();
xml.open("POST", "getnote.php", true);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.send(data);
</script>
getnote.php
<?php
// Takes raw data from the request
$json = file_get_contents('php://input');
// Converts it into a PHP object
$data = json_decode($json, true);
// print whole array decoded from JSON object
print_r($data);
// print single node of the array
echo "The sent note is: {$data['note']}";
echo "The sent foo is: {$data['foo']}";
// etc.
Please, read once again the article you linked, also read carefully the question linked by El Vanja to recognize what mistake you did.
Note: that should be just a comment, and probably will be flagged to delete, anyway I have no idea what else we can do if you don't want to read the simple comments that solve your problem and give you a detailed description.

Related

I want to receive a JSON (sendend by POST method of JS xmlHttpRequest()) echo from PHP

The code JS is
var xhr = new XMLHttpRequest()
//console.log(xhr)
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
console.log(xhr)
}
}
xhr.open("POST","https://testepr.harpiastudios.com.br/http-receiver.php")
xhr.setRequestHeader('Content-Type', 'application/json')
function sendText(text){
let dataToSend = {
"text": text
}
console.log(dataToSend)
xhr.send(dataToSend)
}
and the PHP Code is:
$dataToSend = json_decode(file_get_contents('php://input'));
echo($dataToSend->text);
The php file returns
Notice: Trying to get property of non-object in
I need to echo this value cause i need to use for other things. I dont know to have acces from this index of JSON

JavaScript problem with fetching data from PHP

I'm new to PHP, and i'm trying to fetch data from PHP to JavaScript. When i do that, JavaScript always giving me the same error "Unexpected token < in JSON at position 0". I don't have any idea what to do. I'm stuck...Help Help ! x)
There is the code
JavaScript
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "data.php", true);
xmlhttp.send();
PHP
<?php
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";
$myJSON = json_encode($myObj);
echo $myJSON;
?>
I think you are getting an issue of object
Object $myObj need to be initialized before using it
I have updated the code (Initialized the object) please use the below code on php page to resolve the issue
<?PHP
$myObj = new StdClass();
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";
$myJSON = json_encode($myObj);
echo $myJSON;
Obviously, the response returned for your XMLHttpRequest is not a valid JSON. Provided that your PHP codesample is complete, PHP will most likely(*) echo an E_WARNING error before outputting the JSON string, although your code will work. Related question and solution here. Easiest way to check is to view the raw response in your browser's dev tools (supported by all major browsers). If the response contains anything except the JSON string, JSON.parse() will throw an error.
(*)This depends on your error reporting settings

Data not being sent via XMLHttpRequest

I have a weird issue with a script I am using to send some info to my PHP. I say weird because this code is a direct copy of some already working code on the same application, with new variable names. I need to upload a small amount of data to my server, and while the value is there and the code runs all the way through, the POST data is not being sent or something. I have checked, and it says it has been submitted to my PHP with the value but nothing happens. I am using Vue.js if there are questions about some of my formatting
I have tried looking at other examples online, but my thing is that this was a block of code that copied from a working part of my application. It works until the data transfer from JS -- PHP
JS
editDisplayName: function() {
var self = this;
var newName = prompt("10 Characters Max, 3 Min", "Enter Display Name");
if(newName.length <= 10 && newName.length >= 3 ) {
var sendData = new XMLHttpRequest();
sendData.open("POST", "primary.php", true);
sendData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendData.send(newName);
self.username = window.localStorage.getItem('username');
window.localStorage.clear();
}
}
PHP
function changeUsername() {
// Connect to Server
$link = // Commented Out For Security;
if (mysqli_connect_error()) {
die ("DB Connection Error");
}
$newName = $_POST['newName'];
$newName = mysqli_real_escape_string($link, $newName);
$token = $_COOKIE['validToken'];
$token = mysqli_real_escape_string($link, $token);
$query = "UPDATE userData SET username = '$newName' WHERE token = '$token' LIMIT 1";
mysqli_query($link, $query);
mysqli_close($link);
echo("
<script>
var username = $newName;
window.localStorage.setItem('username', username);
</script>
");
}
if(isset($_POST['newName'])) {
changeUsername();
}
I'm expecting on my DOM that I would have the new username set, instead it is blank. The spot where stuff stops working is somewhere with the POST data being sent, since my PHP isn't picking anything up, but I can't figure out what is wrong.
Instead of just sending the value, you should send the parameter name as well.
So, instead of using sendData.send(newName);, try using:
sendData.send("newName=" + newName);
(as your Content-type is application/x-www-form-urlencoded)
Or if you want to use JSON:
Change your Content-type to application/json, then send the data as a JSON string, like so:
sendData.send(JSON.stringify({'newName': newName}));

Calling PHP JSON data results from JavaScript

I am attempting to obtain PHP data from my Javascript code. This is meant to be shown in the dayta div id. What I end up getting instead is undefined instead of the desired result (which in this instance is the firstname in my JSON file). I am not sure why this is happening.
My JavaScript code:
window.onload = function(){
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if (http.readyState == 4 && http.status == 200){
var dayta = document.getElementById('datadisplay');
dayta.innerHTML = http.response.firstname;
}
}
http.open("GET", "myphpfile.php", true);
http.send();
}
My PHP code (myphpfile.php):
<?php
$content = file_get_contents('somejsonfile.json');
print_r($content);
$dbcon->close();
?>
The PHP code included is only a portion of my code, but it contains all the parts relevant to my problem.
$content outputs a JSON file, as that is what it is pointed to. If I echo $content I am able to verify that the content is streamed out as intended.
Thus, the problem is most likely with my JavaScript code. But I cannot identify specifically what is wrong.
My JSON file (somejsonfile.json):
{"firstname": "Ki ki ki ma ma ma"}
I understand that the most obvious way to approach this specific example is to simply have the JavaScript file reach the JSON file. However, since I'm trying to secure the path of my JSON file in my production code I am trying out this method.
Make sure you get a JSON response by using JSON.parse. Here's a quick solution. I have tried it and it works great!
window.onload = function(){
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if (http.readyState == 4 && http.status == 200){
var dayta = document.getElementById('datadisplay');
var data = JSON.parse(http.responseText);
dayta.innerHTML = data.firstname;
}
}
http.open("GET", "myphpfile.php", true);
http.send();
}
pls check this code;
<?php
$content = file_get_contents('somejsonfile.json');
print_r(json_decode($content));
?>
if you see array truly then,
<?php
$content = file_get_contents('somejsonfile.json');
echo(json_encode($content));
?>
if you want to query in json file, you can use json_decode function to convert array and push or remove array item and then json_encode.

$_GET variable not showing up in string and boolean operations

I have a javascript file that uses POST to send some data to a PHP file, as such:
var additional = "Feb2015";
xmlhttp.open("POST", "database_comm_general.php?query=" + additional, true);
In the PHP file, I use $_GET to get that 'additional' variable:
$query = $_GET['query'];
Now, if I want to use it to get some data from MySql, I use this for my query, but when I echo it, it just shows empty quotation marks, where 'Feb2015' should be:
$sql_query = "SELECT * FROM '" . $query . "'";
Output: "SELECT * FROM ''"
Even more odd, if I use json_encode and print it on the javascript side, it shows up just fine.
Similarly, if I see if the variable equals 'Feb2015', with json_encode it will return true, but on the page it will output false at the same time.
Any ideas?
Edit:
This is my javascript code:
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var content = JSON.parse(this.responseText);
window.alert(content);}}
xmlhttp.open("POST", "database_comm_general.php?query=" + additional, true);
xmlhttp.send();
Alright, I haven't been able to fix this exact issue, but I got my code working through other means:
First, I use jquery instead of javascript for communicating with PHP:
text = "Feb2015";
$.ajax(
{ url : "database_comm_general.php?" + text, success: function(data){
var return_data = JSON.parse(data);
populateTableList(return_data);
}});
Second, in the PHP file, I don't use $_GET, I get the data from the link address:
$link = $_SERVER[REQUEST_URI];
$index = strpos($link, "?");
$sub_string = substr($link, $index+1, 7);
$sub_string = $sub_string;
Third, I added a single line of code in the MySQL code that resolved the issues with some of the arrays which couldn't be encoded:
mysqli_set_charset($conn, 'utf8');
All in all, I feel I've been to hell and back, but I hope this helps someone in the future.

Categories

Resources