PHP json_encode then getJSON issue in javascript - javascript

Sorry if this is still another thread on the subject but I am struggling since hours but could not find the solution.
I am trying to get data from a Mysql database, create a JSON with php, then parse this JSON in javascript.
Here is my json.php
<?php
$link = mysql_pconnect("localhost", "root", "") or die("Could not connect". mysql_error());
mysql_select_db("people") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM nom");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":',json_encode($arr),'}';
/*
//The json object is :
{"users":[{"id":"1","prenom":"Alain","age":"23"},{"id":"2","prenom":"Bruno","age":"24"}]}
*/
?>
Then I try to parse it into java
<div id="placeholder6"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('http://localhost/json.php', function(data) {
var output="<ul>";
for (var i in data.users) {
output+="<li>" + data.users[i].id + " " + data.users[i].prenom + "--" + data.users[i].age+"</li>";
}
output+="</ul>";
document.getElementById("placeholder6").innerHTML=output;
});
</script>
when I replace localhost/json.php by the result in a file data.json, it works, when I open localhost/json.php with firefox, I can see the JSON table...so I do not know why it does not work with localhost/json.php.
Is my php code or javascript code wrong ?
Thanks in advance for your help !

Try this method
var users= data.users;
$.each(users,function(index,users){
console.log(users.prenom); /// and users.id etc
})

Try This in php
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
$return = new stdClass();
$return ->users = $arr;
echo json_encode($return);

I think your web application server (like Apache or nginx) sends Content-Type: text/html by default or something of that sort for your json.php file. On the other hand, it looks like $.getJSON method requires a application/json content type field.
Try adding:
header("Content-Type: application/json");
to the top of the json.php file.
Edit - additional info:
I couldn't find in the original documentation of the $.getJSON method whether it, in fact, requires the specific Content-Type so I looked into the source code:
https://github.com/jquery/jquery/blob/1.7.1/src/ajax.js#L294
Here is the line of source code for jQuery 1.7.1 (which is the version you said that you use, I hope) for getJSON and as you can see, it calls jQuery.get with the last argument set to "json".
In turn, the jQuery.get documentation reveals that this argument means:
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
from: http://api.jquery.com/jQuery.get/
Thus, when you call $.getJSON("/url/to/file", ...) that first argument is expected to be a JSON. If you add the PHP code from the top of my answer, your web application server will mask the output of the php file as a JSON.

Related

Pull mySQL data via PHP into an array of Javascript objects

i am trying in pull my data from mySQL and convert it to a format I can then pass to google.maps API. I am thinking mySQL -> php -> javascript -> google.maps makes the most sense but am deffinitly open to other suggestions.
So far I have connected to and successfully queried my data into an array
<?php
//library of mysql functions including linkDB()
include('../sqlFunctions/sqlFunctions.php');
//Establish connection to database
if($link = linkDB()){
echo "connected to DB";
}
//set up a MySQL query. I am simply pulling geocoordinate ints, strings and boolean.
$sql = "SELECT title
,lat
,lng
,titleYou
,descriptionAre
,privacyRockstar
FROM shelters;";
if($results = $link->query($sql)){
echo "<p>Query succsessful.</p>";
}else{
echo "Query Failed";
}
//initialize an array to store data
$rows = array();
while ($data = $results->fetch_assoc()) {
$rows[] = $data;
echo "<br><br>Loop rotation: ";
var_dump($data);
}
echo "<br><p>The End of The Loop<p><br>";
var_dump($rows);
?>
Now I just need to convert this data into something usable I can pass to google.maps.
Before I was pulling JSON from a text file, which worked, but I want to flexibility and stability of a database. It was easy to parse into and array of Javascript Objects. Then I could just call the index and the property that I needed as you can see from this function I was using.
function setMarkers(){
for(i=0; i < jsonParsed.arrayOfObjs.length; i++){
//setting parameters to hand to google
var markerOptions = {
position : jsonParsed.arrayOfObjs[i].position,
map : mapCanvas,
description : jsonParsed.arrayOfObjs[i].title,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
};
//create marker
this ['marker' + i] = new google.maps.Marker(markerOptions);
}
}
Thank you for any light you can help shed on my issue.
It sounds like you already found your answer but I'll post for completeness.
Simply change your the var_dump($rows) line to json_encode($rows).
Read more about json_encode in the php docs.
You probably want to have two php files:
api.php file that emits Content-type: application/json
index.php file that emits Content-type: text/html and calls api.php
On the index page, you can make an AJAX call to your API endpoint and then use JSON.parse(response).

How can I send HTML data to PHP using JSON?

I can't seem to understand how to send data from my Client-side HTML to my Server-side PHP (Which already means their not in the same folder and are not running in the server) and only get a Notice of an unidentified variable and a Fatal error: Cannot access empty property.
I tried the methods in W3Schools and still no luck. And just to be sure I tried to copy paste it. Still the same.
So my question is: How can I send this simple Client-side HTML/JavaScript data:-
<script>
function sender(){
obj = "tblname";
// how to send that data to the php server-side.
}
</script>
To this PHP:-
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "root", "", "mydb");
$result = $conn->query("SELECT * FROM ".$objData);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
Using JSON?
If anyone could elaborate and show me a sample it would be great.
Again, I am a noob/newb in using JSON and have no long term background (I just started like a week ago and that had a lot of problems already) and am completely clueless when it comes to this type of client-to-server communication.
I Just need the simple sender code (from the JavaScript) and the receiving code (from the Php) one or two lines will do; with a short description on how they work.
I'm using Windows 7, Wamp3.0.6 and Chrome.
PS: I got that from W3Schools. Yes it didn't work. And please don't be Vague. Thank you!
You can make ajax call form client side to server file and can send data with get method
// Using the core $.ajax() method
$.ajax({
// The URL for the request
url: "path of your php file",
// The data to send (will be converted to a query string)
data: {
id: 123
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
dataType : "json",
})
// Code to run if the request succeeds (is done);
// The response is passed to the function
.done(function( json ) {
})
// Code to run if the request fails; the raw request and
// status codes are passed to the function
.fail(function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
})
// Code to run regardless of success or failure;
.always(function( xhr, status ) {
alert( "The request is complete!" );
})
-_-
Everyone seems to try and over complicate and over think this when the simple answer would have been this code.
function caller(){
myData = "myTbl";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "bring.php?q="+myData,true); //sends myData to the php. You can change the GET to POST if ya want to be extra safe but either way, the php won't care anyways.
xmlhttp.send();
}
The above code is from the client server and sends the data of myData to this Server-side php.
<?php
$q = $_REQUEST['q']; //the receiver of the data. You can use explode() to separate them into pieces and turn it into a jigsaw puzzle if ya want.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} // how to connect is not important in my question but it is important for you to be able to connect to the database.
// now for the important stuff
$sql = "SELECT * FROM ".$q." "; // I had to extend it with a space because sometimes it's misunderstood.
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
$outp = array();
while($row=mysqli_fetch_assoc($result))
{
$outp[] = $row;
}
echo json_encode($outp); //sends the data gathered from the database table back to the client as a JSON file, and you are done.
?>
It took me 6 hours worth of studying with a lot of internet surfing and trials and errors.
And like I said; I am a newb at JSON so it's pretty much understood that I don't understand AJAX. Like, AT ALL.
I'm sorry if ya think I sound like an idiot but let's face it, almost all of us were idiots at one point while trying to learn programming. So, I'm surprised why some people are just plain rude here. Thanks. Somehow I'm not really surprised that their also like this here. Makes my internet social life a bit more boring.
So next time, do me a favor and instead of being totally rude, just answer the question if you have one.
You cannot transfer an object via HTTP as it is. You need to transform it into a string you can put into the body of your HTTP-POST Request:
try {
var jsonString = JSON.stringify(anyJsonObject);
//send it to the server
} catch(ex) {
//handle error if anyJsonObject wasn't a valid JSON object. Remember: Not every JS object is a JSON object too.
}
The opposite way is:
try {
var jsonObject = JSON.parse(anyJsonString);
} catch(ex) {
//handle error if anyJsonString was malformed
}

Server error 500 in PHP

So today I have another small little issue with my PHP, that is causing me to get a server error. You see, I have this javascript function:
$.post('script.php', { limit: str }, function(result) {
console.log(result);
});
which of course makes a call to my php file:
require_once("../data/db-settings.php");
require_once("../data/file.php");
global $pdo;
$list = array();
$limit = $_POST["limit"];
chop($limit, ";");
$stmt = $pdo->prepare("SELECT cust_id, cust_addr FROM project WHERE " . $limit . " = cust_id");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$list[] = $row;
}
echo $list;
The point of the php is to grab some information from a database that a user can dynamically change and use. The issue, I'm assuming, is with how I'm using PDO, because the code I'm using is in working order in another section. I also know that my function call is sending data and working properly, because when I check for just what I send, it sends properly.
Thanks for any help guys.
Check your query FROMproject can not be together.
Your query should look like this:
$pdo->prepare("SELECT cust_id, cust_addr FROM project WHERE " . $limit . " = cust_id");
It is an unobvious error!
So you step by step following the : http://pcsupport.about.com/od/findbyerrormessage/a/500servererror.htm
PDO doesn't throw Internal server error. Must be require_once.
checkout db-settings.php and file.php files. Require_once throws 500 error if it can't find files.
If the paths are correct, then check out included files.
proper way: check your log files.

AngularJS JSON not arriving php

i am having the following problem, i have a service that makes a http request, and when i try to get the response throws a parser error, and that is because the response is not ready when it tries to parse the response.
here is the code
simpafAPIservice.getSimulacao($stateParams.id).success(function(response){
console.log(JSON.stringify(response[0].info));
$scope.simuladorInfo.cliente = response[0].cliente;
$scope.simuladorInfo.info = JSON.parse(response[0].info);
console.log(JSON.stringify(response[0].info));
setTimeout(function(){
for(var i=0;i<$scope.simuladorInfo.info.simuladores.length;i++){
$scope.addDataGraphic(i);
}
},100);
});
}
When i console.log the response it prints an empty string, which is odd, that's why it throws this parser error.
My question is how can i do .success function only when the response is ready?
Edit:
in the end the problem is other, i am storing a JSON in a database, but when the JSON has very information it doesn't arrive at php.
here's my php code:
<?php
$id = $_POST["id"];
$id_col = $_POST["id_col"];
$tipo = $_POST["tipo"];
$cliente = $_POST["cliente"];
$info = $_POST["info"];
date_default_timezone_set("Europe/Lisbon");
$data = date("Y-m-d H:i:s");
require 'connection.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if($id!=""){
$sql = "UPDATE `Simulacoes` SET `info`='".$info."' WHERE `id`='".$id."'";
}else{
$sql = "INSERT INTO `Simulacoes`(`id_col`, `tipo`, `data`, `cliente`, `info`) VALUES ('".$id_col."','".$tipo."','".$data."', '".$cliente."', '".$info."')";
}
if ($conn->query($sql) === TRUE) {
echo $info;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
?>
here's the response i get:
{"data":"","status":200,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"params":{"id_col":"1","tipo":"Património Reforma","info":{"simuladores":[{"nome":"ii","info":{"prazoReforma":20,"empreendimentos":{"empreendimentos":[{"id":"1","nome":"Oporto Place","localizacao":"Porto","$$hashKey":"object:50"}],"tipologias":{"0":"Loft","19":"T2","37":"T3"},"plantas":{"0":"3.1","1":"6","2":"8","5":"3.2","12":"2.1","13":"7","14":"2.2","15":"5"},"pisos":[{"id":"2","piso":"1","$$hashKey":"object:69"}]},"entrada":"20000","duracao":"35","taxa":"5","montante":82000,"prestacao":"414","prestacao_seguros":"440","renda_liquida":"320","resultado":-120,"patrimonio":134367},"$$hashKey":"object:38","imovel":{"empreendimento":{"id":"1"},"tipologia":"Loft","planta":"3.1","piso":"2","info":{"condominio":"50","renda":"400 ","preco":"102000 ","id":"1"}},"hide":1}],"montanteTotal":134367,"pensao":"569","idadeActual":"45","idadeReforma":"65","pmII":120,"pmTotal":120}},"url":"php/guarda-simulacoes.php","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"OK"}
As you can see, when i echo $info it returns nothing, an empty string, but in data.config.params i get all params. Anyone knows why is this happening?
Your codes looks ok, which is taking promise from And executing code in its success. I think instead of setTimeout you should use $timeout which will run $digest cycle when timeout complete
Code
simpafAPIservice.getSimulacao($stateParams.id).success(function(response){
console.log(JSON.stringify(response[0].info));
$scope.simuladorInfo.cliente = response[0].cliente;
$scope.simuladorInfo.info = JSON.parse(response[0].info);
console.log(JSON.stringify(response[0].info));
$timeout(function(){
for(var i=0;i<$scope.simuladorInfo.info.simuladores.length;i++){
$scope.addDataGraphic(i);
}
},100);
});
}
According to the docs, $http.success returns data in the first argument, which is converted to JSON only if the active transformResponse can detect is is the appropriate format:
Angular provides the following default transformations:
...
Response transformations
($httpProvider.defaults.transformResponse and
$http.defaults.transformResponse):
If XSRF prefix is detected, strip it (see Security Considerations
section below). If JSON response is detected, deserialize it using a
JSON parser.
If your server is responding with an empty string (which seems the case here)
then it will not be detected as a JSON object and will remain an empty string.
Check your server response, it may be responding with no body and an error status. One thing to watch for if you are requesting data from a different domain (even if it's ultimately the same server) is same-origin policy.

Possible to make a php string into XML and send to JavaScript?

I want to form a string in my php server code as xml, and then send it to javascript so that ajax.responseXML can navigate through it and do things with the data. I haven't been able to find exactly what I need to accomplish this and have tried a few different methods. Here's the most recent thing I've tried.
<?php
header("Content-type: text/xml");
$xmlstring = "<?xml version'1.0' encoding='UTF-8'>";
$xmlstring = $xmlstring . "<book name='$name' author='$author'>";
foreach($rankings as $entry)
{
$xmlstring = $xmlstring . "<rank>$entry</rank>";
}
echo $xmlstring;
?>
I know the data is getting there because if I echo it as a string and open it directly, the numbers I need are getting printed. I'm using Ajax.Request to open the php file with certain parameters, and when it reaches the onSuccess function, ajax.responseXML is null. This is my first time dealing with xml so I could be doing something stupid.
function that makes the call:
function findRankings(author, name)
{
new Ajax.Request("server_code.php",
{
method: "get",
paramters: {"type": "rank", "name": name, "author": author},
onSuccess: makeGraph,
onFailure: ajaxFailed
});
}
function makeGraph(ajax)
{
alert(ajax.responseXML); // testing that it made it
.....// do stuff with the response
}
EDIT: I added the header and made it echo just the string. I also added the ajax functions. I keep getting null though. :(
As Dustin said, you need to echo $xmlstring; instead and add header('Content-Type: text/xml');
But you also have a couple of errors in your XML declaration. You're missing a = and a ?:
$xmlstring = "<?xml version='1.0' encoding='UTF-8'?>";
I'd recommend using an XML validator in future.
You used simplexml_load_string, which converts your XML string to an object.
Just echo your $xmlstring
For clean coding you should insert header('Content-Type: text/xml'); as #Twisty mentioned.

Categories