I have a PHP script in which I get the content of a query made into a Postgresql database :
<?php
require_once 'connection.php';
$query1 = pg_query("This_is_my_query");
$instruction = "[";
while ($row = pg_fetch_array($query1)) {
$row1= $row['row1'];
$row2= $row['row2'];
$instruction .= "{name : '". $row1. "', y : ". $row2. "},";
}
$instruction .= "]";
echo $instruction;
?>
The echo $instruction gives :
[{name : 'Prestation', y : 1}]
Then I have a JS file in which I try to display and use the $instruction variable.
I use Ajax and my script is the one :
$.ajax({
url : 'Path_To_Php_File_Is_OK', // requesting a PHP script
dataType : 'json',
type: "GET",
async : false,
success : function (data) { // data contains the PHP script output
alert(data);
},
error: function(data) {
alert('error');
},
})
The result is that the success function is not called and I have the alert('error').
But when I use the dataType 'text' and not 'Json', the success function is ok and I have the alert(data).
How to explain that behaviour ? And how could I parse the PHP variable $instruction ?
Any help would ve very appreciated, thanks !
There is no need to create a json string manually. Just build up and array and encode it to json with json_encode()
You have to set JSON content-type in the response headers
Closing ?> tag is redundant and is not recommended to use (see PSR-12)
So eventually your code should look like this
<?php
require_once 'connection.php';
$query1 = pg_query("This_is_my_query");
$instructions = [];
while ($row = pg_fetch_array($query1)) {
$row1 = $row['row1'];
$row2 = $row['row2'];
$instructions[] = ['name' => $row1, 'y' => $row2];
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode($instructions);
Related
I ideally want the Ajax result to be converted from Jsonstring to OBJ Thank You in advance.
I know the AJAX GET script is working becuase when I alert the Ajax Post result I see the Contents in json string format as below.
alert(JSON.stringify(data));
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I want the AJAX GET result data converted to look like this in OBJ format like below.
{id:31,name:"Mary",username:"R8344",email:"wemail}];
PHP/SQL CODE with the Json encoded Array
<?php
include "../mytest/config.php";
$return_arr = array();
$sql = "SELECT * FROM users ORDER BY NAME";
$result = $conn->query($sql);
//Check database connection first
if ($conn->query($sql) === FALSE) {
echo 'database connection failed';
die();
} else {
while($row = $result->fetch_array()) {
$id = $row['id'];
$username = $row['username'];
$name = $row['name'];
$email = $row['email'];
$return_arr[] = array(
"id" => $id,
"username" => $username,
"name" => $name,
"email" => $email);
}
// Encoding array in JSON format
echo json_encode($return_arr);
}
?>
php echo _encode array above returns below Json string format
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I am looking for something like below.( top half of the script)
<script>
$(document).ready(function(){
$.ajax({
url: 'ajaxfile.php',
type: 'get',
dataType: 'JSON',
success: function(result){
var data =(JSONstring convert to OBJ(result);
//-----The top half of script -------------
$.each(data, function( i, person ) {
if(i == 0) {
$('.card').find('.person_id').text(person.id);
$('.card').find('.person_name').text(person.name);
$('.card').find('.person_username').text(person.username);
$('.card').find('.person_email').text(person.email);
} else {
var personDetailCloned = $('.card').first().clone();
personDetailCloned.find('.person_id').text(person.id);
personDetailCloned.find('.person_name').text(person.name);
personDetailCloned.find('.person_username').text(person.username);
personDetailCloned.find('.person_email').text(person.email);
$('.card-container').append(personDetailCloned);
}
});
});
</script>
I will need help with the closing tags as above is just an example
The solution is:
success: function(result){
data =(result);
There was no need o convert the data to OBJ or anything ( blush). Then the code on the 2nd half of the Ajax script will receive the data and populate. Thanks to all contributors.
I've looked around on the internet for answers, but I couldn't find any specific to my situation. As mentioned in the title, i'm trying to retrieve and then display a certain value from mysql database.
Disregarding the security measures which I will add later on, I've managed to retrieve the data, but when I send it back to the javascript and alert it, this value is returned: {"acc_points":"5"}. I would like it it to be just "5", is there any way that I can do this? Thanks!
Here are the codes:
js file
$(document).ready(function() {
$("#viewpoints").click(function() {
{
$.ajax({
type: "GET",
url: "http://127.0.0.1/MP/apppoints.php?callback=?",
dataType: 'JSONP',
async: false,
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function jsonpcallback(response)
{
alert(JSON.stringify(response));
}
})
}
});
});
php file
<?php
header('Content-Type: application/json');
require 'dbcon.php';
session_start();
$acc_id = $_SESSION["acc_id"];
$sql = "SELECT acc_points FROM points WHERE acc_id = '$acc_id'";
$result = mysqli_query($con, $sql);
$acc_points = mysqli_fetch_assoc($result);
if($acc_points != null)
{
$response = $acc_points;
echo $_GET['callback'] . '(' . json_encode($response) . ')';
}
else
{
$response = "Failed. Please try again.";
echo $_GET['callback'] . '(' . json_encode($response) . ')';
}
//connection closed
mysqli_close ($con);
?>
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.
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"); }
});
});
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.