I have a curl statement that pulls json formatted array to php. I then want to transfer this array to jQuery so that the client side will hold the array. I'm currently using the below method:
<script>var obj = jQuery.parseJSON( <?php echo var_dump($json_short); ?> );</script>
The client sees something like:
<script>var obj = jQuery.parseJSON( array(1) {
["search"]=>
array(50) {
[0]=>
array(6) {
["id"]=>
string(6) "641279"
["description"]=>
string(36) "Instyle - Responsive Portfolio Theme"
["url"]=>
string(69) "http://themeforest.net/item/instyle-responsive-portfolio-theme/641279"
["type"]=>
string(9) "wordpress"
["sales"]=>
string(3) "135"
["rating"]=>
string(3) "4.5"
}
....
}
}
);</script>
Will obj now hold the array? is this the right way becuase I'm getting an error:
Uncaught SyntaxError: Unexpected token {
PHP has json_encode function already, you should use that.
Would look like:
<script>
var a = <?php echo json_encode($json_short); ?>;
</script>
You cannot use a direct dump, you need to json_encode first:
<script>var obj = <?php echo json_encode($json_short) ?>;</script>
I don't understand what you're trying with <script>var obj = jQuery.parseJSON( <?php echo var_dump($json_short); ?> );</script>
in PHP try echo json_encode($json_short);
the var_dump function doesn't dump it as a json object.
use json_encode instead of var_dump.
Don't use var_dump first off. Next make sure you have converted your variable to a json array you have a normal array.
<script>var obj = jQuery.parseJSON( <?php echo json_encode($json_short); ?> );</script>
Related
i am working on online exam test where childArray[] contains data from each row of table and parrentArray[] contains number of childArray[]. i want to get value of each childArray from ParentArray with Index passed through ajax.
<?php
$childArray1[]=[1,question,optionA,optionB,optionC];
$childArray2[]=[1,question,optionA,optionB,optionC];
$parentArray[]=[$childArray1,$childArray2];
?>
<script>
$(document).ready(function(){
var counter=0;
$("#ButtonNext").click(function(){
$.ajax({
type:"POST",
url: "ChangeQuestionProcess.php",
data:{
MainList:"<?php echo json_encode($parentArray); ?>",
Counter:counter,
},
success: function(result){
$("#callMe").html(result);
}});
counter++;
});
});
</script>
ChangeQuestionProcess.php
<?php
$index=$_POST["Counter"];
$test[]=$_POST["MainList"];
echo test[$index];
?>
In your ChangeQuestionProcess.php, this line:
$test[]=$_POST["MainList"];
...is saying "take the contents of $_POST["MainList"] and make it the next element of the array $test"
You're doing a similar thing at the top of your first script - I think you mean this, without the [] after the variable names:
<?php
$childArray1=[1,'Question 1','Option 1A','option 1B','option 1C'];
$childArray2=[2,'Question 2','Option 2A','option 2B','option 2C'];
$parentArray=[$childArray1,$childArray2];
?>
You could even simplify this to:
<?php
$parentArray = [
[1,'Question 1','Option 1A','option 1B','option 1C'],
[2,'Question 2','Option 2A','option 2B','option 2C']
];
?>
Now back to ChangeQuestionProcess.php again - bear in mind that $_POST["MainList"] is going to be a string containing JSON-encoded data (as that's what json_encode() returns)
Therefore what I think you are trying to do is read the array of JSON-decoded data into $test, which you would do like so:
$test = json_decode( $_POST["MainList"] );
Finally, you're missing a $ when echoing your variable. But as $test[$index] is an array, you'll just see Array on your screen instead of its contents. I think you need something like print_r instead of echo:
<?php
$index = $_POST["Counter"];
$test = json_decode( $_POST["MainList"] );
print_r( $test[$index] );
?>
I have the following issue, my php code gets the required data from the dB:
<?php
require('dB_connect.php');
$reportID = intval($_GET['q']);
$sql = "SELECT nmech, nelect, nplant, ncivil FROM `flashreport` WHERE ID = '".$reportID."'";
$result = mysqli_query($dbc, $sql);
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
file_put_contents("newport.json", json_encode($emparray,JSON_FORCE_OBJECT));
mysqli_close($dbc);
?>
As you see this writes to a json file - results:
{"0":{"nmech":"2.00","nelect":"2.00","nplant":"2.00","ncivil":"2.00"}}
When I use the following js code to extract from json file:
$.getJSON('newport.json', function(data) {
console.log(data);
The console log using chrome displays the following:
[Object]
0: Object
nmech: "3.00"
__proto__: Object
length: 1
only shows the first key/value pair and not all 4 K/V pair? Can someone explain what I am doing wrong please.
Writing the results to a json file is overkill, IMHO. Why not just add the json into a Template or Page view (PHP).
<script>
// Create settings from PHP/Session and
// Initialize Registration Namespace
var registrationSettings = <?php echo (!empty($data)) ? #json_encode($data) : json_encode(array()); ?>;
Registration.init({ settings: window.registrationSettings });
</script>
Obviously, you don't have a Registration namespace object, but this just an example approach to setting settings from PHP when the page first loads.
All you really need it to output some data.
<script>
var newport = <?php echo (!empty($emparray)) ? #json_encode($emparray) : json_encode(array()); ?>;
</script>
Or maybe a more simple way to write it would be.
<script>
var newport = <?php echo (!empty($emparray)) ? #json_encode($emparray) : '[]'; ?>;
</script>
I can see your trying to file (or cache) the results. You should probably just write an AJAX method in your PHP controller to handle the request. The data could be cached server side in Memcached or some other fast handler of data. Most PHP frameworks support memcached.
This is ok, because your PHP array looks like this:
<?php
$arr = [
[
"key1" => "value1",
"key2" => "value2",
]
]
You must use data[0]['key'] to access key1 part of first element.
Another (better solution) is to not to use while loop in php, since you are expecting 1 element in your case to be returned from mysql. Use like this then:
<?php
require('dB_connect.php');
$reportID = intval($_GET['q']);
$sql = "SELECT nmech, nelect, nplant, ncivil FROM `flashreport` WHERE ID = '".$reportID."'";
$result = mysqli_query($dbc, $sql);
//Get first row from db.
$emparray = mysqli_fetch_assoc($result);
file_put_contents("newport.json", json_encode($emparray,JSON_FORCE_OBJECT));
mysqli_close($dbc);
?>
Now your data will be in javascript like you expected on beginning.
I have a php file where I am outputing json.
<?php
header('Content-Type: application/json');
?>
var data = {
"cars": [
<?php foreach ($runshowcars as $rowscar):;?>
{
"id":"<?php echo $rowscar['id'] ?>",
"name":"<?php echo $rowscar['name'] ?>"
}
],
"boats": [
<?php foreach ($runshowboats as $rowsboat):;?>
{
"id":"<?php echo $rowsboat['id'] ?>",
"name":"<?php echo $rowsboat['name'] ?>"
}
],
};
This works however the output looks like this.
var data = {
"cars": [
{
"id":"1",
"name":"Ford"
}
,{
"id":"2",
"name":"Honda"
}
]
};
I want it to look like this.
var data = {"cars": [{"id":"1","name":"Ford"},{"id":"2","name":"Honda"}]};
The only way I have found to do this is to remove the white spaces from my php file, this is obviously not an ideal solution as it makes it very hard to maintain.
How can strip out all the white spaces here?
I have seen plenty of questions like this one, How to minify php page html output? however I can't get something like this working here as my data isn't in a variable?
Why don't you collect your data into an array and encode it to json.
Like this:
$data=array('cars'=>$runshowcars, 'boats'=>$runshowboats);
print json_encode($data);
(Otherwise you return javascript, and not json. At least if you prepend the result with the var data = part.)
Just create a multi dimensional associative array and use json_encode
You can remove everything outside <?php ?> like this :
<?php
header('...') ;
echo 'var data = {' ;
echo '"cars": [' ;
foreach ($runshowcars as $rowscar)
{
echo '{' ;
echo '"id":"'.$rowscar['id']?'",' ;
echo '"name":"'.$rowscar['name'] ;
echo '}' ;
}
echo '],' ;
...
?>
Or you can try json_encode php function (wich could be a better way imo) :
<?php
$data = Array('cars'=>$runshowcars,'boats'=>$runshowboats) ;
echo 'var data = '.json_encode($data) ;
?>
i have a json object.
$json = json_decode($data,true);
it looks like-
array(5) {
["screenShareCode"]=>
string(9) "021113322"
["appletHtml"]=>
string(668) ""
["presenterParams"]=>
string(396) "aUsEN5gBYi4vlIEGpk0="
["viewerUrl"]=>
string(65) "http://api.leap.com/v2/viewer/021113322?accountid=mynet"
["origin"]=>
string(3) "API"
}
alert('?php echo $json; ?>');
when i am trying to assign this into javascript variable it gives me an error saying "unterminated string constant".
You don't decode it, in PHP or JavaScript. The contents of a JSON string is a valid JavaScript literal.
<?php
...
?>
<script ...>
var data=<?php echo $data; ?>;
alert(data["screenShareCode"]);
<?php
...
Try:
alert(<?php echo json_encode($json); ?>);
or:
alert(<?php echo $data; ?>);
You're a bit confused about terminology. $data is a JSON string, $json is a PHP array that you got by decoding the JSON string.
Try the following code. I have created a php file named sample.php. We have a php array named $data. Encode that data in to json using json_endode(). That results json formatted data. Then we can assign it into a java script variable like var jsonData = <?php echo $jsonData ?>; Note that this is done inside <script> tag.
<?php
// We have some data
$data = array(
"screenShareCode"=>"021113322",
"appletHtml"=>"",
"presenterParams"=>"aUsEN5gBYi4vlIEGpk0",
"viewerUrl"=>"http://api.screenleap.com/v2/viewer/021113322?accountid=mynet",
"origin"=>"API"
);
// Convert it into json format.
$jsonData = json_encode($data,true);
?>
<script>
// Assign that json data to a java-script variable
var jsonData = <?php echo $jsonData ?>;
// To view the full data
console.log(jsonData);
// You can take a specific data like this.
alert(jsonData.presenterParams);
</script>
I am trying to implement Typeahead.js to my site.
The typeahead.js will take from a remote page that would return JSON,
something like: http://example.org/search?q=%QUERY
For my site, this is what I've wrote for the PHP:
$q=mysql_real_escape_string($_GET['q']);
$getship= #mysql_query('SELECT * FROM `tbl` WHERE data1 LIKE \'%'.$q.'%\' OR schar LIKE \'%'.$q.'%\';');
while($tbl=mysql_fetch_array($getship)){
$id=$tbl['id'];
$data1=$tbl['data1'];
$fplod=explode(" ",$data1);
$data2=$tbl['data2'];
$splod=explode(" ",$data2);
$data3=$tbl['data3'];
$data4=$tbl['data4'];
echo '{
"value":'.$id.',
"tokens":["'.$fplod[0].'","'.$fplod[1].'","'.$splod[0].'","'.$splod[1].'"],
"data1" :"'.$data1.'",
"data2":"'.$data2.'",
"data3":"'.$data3.'",
"data4":"'.$data4.'"
}';
}
But when ever I ask that typeahead thing to return, it seems to return in text/html and not application/json .
How can I make this to work?
Thanks in advance
You can set the Content-Type header yourself. Before any output is sent, call header:
header('Content-Type: application/json');
That is not valid JSON. You do not have quotes around the names. PHP has built in json encoding/decoding functions already so you don't have to build the string yourself.
echo json_encode(array("value" => $id /* etc
It is not a good practice to convert your data into json manually, rather use json_encode
$data = array();
while($tbl=mysql_fetch_array($getship)){
$data[] = $tbl;
}
$return = array("data"=>$data);
echo json_encode($return);
try something like:
while($row = mysql_fetch_array($getship, MYSQL_ASSOC))
{
$row_set[] = $row;
}
echo json_encode($row_set);
you can also use mysql_fetch_assoc.