Can't display JSON on page - javascript

I have been trying to get my JSON code from a PHP file which is connected to my database to display on my website using an XMLHttpRequest, but we cant split them and display it.
We are using an php file example.php that does the following:
function jsonFromQuery($result) {
if (mysql_num_rows($result) > 0) {
while($r = mysql_fetch_array($result, MYSQL_ASSOC)) {
$json[] = $r;
}
} else {
$json = "Table is empty";
}
return json_encode($json);
}
This will display the json code as following on the website if you open the php file:
[{"UserID":"2","Firstname":"Piet","Lastname":"Klaas","Age":"23","Specialization":"Voet","Branch":"Been","Interests":"Hoofd","Hospital":"OLVG","Email":"pietklaas#gmail.com","ProfilePicture":""}]
With this we use the following javascript file to request this php file and stringify and try and display it.
var request = new XMLHttpRequest;
request.open('GET' , 'http://myurl.nl/example.php', false);
request.send(null);
if (request.status == 0)
console.log(request.responseText);
var obj = JSON.stringify(request);
var firstname = obj.Firstname;
document.writeln(firstname);`
But I get a massive string which includes the type status etc. And don't know how to split this up to display on their own. For example only Firstname = Piet on the page.

When you get the data back from PHP it's already in the form of a string. You need to use JSON.parse() to convert it into an object you can use. Try...
var obj = JSON.parse(request.responseText);
var firstname = obj[0].Firstname;
document.writeln(firstname);`
Note as well that the Json you're getting back is a list of objects: [{...},{...},{...}], so you can't just call .Firstname as you haven't specified which object you care about. Hence the [0] in the example above to pick out the first object.
One other thought... At present if your PHP doesn't find any results it's going to send back something that isn't in the format you're expecting. Consider either wrapping the list in an object with a status...
{
"Success": true,
"Results": [{...}, {...}]
}
Or make the PHP script return a different HTTP code to indicate failure (404 seems appropriate here)
For future reference, JSON.stringify does the opposite - it takes a complex object and converts it into Json

You are parsing the whole XMLHttpRequest object
var obj = JSON.parse(request);
try using just the response body
var obj = JSON.parse(request.responseText);

Related

Sending array to PHP using XMLHttpRequest (pure JS)

I'm attempting to send an array from JS to PHP using AJAX.
What seems to be happening is that the request is going through and is successful, but no data is received on the server (my test.php script needs the data from this array). Here is what I have so far...
Javascript
myButton.onclick = function() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php", true);
xhr.onreadystatechange = function () {
if (xhr.readyState==4 && xhr.status==200) {
console.log("Done. ", xhr.responseText);
}
}
//xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send('myArray='+JSON.stringify(myArray));
};
test.php
<?php
//$myArray = json_decode($_POST['myArray']); //Undefined index
print_r($_POST);
Note, myArray is not shown in the above code, but it is a valid array.
I've searched around SO (which led me to adding the 'setRequestHeader' in), as well as the wider internet. However, this has made no difference and I seem to be going round in circles. When I print $_POST, it's always an empty array.
I'm sure there's something I'm missing/misunderstanding.
Edit
As requested...
var myArray = ["John", "Jill", "James"];
I've also attempted this with an array of booleans, as well as an associative array/object.
Edit 2
As requested, adding screen shot from dev console...
you can use formData :
let data = new FormData();
let values = [1, 2, 3];
data.append('myArr', JSON.stringify(values));
// send data to server
and in php use json_decode :
$Values = json_decode($_POST['myArr']);
another way is to create HTML checkbox or select elements with javascript , assign values , serialize them and send them to back-end .

Accessing and decoding JSON sent from JavaScript to PHP

So I have a form, I took the contents of its inputs, threw them into an array, had it made into a JSON and then sent it to PHP so it can in turn decode and enter it into a database. I know it'd be easier to just use a <form method="POST" action="phpfile.php"> but I can't have this redirecting to another page, especially since my PHP is not embedded into HTML, instead it handles things offsite. Otherwise it'd be simpler to just use $_POST["name"] to get what I need. Nonetheless, this page in particular is supposed to create the user, receive a server response, that the user has been entered into the database and then is given an alert with a button to be redirected to the main page.
So anyway here are the relevant sections of this whole process.
JavaScript:
window.onload = function findSubmitButton() {
var button = document.querySelector(".send_info").addEventListener("click", serverInteraction);
}
function serverInteraction() {
var xmlhttp;
var inputArray;
var finalArray = [];
var JSONArray;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("Your browser is not compatible with XMLHTTP");
return false;
}
inputArray = document.querySelectorAll("input[type=text]");
for(var i = 0; i < inputArray.length; i++){
finalArray[i] = inputArray[i].value;
}
console.log(finalArray);
JSONArray = JSON.stringify({finalArray: finalArray});
console.log(JSONArray);
xmlhttp.open("POST","phpFiles/sendUserInfo.php", true);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.send(JSONArray);
}
PHP:
<?php
$finalArray = json_decode($_POST['finalArray']);
var_dump($finalArray);
?>
That var_dump simply returns a null and using echo gives me nothing, except a warning that my array variable isn't initialized through XDebug. I'm not quite sure what I'm doing wrong here, I've been following this just like the tutorials tell you to do it, and isn't generating the array. I've also tried $_POST['JSONArray']without any luck in case that was how it was supposed to go. Also tried file_get_contents('php://input') which sends an empty string as well.
You can't get your data from $_POST if you put JSON in your post body.
see this question Receive JSON POST with PHP. php can't handle application/json properly.
For your var_dump is empty, try this
var_dump(file_get_contents('php://input'));
var_dump(json_decode(file_get_contents('php://input'), true));
you will see your data.
And if you send your data without change it to JSON, you will get wrong data.
eg: your finalArray is ['a','b','c'] and you send it directly.
var_dump(file_get_contents('php://input'));
you will see php got string a,b,c instead of ['a','b','c']
So if you want to use $_POST to receive data, you need to use application/x-www-form-urlencoded. you can use jquery to do it. see http://api.jquery.com/jquery.ajax/
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
it will serialize your js object into x-www-form-urlencoded and php will handle it properly.
use chrome's dev tools, switch to network and see the request payload and response would be helpful for you.
You are bypassing $_POST by sending the the data as "Content-type","application/json" .
The data will instead be set in the body of request and can be retrieved using file_get_contents("php://input")
For further discussion see file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?
Generally there is no need to send your data as json to php

json from js to php - failed to open stream: http request failed

I am trying to send some json data from js to php, and pass it to mongo by REST.
The following outputs json string (that works fine later if I just put it as string in PHP file, please see snippet below).
JS to send json:
var s = JSON.stringify(send); //s contains previous data in arrays, etc
ic(s);
function ic(s){
var ajaxUrl = './iM.php';
$.getJSON(ajaxUrl,
{da: s},
function(data) {
console.log (data);
});
}
in iM.php:
$s = $_GET["da"]; // <-- doesn't work
//$s = '{"r":"pax","c":1,"w":["kiwi","melon"],"g":["cat","dog"]}'; //<-- works fine
$opts = array(
"http" => array(
"method" => "POST",
"header" => "Content-type: application/json",
"content" => $s,
),
);
$context = stream_context_create($opts);
$result = file_get_contents("https://api.mongolab.com/api/1/databases/$db/collections/$collection?apiKey=$key", false, $context);
var_dump($result); // Dumps the response document
At the firefox debugger, I can see the file is actually being called, however No data is added.
error_log file is created:
failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
I also tried urlencode($s) in php, still not working.
$db, $collection and $key are defiend in php, no problem there.
What am I missing?
Basically JSON.stringify(send) function is designed in such way that it will make your json into what you are getting.
JSON.stringify(value[, replacer[, space]])
You should use this function properly. read the docs to know more.
Its basically useful if you have input value as JS array or JS object
which can be converted to single string.
You are getting '{/"r/":/"pax/",/"c/":1 in only case if you are trying to stringify a json which already in string format.
these:
var s = ['1','2','3'];
and
var s = "['1','2','3']";
are totally different things.
If you are sending an array or json object you can even send it directly
using the code above.
for example :
send = {"r":"pax","c":1,"w":["kiwi","melon"],"g":["cat","dog"]};
ic(send);
function ic(s){
var ajaxUrl = 'im.php';
$.getJSON(ajaxUrl,
{da: s},
function(data) {
console.log (data);
});
}
make sure to handle array at php side properly.
Like if you want return json, do:
$s = $_GET["da"]; //this will be array.
var jsonObject = json_encode($s);
or you can stringify it there and then provide.
or else just send string and then use json_decode to make it json in php

Json_encoding a Php Variable in an Ajax Request

Currently I am using a jQuery Ajax asynchronous function to request a PHP page multiple times until a large number of spreadsheet rows are processed. Right now I am using the following code to set the variables to be passed to the requested page, I am not sure if this is the proper way to do it or not. PHP:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$new_spreadsheet = nl2br($_POST['spreadsheet']);
$new_spreadsheet = explode('<br />', $new_spreadsheet);
array_shift($new_spreadsheet);
$new_spreadsheet = array_values($new_spreadsheet);
$new_spreadsheet = json_encode($new_spreadsheet);
echo var_dump($new_spreadsheet);
}
JavaScript/PHP:
var done = false,
offset = 0,
limit = 20,
rankings_abv_twenty = 0,
sum = 0,
num_count = 0,
websites = 1
<?php if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo ', spreadsheet = '.$new_spreadsheet;
}?>;
On the requested PHP page (which happens to be Object-Oriented PHP), I have the following code to slice off 20 rows to process on the given request. Please not the PHP is a full working class, I just did not include all the PHP for the sake of post length. Also note, I have another page which calls the class, which passes the spreadsheet variable to the constructor of the PHP by reference as $_POST['spreadsheet'], so I know I have the right value as the spreadsheet. PHP:
$this->offset = $offset;
$this->limit = $limit;
$this->spreadsheet = json_decode($spreadsheet);
Here is the PHP line which slices off the rows:
$this->rows = array_slice($this->spreadsheet, $this->offset, $this->limit);
For some reason my code is not working properly and is giving me the following errors relating to the above code:
PHP Warning: json_decode() expects parameter 1 to be string, array given
PHP Warning: array_slice() expects parameter 1 to be array, null given
I think it might have something to do with how my string is getting passed the requested PHP. Also, just as a further note, when I use var_dump() on my spreadsheet variable before it is passed to the requested PHP, I get it outputted as a string like so:
string(7560) "String content goes here"
On the first look, instead of echoing the json_encode, you used var_dump.
And when manually modifying the json encoded string make sure to use " around the vars.
And this:
websites = 1
<?php if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo ', spreadsheet = '.$new_spreadsheet;
}?>;
Will result in:
websites = 1, spreadsheet = "{"1":"foo","2":"bar","3":"baz","4":"blong"}";
Wrap the line in ' if that's what you expect it..
like this:
echo ", spreadsheet = '".$new_spreadsheet."'";

Handle JSON server response in javascript

I've seen many similar issues, but they didn't provide answer for my question.
My Server form JSON string and put it into response:
List<String> list = getSomeList();
JSONArray jsArray = new JSONArray(list);
System.out.println(jsArray);
response.setContentType("application/json");
response.getWriter().write(jsArray.toString());
But in my javascript handle function when I alert response, it alert ALL page!
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
alert(response); //alert all page!
var list = JSON.parse(response.toJSON()); //doesn't work!
}
}
Question: how could I separate only jsArray in javascript?
P.S. As I understand, my JSON.parse(response.toJSON()) doesn't work because response contain the whole page?
Disclaimer: I don't know java.
Server-side, the problem is probably that your response is not closed after writing your JSON Array, allowing other (html) text to be written. Try this:
response.setContentType("application/json");
response.getWriter().write(jsArray.toString());
response.getWriter().close();
Client-side, responseText is a string, and strings don't have a toJSON() function defined.
var list = JSON.parse(http.responseText);
should suffice.

Categories

Resources