Calling PHP JSON data results from JavaScript - 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.

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

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

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.

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

Javascript using PHP to return an array

Basically, what I'm trying to do is send a request to a separate .php file which queries my database. The problem occurs when trying to return an array as a variable type array. I need this, because I want to send it to another PHP when it is send to the HTML. In the second PHP file, I want to use a for-each-loop-statement in order to create some code, but this only takes arrays and not strings. I've tried a couple of things including the use of JSON in an attempt to fix this, but on return the array keeps turning into a string. Any help would be appreciated. Most relevant code is included below:
javascript:
function getEvents(){ //gets the events from the database
var req = new XMLHttpRequest();
var att = 1; //Just a filler because somehow this seems needed
var link = "IekjeConnector.php";
dataType:"json";
req.onreadystatechange = function() {
if(req.readyState === 4 && req.status === 200)
{
addEvents(JSON.parse(this.responseText)); //This should be a normal array
}
}
req.open("GET", link + "?att=" + att, true);
req.send();
}
function addEvents(events = ""){
var req = new XMLHttpRequest();
var link = "IekjeHome.php"; //sends to the next php
req.onreadystatechange = function() {
if(req.readyState === 4 && req.status === 200)
{ document.getElementById("event").innerHTML = this.responseText; }
}
req.open("GET", link + "?events=" + events, true); //events has the right value
req.send();
}
php:
if (filter_input(INPUT_GET, "events", FILTER_SANITIZE_STRING)) {
$events = filter_input(INPUT_GET, "events", FILTER_SANITIZE_STRING);
$length = count($events);
print_r(gettype($events));
foreach($events as $event)
{ echo $events[$count] . $events[$count+2]; }
}
The foreach returns an error that $events is a string as does the gettype().
I tried changing the way addEvents and the php-code receive the array, but i'm probably doing something wrong trying.
I think you need to change the string to array, for example using explode.
$events = filter_input(INPUT_GET, "events", FILTER_SANITIZE_STRING);
$events = explode(",",$events);
Instead of the ",", just put your event's separator.
I believe what you're looking for is JSON.parse(this.responseText).

$_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