Accessing PHP JSON response using Javascript - 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.

Related

Sending data from front-end to back-end to front-end

Hi i'm a beginner in using JavaScript i have this html page with JavaScript codes that receives data from the server and display it on this current page, what i'm trying to do is use that data and sending it to another PHP page for my SQL query to get back results.
<script>
var json = sessionStorage.xhr;
var object = JSON.parse(json);
var hard = object["red-fruits"];
var string = JSON.stringify (hard);
var stringData = encodeURIComponent(string);
$.ajax({
type: "POST",
url: "http://localhost/web/main.php",
data: {"dataA" : stringData},
cache: false,
success: function(){
console.log("OK");
}
});
var user = sessionStorage.getItem('impData');
console.log(user);
</script>
This is my PHP page codes, what i'm doing here is getting the data "dataA" from that html page and sending it to this PHP page for the SQL query and getting the results which is the "$haha" array and using JavaScript session function to send it back to the HTML page. But my console only shows "null" can anyone tell me if i'm doing anything wrong or have any suggestion would be really appreciated.
<?php
$connection = mysqli_connect("localhost","root","","") or
die("Error " . mysqli_error($connection));
if (isset($_POST['dataA'])) {
echo $name = $_POST['dataA'];
}
else {
echo "Error";
}
$string = str_replace("]", "", str_replace("[", "", str_replace('"','',$falcon)));
$array = explode(',', $string);
$array2= implode("', '",$array);
$sql = // "SQL query"
$result = mysqli_query($connection, $sql) or die("Error in Selecting " .
mysqli_error($connection));
while($row = mysqli_fetch_array($result)) {
$haha[] = $row['row_name'];
}
?>
<script type="text/javascript">
var tills = <?php echo '["' . implode('", "', $haha) . '"]' ?>;
console.log (tills);
sessionStorage.setItem('impData', tills);
</script>
You are now mixing ajax and session data on a strange way. The session data used by your javascript will not be updated by the php-script till you refresh your page. The correct way to handle data is in the "success" function:
$.ajax({
type: "POST",
url: "http://localhost/web/main.php",
data: {"dataA" : stringData},
dataType : "json",
cache: false,
success: function(data){
console.log(data);
}
});
and in you PHP output the data you want to send to the browser as a json string:
echo json_encode($your_object);

Saving data into a text file sent as JSON with Ajax

I have currently a problem with my code. I would like to send JSON data with Ajax to a PHP script but it doesn't work. What does work is that the PHP script can be called by the Ajax code but it can't put the code into the .txt file. I have tried several things but I can't get it working. (I am trying to set the users array in the .txt file)
jQuery code:
var users = [];
$.ajax({
type: "POST",
url: hostURL + "sendto.php",
dataType: 'json',
data: { json: JSON.stringify(users) },
success: function (data) {
alert(data);
}
});
PHP Code:
<?php
$json = $_POST['json'];
$data = json_decode($json);
$file = fopen('test.txt','w+');
fwrite($file, $data);
fclose($file);
echo 'Success?';
?>
You must know that in PHP json_decode generates an Array that you can't write into an text file.
So only remove the json_decode command.
Since json_decode() function returns an array, you can use file_put_contents() that will save each array element on its own line
<?php
$json = $_POST['json'];
$data = json_decode($json, true);
file_put_contents('test.txt',implode("\n", $data));
?>

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); //
});

jQuery reading JSON Data

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);

Categories

Resources