jQuery reading JSON Data - javascript

So I have a database pass a whole bunch of data using PHP back to jQuery through JSON.. I'm trying to access individual columns from the returned data but no luck..
My PHP:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
Here's my JS:
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
success:function(data){
$('.quoteList').append(data[0]);
}
});
}
Currently that appends the following to the element:
[{"id":"1","text":"The most wasted of all days is one without laughter.","author":"E.E. Cummings","status":"1"}]
So for example.. if I wanted the jQuery to go through data[0] to data[92] (the last one) and append the author of each to .quoteList, how could I do that? I've tried data[0][1] and data[0][author]

You can use $.each() to loop through the data and append the author:
$.each(data, function(i) {
$('.quoteList').append(data[i]['author']);
});

The PHP might be defective because json_encode is called twice, and this is unusual. As written this would be flattening the rows into JSON strings, but mere strings nonetheless, which then get JSON encoded again into an array of strings. This is probably not what you intended, as it would be making it possible to print the received data but not access the components of rows which will be decoded to strings and not objects.
Compare https://stackoverflow.com/a/6809069/103081 -- here the PHP echoes back a callback with a single JSON object inside parenthesis ().
I suspect the fix looks like https://stackoverflow.com/a/15511447/103081
and can be adapted as follows:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
Once you have this, you should be getting back proper JSON for your array of objects and be able to use #Felix's code on the client side.

you need to use loop on your data, try this
success:function(data){
for (var i in data) {
$('.quoteList').append(data[i]);
}
}

This should work:
(upd. all code:)
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
contentType: "application/json",
success:function(data){
var str = "";
$(data).each(function(index, item){
str += item.author + " ";
});
$('.quoteList').append(str);
}
});
}

Your problem is here:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
you need something like this:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
$myjsons['callback'] = $_GET['callback'];
echo json_encode($myjsons);

Related

Accessing PHP JSON response using Javascript

Is this valid approach: I want to keep api key from being accessible via source code so I have been trying to keep it hidden with PHP and use Javascript to display data. (I prefer to use js syntax to display data) I've been able to display data successfully but when I look at the source code I can see the JSON response. Can anyone tell me if this is a valid approach and why not good idea to have json shown in source?
<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
$json = json_decode($data,true);
?>
I then access the response like so:
<script type="text/javascript">
var data = <?php echo json_encode($json) ?>;
$('.in-theaters-soon').append('<p>' + data.movies[0].title + '</p>');
</script>
You can directly echo the values from PHP since you already have the response in $json. For example:
<div class="in-theaters-soon">
<p><?php echo $json['movies'][0]['title']; ?></p>
</div>
Always make some validation of the printed data.
<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
if (is_array($data) && ! empty($data)) {
/**
* Do something.
/**/
}
You could do something like this if you have the php in a separate file.
Your php file.
<?php
// create a token check to make sure it is being called.
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
echo json_encode($data);
?>
Then query your php file something like this sending a token or something similar.
$.ajax({
url: url,
type: 'POST',
data: {token:token},
success: function(data){
var response = $.parseJSON(data);
for(var x = 0; x < response.length; x++){
$('.in-theaters-soon').append('<p>' + response[x].title + '</p>');
}
},
cache: false,
contentType: false,
processData: false
});
Hope this helps.

How to read data from in Javascript

I'm trying to use Javascript to read stock data from yahoo finance at "http://table.finance.yahoo.com/table.csv?s=000001.sz", which returns a csv file and convert the data into json format as in http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback=? to be used in highcharts.
I tried using $.ajax get and jquery.get but neither worked. Can somebody tell me how to read the data from the url and convert it into json? Thanks a lot.
This can be easily done with PHP.
<?php
file_put_contents("data.csv", fopen("http://table.finance.yahoo.com/table.csv?s=000001.sz", 'r'));
//reads the CSV file and save value into an associative array
function csv_to_array($filename = '', $delimiter = ',')
{
if (!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
if (!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$arr = csv_to_array('data.csv');
//<pre></pre> tags appear only to prevent white-space collapsing
//prints the associative array
echo "<pre>";
print_r($arr);
echo "</pre>";
//displays the the JSON
echo "<pre>";
echo json_encode($arr, JSON_PRETTY_PRINT);
echo "</pre>";
?>
Now depending on the format of JSON that it acceptable to Highcharts API, you are required to tweak how the array is encoded into JSON.
Also avoid using JSON_PRETTY_PRINT if the size of the incoming data is large.
I guess you are facing Cross Domain issue. Use jsonp calls for Cross Domain requests. Use something like this
$.ajax({
url : "http://xx.xx.xx.xx/xxx/xxx",
type: "GET",
dataType: "jsonp",
jsonp : "callback",
success: function(data) {alert("Success");},
error: function(data) { alert("Error"); }
});
});

How to Pass Two Values From PHP to Ajax

Can you please let me know how I can pass Two Values from PHP file into a jQuery Ajax script. What I have is a Ajax call as:
<script>
$(function() {
var req = $.ajax({
url: 'captcha.php',
});
req.done(function(data){
alert(data);
})
});
</script>
and my PHP (captcha.php) is like:
<?php
$number1 = rand(1,9);
$number2 = rand(1,9);
$sum = $number1 + $number2;
echo $number1;
?>
as you can see currently I am able to pass the value of the $number1 but I need to have both values($number1 and $number2). Can you please let me know how to achieve this?
Thanks
Instead of sending (invalid) HTML to the client, use a structured data format, such as JSON.
<?php
header("Content-Type: application/json");
$data = Array($number1, $number2);
print json_encode($data);
exit;
In the JavaScript, jQuery will now populate data with an array.
Why don't you make an array containing variables to return and json_encode it to parse it in JS?
echo json_encode(array($number1, $number2));
Make an array out of your values:
$array = array($number1, $number2);
Then parse it to json
$json = json_encode($array);
Then echo out the $json and you have multiple variables in your js!
<script>
$(function() {
var req = $.ajax({
url: 'captcha.php',
});
req.done(function(data){
data = data.split(",");
//Number 1
alert(data[0]);
//Number 2
alert(data[1]);
})
});
</script>
<?php
$number1 = rand(1,9);
$number2 = rand(1,9);
$sum = $number1 + $number2;
echo $number1 .",". $number2;
?>
All this does is tells the php script to echo Number1,Number2 and then the javascript splits this string into an array from the ,
First Way
You can concatenate the two values seperating them by a special character like '_' like this
PHP
echo $number1 . '_' . $number2;
And then do like this in javascript
data = data.split('_'); // get an array with the two values
Second way
You can encode as JSON in php and do a json ajax request
PHP
$result = array($number1, $number2);
echo json_encode($result);
Javascript
$.getJSON('captcha.php',function(data){
console.log(data); //
});

Send image from localstore to mysql with ajax post

I'm trying to send a picture stored in localstore with javascript but can't retrieve it and show it.
Javascript part :
liste['pic'] = localStorage['pic'];
$.ajax({
type: "POST",
url: "save.php",
data: { pic : liste['pic'] },
dataType: "json",
success: function(data) {
if(data) {
alert("Picture sent succesfully");
}
}
});
The php part that receive the data :
require "lib/connect.php";
$pic = $_POST['pic'];
$insert_query = "INSERT INTO liste ( `pic` ) VALUES ( '".$pic."' );";
$result = mysql_query($insert_query);
The php part that shows the pic.
There's something in the table but since it's blob , I can't check if the right data.
$select_query = "Select `pic` From liste;";
$result = $dbhandle->query($select_query);
echo "<table border='1'>
<tr>
<th>Image</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td><img src=\"" . $row['pic'] . "\" width=\"200\"/><br/><br/></td>";
echo "</tr>";
}
echo "</table>";
$result->closeCursor();
mysqli_close($dbhandle);
from this I get a broken image. What is missing ? Text works but not image, why ?
What you need to know is that when you are sending values encoded in json through POST, these values are not present in the $_POST variables.
The only way to have values in the POST variables is by using having the application/x-www-form-urlencoded and multipart/form-data.
If you wish to use another content-type, you actually need to use 'php://input'.
e.g.
$data = json_decode(file_get_contents('php://input'), true);
$text = print_r($data, true);
You should then see an array containing your image's data.

How to get my data back

I'm new to dynamic data and trying to
read data from a mysql database using PHP
turning this data to JSON
fetching the data through javascript (jQuery)
Inserting it into my page.
As far as I can see, 1) and 2) work fine, 3) seems to kind of work and 4) is where it breaks.
I've set up the database and the table, query & echo the data like so (api.php)
<?php
include 'db.php';
$con = new mysqli($host,$user,$pass,$databaseName);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM $tableName";
$myArray = array();
if ($result = $con->query($query)) {
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
$result->close();
$con->close();
?>
Now I get it through javascript...
jQuery(function($) {
$.ajax({
url: 'php/api.php',
data: "json",
dataType: "",
success: function(data) {
var r = new Array(), j = -1;
for (var key=0, size=data.length; key<size; key++){
r[++j] ="<tr><td>";
r[++j] = data[key][0];
r[++j] = "</td><td>";
r[++j] = data[key][1];
r[++j] = "</td><td>";
r[++j] = data[key][2];
r[++j] = "</td></tr>";
}
var joined = r.join('');
console.log(joined);
$('#maintable tbody').html(joined);
}
});
});
... and throw it in the tbody element of my table.
The result is absolutely not what I expected:
See http://i.imgur.com/hRNrmdC.jpg (sorry for the partly german interface)
The Answer to the GET request is valid JSON, at least in theory (checked by http://jsonlint.com/ ), but to me it seems the data is treated as a string and split into an array of chars (each char a "key" in data[]), therefore "data[key][1] returns nothing.
var json = JSON.stringify(eval("(" + data + ")"));
and continuing with json[key][0] didn't help...
Now I wonder why and especially, what went wrong and how its fixed.
You have mixed up the keys in your ajax call:
data: "json",
dataType: "",
Should be:
dataType: "json",
as you are not sending or using any data at all.

Categories

Resources