Valid JSON not working with jQuery.parseJSON() - php

I'm saving a JSON string to a file and trying to read it back. For some reason it won't read it back. jsonlint.com is telling me it is a valid JSON.
Here is the JSON string:
{"userdef":{"vlan10":{"dfault":{"down":{"rate":"876","ceil":"876"},"up":{"rate":"876","ceil":"876"}},"upsell":{"down":{"rate":"876","ceil":"876"},"up":{"rate":"876","ceil":"76"}}},"br0":{"dfault":{"down":{"rate":"798","ceil":"987"},"up":{"rate":"987","ceil":"987"}},"upsell":{"down":{"rate":"98","ceil":"987"},"up":{"rate":"987","ceil":"89"}}},"br1":{"dfault":{"down":{"rate":"3","ceil":"654"},"up":{"rate":"654","ceil":"63"}},"upsell":{"down":{"rate":"65","ceil":"4"},"up":{"rate":"646","ceil":"5"}}},"eth3":{"dfault":{"down":{"rate":"65","ceil":"7876"},"up":{"rate":"7657","ceil":"5"}},"upsell":{"down":{"rate":"7865","ceil":"7"},"up":{"rate":"7","ceil":"5"}}}}}
Here is javascript/php code:
<?
if (file_exists('/tmp/qosconfig.conf'))
{
?>
var config = jQuery.parseJSON('<?=file_get_contents("/tmp/qosconfig.conf");?>');
<?
}
?>

This is a rather odd way of doing this. If you have the JSON string available to you in PHP, you can output it into the javascript as an object literal which saves the parsing step.
<?
if (file_exists('/tmp/qosconfig.conf')) {
$json = file_get_contents('/tmp/qosconfig.conf');
?>
var config = <?php echo $json; ?>;
<?
}
?>

Related

Pulling nested variable from json API

I'm trying to pull the highlighted variable from this API:
{
"timestamp":{
"total":1486424886,
"exchanges":{
"NEG":1486423855,
"MBT":1486424738,
"LOC":1486422237,
"FOX":1486424483,
"FLW":1486411044,
"B2U":1486424811,
"ARN":1486405596
}
},
"ticker_24h":{
"total":{
"last":**3011.8756088755**, // <---
"high":4073.32,
"low":2631.58,
...
http://api.bitvalor.com/v1/ticker.json
This is my code so far:
<html>
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<table width="auto">
<tr><td>BTC/BRL (Bitvalor)</tr></td>
<tr><td>
<?php
$url1 = "http://api.bitvalor.com/v1/order_book_stats.json";
$fgc1 = file_get_contents($url1);
$json1 = json_decode($fgc1, true);
$price1 = $json1["ticker_24h.total.last"];
echo $price1;
?>
</tr></td>
</table>
</html>
What am I missing?
You access decoded JSON like an associative array:
$price1 = $json1['ticker_24h']['total']['last'];
Make sure you use an isset in case the format of data changes or the response is not what you expect.

Using json_encode to send html returns “null” string at the end

I'm using this to load php functions and send them to javascript in a plugin, like:
function me_nav_query_submit() {
$urlcall = nav_me_paises(); /* fetches a large html string */
$response = json_encode($urlcall); /* encode to display using jQuery */
//header( "Content-Type: application/json" );
echo $response;
exit;
}
I insert the html on the page, using
function(response) {
jQuery('#navcontainer').html(response);
}
and everything works fine, except that i get a "null" string at the very end of the result.
json_encode() documentation talks about null strings on non-utf-8 chars, but this doesn't seem to be the case. I've also tried using utf8_encode() with no success. I've read a bunch of other questions here on SO, but most of them either talk about one given value returned as null or bad UTF-8 encoding and in my case everthing just works, and then append "null" to the end.
note: Defining that header() call is recommended in the WP Codex, but i commented it because it was giving a "headers already sent" error.
Any ideas?
EDIT this is the function called:
function nav_me_paises() {
?>
<ul class="navcategorias">
<?php $tquery = $_POST['wasClicked']; ?>
<?php $navligas = get_terms($tquery,'hide_empty=0') ?>
<?php foreach ($navligas as $liga) : ?>
<?php $link = get_term_link($liga); ?>
<li class="liga"><a href="<?php echo $link; ?>" ><?php echo $liga->name; ?></a></li>
<?php endforeach; ?>
</ul>
<?php
}
nav_me_paises() is not returning anything. the html block is treated as output!
function nav_me_paises() {
$output = '<ul class="navcategorias">';
$tquery = $_POST['wasClicked'];
$navligas = get_terms($tquery,'hide_empty=0')
foreach ($navligas as $liga) {
$link = get_term_link($liga);
$output .= '<li class="liga"><a href="'.$link.'" >'.$liga->name.'</a></li>';
}
$output .='</ul>';
return $output;
}
nav_me_paises() doesn't return anything. Passing this "nothing" to json_encode() gives "null". Convert the function so that it returns the HTML instead of outputting it
function foo()
{
};
var_dump(json_encode(foo()));
string(4) "null"
Also, if it's just plain HTML, why json it? Just send it to JS, it will be a string stored in a variable, and you handle it normally.
I presume all you wanna do is put that HTML inside some div, because you'd not parse it into a DOM and process its elements... because if u'd do that u'd not use HTML for it.

jquery $.parseXML cannot parse XML from php strings?

Somehow I keep getting error in javascript when I try to parse xml from php string, my code is like:
<?php
$xml = simplexml_load_file('file.xml');
$products = $xml->xpath("/products/product[#model='".$model . "']");
$filtered_xml = $products[0]->asXML();
?>
<script>
alert( $.parseXML( '<?php echo $filtered_xml;?>' ).find('name').text() );
</script>
echo $filtered_xml is returning a well formed xml as I am looking for, but something in the javascript - $.parseXML( '<?php echo $filtered_xml;?>' ) is causing errors. Thanks in advance for any help.
$.parseXML() itself does not return a jQuery object. Look at example in docs
http://api.jquery.com/jQuery.parseXML/
Proper use in your case would look more like:
var xml= $.parseXML( '<?php echo $filtered_xml;?>') ;
alert( $(xml).find('name').text() )

JavaScript & JSON

I am new to JS & JSON.I am struggle with converting JSON array to JavaScript array.How to do that? Here is my code:
var data = {
items: [
<? $i=1; foreach($query->result() as $row){ ?>
<? if($i!=1){ ?>,<? } ?>
{label: '<?=$row->district_name;?>', data: <?=$row->countid;?>}
<? $i++; } ?>
]
};
how to get the JSON array value to JavaScript Array.
i just tried but it doesn't work. please some suggestions.
here is my javascript array
for(i=0;i<5;i++){
chartData[i]=data.items[i].label+";"+data.items[i].data;
}
As the others already said, be careful when talking about JavaScript and JSON. You actually want to create a JavaScript object and not JSON.
Don't mix PHP and JavaScript like this. It is horrible to maintain. Create an array beforehand, encode it as JSON* and print it:
<?php
$results = $query->result(); // get results
function m($v) { // a helper function for `array_map`
return array('label' => $v->district_name,
'data' => $v->countid);
}
$data = array('items' => array_map('m', $results));
?>
var data = <?php echo json_encode($data); ?>
*: Here we use the fact that a JSON string is valid JavaScript too. You can just echo it directly in the JavaScript source code. When the JS code runs, it is not JSON, it is interpreted as JavaScript object.
You really oughtn't think too hard about this. PHP does a fine job of serializing arrays as JSON.
var data = {
items: <?php
$arr = array();
foreach($query->result() as $row) {
$arr[] = array('label' => $row->district_name,
'data' => $row->countid);
}
echo json_encode($arr);
?>
};
[insert same disclaimer as above about how you're really trying to create a JavaScript object]
This is JSON:
var foo = "{bar: 1}";
This is not JSON:
var foo = {bar: 1};
Your code snippet is not using JSON at all and my educated guess is that you don't even need it. If you are using PHP to generate some JavaScript code, you can simply tweak your PHP code to print text that will contain real JavaScript variables. There is no need to encode stuff as plain text!
Now it's clear we don't need JSON, let's use a dirty trick. PHP has json_encode() and we can abuse the fact that a JSON strings resemble JavaScript variables. All we have to do is call json_encode() on our PHP variable and forget to quote the result:
<?php
$foo = array(
'bar' => 1,
'dot' => FALSE,
);
echo 'var JSONString = "' . json_encode($foo) . '";' . PHP_EOL;
echo 'var realVariable = ' . json_encode($foo) . ';' . PHP_EOL;
Compare:
var JSONString = "{"bar":1,"dot":false}";
var realVariable = {"bar":1,"dot":false};
Edit: Yep, my JSONString is not a valid string... but we get the idea <:-)

Returning JSON from PHP to JavaScript?

I have a PHP script that's being called through jQuery AJAX. I want the PHP script to return the data in JSON format to the javascript. Here's the pseudo code in the PHP script:
$json = "{";
foreach($result as $addr)
{
foreach($addr as $line)
{
$json .= $line . "\n";
}
$json .= "\n\n";
}
$json .= "}";
Basically, I need the results of the two for loops to be inserted in $json.
Php has an inbuilt JSON Serialising function.
json_encode
json_encode
Please use that if you can and don't suffer Not Invented Here syndrome.
Here are a couple of things missing in the previous answers:
Set header in your PHP:
header('Content-type: application/json');
echo json_encode($array);
json_encode() can return a JavaScript array instead of JavaScript object, see:
Returning JSON from a PHP Script
This could be important to know in some cases as arrays and objects are not the same.
There's a JSON section in the PHP's documentation. You'll need PHP 5.2.0 though.
As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.
If you don't, here's the PECL library you can install.
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
?>
Usually you would be interested in also having some structure to your data in the receiving end:
json_encode($result)
This will preserve the array keys as well.
Do remember that json_encode only works on utf8 -encoded data.
You can use Simple JSON for PHP. It sends the headers help you to forge the JSON.
It looks like :
<?php
// Include the json class
include('includes/json.php');
// Then create the PHP-Json Object to suits your needs
// Set a variable ; var name = {}
$Json = new json('var', 'name');
// Fire a callback ; callback({});
$Json = new json('callback', 'name');
// Just send a raw JSON ; {}
$Json = new json();
// Build data
$object = new stdClass();
$object->test = 'OK';
$arraytest = array('1','2','3');
$jsonOnly = '{"Hello" : "darling"}';
// Add some content
$Json->add('width', '565px');
$Json->add('You are logged IN');
$Json->add('An_Object', $object);
$Json->add("An_Array",$arraytest);
$Json->add("A_Json",$jsonOnly);
// Finally, send the JSON.
$Json->send();
?>
$msg="You Enter Wrong Username OR Password";
$responso=json_encode($msg);
echo "{\"status\" : \"400\", \"responce\" : \"603\", \"message\" : \"You Enter Wrong Username OR Password\", \"feed\":".str_replace("<p>","",$responso). "}";

Categories