GetJSON not working with PHP file - javascript

I am trying to use the getJSON function with a PHP file that echo some JSON. If I save the JSON expected from the PHP file as a JSON file, it works perfect but if I use the PHP file as URL it doesn't work because it fails when parsing the PHP at line 1 column 1.
PHP file:
<?php
$jsondata = array();
if( isset($_GET['param']) ) {
if( $_GET['param'] == 'valor' ) {
$jsondata['success'] = true;
$jsondata['message'] = 'Correct.';
} else {
$jsondata['success'] = false;
$jsondata['message'] = 'Incorrect.';
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($jsondata);
exit();
}
?>
And this is what I am using in the Javascript file:
$.getJSON('test.php', {format: "json"}, function(data) {
window.alert("Loaded");
}).fail( function(data, textStatus, error) {
console.error("getJSON failed, status: " + textStatus + ", error: "+error)
});
If I change from test.php to test.json it works.
EDIT: I was using mysql instead of mysqli and the server outputted a table and then my JSON and thats why I had the JSON Error parse ...
Fixed just changing from mysql to mysqli.
Thanks everyone.

Try this:
if( $_GET['param'] == 'valor' ) {
$row = array('success'=> true,'message'=>'Correct');
array_push($jsondata,$row);
} else {
$row = array('success'=> false,'message'=>'Incorrect');
array_push($jsondata,$row);
}
And the echo remains the same:
echo json_encode($jsondata);
I've coded like this when I had to work with JSON and PHP with JQuery.I hope it works for you too.

Related

Using extra php files to get the ajax post request and then load the php script

i have a task which is very complicated for me and also explain to you.. I will give my summary on what i m supposed to do.. there are 3 files which are the
1.html file which perform ajax post to the passwrapper.php
2. passwrapper.php will receive the ajax post request and include another file which is 3.student.php which contain codes on how to perform connection to the database and convert all data to json and then show all the data..
I was asked to perform ajax post multiple items.. In other words, i was asked to receive name and religion from the last row of database.. here is my code below...
html file
<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<div id="resulte"</div>
<script type="text/javascript">
showData();
function showData()
{
$.ajax({
type: "post",
url: "passwrapper.php",
dataType: "json",
data: {
lastName: true,
lastReligion: true,
},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
$('#resulte').html('<p>Status Code: '+jqXHR.status+'</p><p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
});
};
</script>
</body>
</html>
passwrapper.php
<?php
include 'student.php';
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"]))){
executePass();
}
else
{
//how to get name and religion from the last row and then perform executepass() to show all data and also data from the last row
}
?>
student.php
<?php
function executePass()
{
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
}
my question is how to get last data from the last row which are student_name and student_religion in the passwrapper.php and also perform executepass() to show all data... please do not modify the sql code. i also do not want get data from the success. for example: data[count(data)-1]['student_name']...
my question is how to get the last values which are student_name and student_religion in the passwrapper.php... and also perform the executepass() function to show all data.. please help me... you can write the last data to the files or show in the html console..
Best would be to change executePass() so it ends with return $json_array; instead of echoing it. Then passwrapper.php could do:
$students = executePass();
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"]))){
echo json_encode($students);
}
else {
file_put_contents("all_students.json", json_encode($students);
$last_student = end($students);
echo json_encode(array($last_student));
}
And other scripts that want to return all the students can do:
$students = executePass();
echo json_encode($students);
If you can't do that, use the output buffering functions to capture the output from executePass() instead of sending it to the client.
else {
ob_start();
executePass();
$json = ob_end_clean();
file_put_contents("all_students.json", $json);
$students = json_decode($json, true);
$last_student = end($users);
echo json_encode(array($last_student));
}

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

Jquery Error parsing Json data

I'm having an error parsing a JSON response from PHP.
Javascript:
function getStock()
{
var color = $("#select_color option:selected").val();
var comp = "<?= $idComp ?>";
$.post( "ajax/getStock.php",
{
idColor: color,
idComp: comp
}).done(function( data )
{
alert(data);
var obj = jQuery.parseJSON(data);
$('#stockReal').val(obj.StockReal);
$('#stockMinimo').val(obj.StockMinimo);
$('#stockMaximo').val(obj.StockMaximo);
});
}
PHP:
<?php
require_once "../../helper/db.php";
require_once "../../helper/security.php";
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(!empty($_POST['idColor']) && !empty($_POST['idComp']))
{
$idComponente = test_input($_POST['idComp']);
$idColor = test_input($_POST['idColor']);
$conn = db_connect($STOCKMANAGER);
$sql = "SELECT * FROM TableStock
WHERE idComponente = '$idComponente'
AND idColor = '$idColor';";
$stock = db_request_one($conn, $sql);
if($stock !== 0)
{
$respuesta = array('StockReal'=>$stock->StockReal
,'StockMinimo'=>$stock->StockMinimo
,'StockMaximo'=>$stock->StockMaximo);
echo json_encode($respuesta);
}
else
{
$respuesta = array('StockReal'=>''
,'StockMinimo'=>''
,'StockMaximo'=>'');
echo json_encode($respuesta);
//echo $respuesta;
}
}
}
?>
The error:
Uncaught SyntaxError: Unexpected token ... jquery-1.10.2.js:550
When I get data from alert for example I get:
{"StockReal":"33","StockMinimo":"0","StockMaximo":"55"}
This is a good Json data. But if I try to validate with http://jsonlint.com/ i get the next error message:
Parse error on line 1:
^
Expecting '{', '['
Also when I try to stringify the Json Data I get a lot of u0000\ before and after the data.
like this:
"\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000{\"StockReal\":\"33\",\"StockMinimo\":\"0\",\"StockMaximo\":\"55\"}\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000"
Can anyone help me?
Have you done an output of what is returned from $respuesta array? print_r($respuesta) and see what's in your array.
Also make sure you have NO white space in your getStock.php file.

PHP to Jquery through json ruins array

I'm trying to perform some PHP code and then pass it's results to another PHP script through jquery.
One of these results is an array, and I'm passing it to a GET so it gets to the other script. (alot of work, but I can't have page reloads even tho I have to use PHP).
The problem occurs when I'm trying to put the PHP variable through JQuery.
What I have to do this for me is:
var _leafs = <?php echo json_encode($leafs); ?>;
When I run json_encode on $leafs and then print the result (all using PHP), it gives me a json array that has been successfully validated by JSONLint.
When I use the above code and alert() the result it's missing the brackets and quotes.
Even weirder is when I pass it through like so:
$.get('set_fields.php?pt=' + _path + '&lf' + _leafs, function(data) {
The result is this:
" string(4) "
"
Which shows up to be a <br> in my html reader.
Am I missing something when I'm converting it to json?
Additional code:
<?php
// Fetch the XML from the URL
if (!$xml = file_get_contents($_GET['url'])) {
// The XML file could not be reached
echo 'Error loading XML. Please check the URL.';
} else {
// Get the XML file
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
$paths = [];
$leafs = [];
foreach ($xpath->evaluate('//*|//#*') as $node) {
$isLeaf = !($xpath->evaluate('count(#*|*) > 0', $node));
$path = '';
foreach ($xpath->evaluate('ancestor::*', $node) as $parent) {
$path .= '/'.$parent->nodeName;
}
$path .= '/'.($node instanceOf DOMAttr ? '#' : '').$node->nodeName;
if ($isLeaf) {
$leafs[$path] = TRUE;
} else {
$paths[$path] = TRUE;
}
}
$paths = array_keys($paths);
$leafs = array_keys($leafs);
echo "Choose a path<br><br>
<form>
<select id='field_dropdown'>";
foreach($paths as $value) {
echo "<option value='".$value."'>".$value."</option>";
}
echo " </select>
<button id='send_path'>Send path</button>
</form>
";
}
?>
<script>
$(document).ready(function() {
$('#send_path').click(function() {
var _path = $("#field_dropdown").val();
// Get the leafs array and send it as a json string to set_fields.php
var _leafs = <?php echo json_encode($leafs); ?>;
$.get('set_fields.php?pt=' + _path + '&lf=' + _leafs, function(data) {
$('#fields').append(data);
}).error(function() {
$('#fields').html('Error calling XML script. Please make sure there is no error in the XML file.');
});
return false;
});
});
</script>
And here the code where I want the json array to end up (and then get turned back into a PHP array).
<?php
// Match all the fields to the values
$path = $_GET['pt'];
$leafs = json_decode($_GET['lf']);
$fieldLeafs = [];
$pathLength = strlen($path) + 1;
foreach ($leafs as $leaf) { if (0 === strpos($leaf, $path.'/')) { $fieldLeafs[] = substr($leaf, $pathLength); } }
var_dump($path."<br>");
var_dump($leafs."<br>");
?>
What if you get the array through jquery instead of echoing it?
<input id="hidden-value" value="<?php echo json_encode($leafs); ?>" />
and then
var _leafs = $('#hidden-value').val();
What about adding an = after the lf query parameter when you build the get URI?
$.get('set_fields.php?pt=' + _path + '&lf=' + _leafs, ...
Just write 'json' in the last parameter of get method:
$.get('set_fields.php?pt=' + _path + '&lf' + _leafs, function(data) {
$('#fields').append(data);
},'json')//<-- this
.error(function() {
$('#fields').html('Error calling XML script. Please make sure there is no error in the XML file.');
});
Did you try this?
var _leafs = [<?php foreach($leafs as $leaf){ echo "'$leaf',"; } ?>]

Javascript read a php file, not run it

I'm making a dynamic csv to array formatter, and part of it displays the formatted array, and the other part is suppose to display the code for it. I can't get it to display the code without it just showing the array again, what do I do?
-Javascript
$.post('csv.php', {names : names, fp : fp}, function(data){
$('#arrayDisp > center > textarea').html(data);
$.ajax({
url: "csv.php",
context: document.body,
success: function(){
$('#codeDisp > center > textarea').html(data);
}
});
});
-Php
$file = file(_FILE_PATH, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$data = array();
$line_number = 0;
foreach($file as $f) {
$line = explode(',', $f);
$i = 0;
foreach($line as $l) {
$data[$line_number][$names[$i]] = $l;
$i++;
}
$line_number++;
}
json_encode($data);
print_r($data);
?>
You can try
foreach($data as $key => $value)
{
echo $key." has the value". $value;
}
This might work for you
I'd modify the script to accept a GET param. so it reads like this
if($_GET['showSource'])
highlight_file ($_SERVER['PHP_SELF']);
else
//do stuff
So your JS call would actually be two calls, first you call the script without the ?showSource=1 so you will get the parsed csv thingy, then you do the call with the ?showSource=1 and get the source displayed.
Thanks to Emissary's helpful hint I found the answer to my problem -
I added a request variable to my post requests and renamed them when each was over -
var request = 'array';
$.post('csv.php', {names : names, fp : fp, request : request}, function(data){
$('#arrayDisp > center > textarea').html(data);
request = 'code';
$.post('csv.php', {names : names, fp : fp, request : request}, function(data){
$('#codeDisp > center > textarea').html(data);
});
});
Then in my php code I did this -
if ($_POST['request'] === "array") {
json_encode($data);
print_r($data);
}
else if ($_POST['request'] === "code") {
echo file_get_contents('csv.php');
}

Categories

Resources