Get data array from PHP to JavaScript - php

I want to get data array from php to Javascript. (Actually I am doing plotting using javascript library and the data is in the database: I get the data using php script and want to use that data for plotting). I have tried to use a JSON for this. My code looks follows but it is not working. Please give me a help on this
<script type="text/javascript">
<?php
$php_arr=array('abc','def'); // I want to transport this array to javascript
echo "display_diagram(" . json_encode($php_arr) . ")";
?>
function display_diagram(data) {
obj = JSON.parse(data); // this is not working for me

Try use data variable in display_diagram function without JSON.parse.
You now give data attribute in json format and this not require additional json parsing.
Check this:
<script>
<?php
$php_arr=array('abc','def'); // I want to transport this array to javascript
echo "display_diagram(" . json_encode($php_arr) . ")";
?>
function display_diagram(data){
obj = data;
alert(obj);
}
</script>

Related

Pass array into GET URL using jQuery

I am trying to pass an array into a GET URL BUT it is coming as add_cart?ids=1,2,3,4,5 as opposed to sending it properly.
This is my jquery code where it adds the array to the URL and directs the user to the next page:
$(document).on("click", 'button.btn_checkout', function(){
var cart = <?php echo json_encode($carts); ?>;
window.location.href = "addcart.php?cart=" + cart;
});
And then on the addcart.php page I am unable to get these values.
Ideally on this page, I want the values in the form 1,2,3,4,5
This is the code for that page:
<?php
session_start();
$cart = isset($_GET['cart']) ? $_GET['cart'] : "";
$cart = explode(",", $_GET['cart']);
for($i = 0; $i<$cart.size; $i++){
echo $cart[$i];
}
?>
Where am I going wrong?
You are using the jQuery GET request a little wrongly. You will use
window.location.href
when you are trying to change the location of your current webpage.
Try this instead:
$(document).on("click", 'button.btn_checkout', function(){
var result = <?php echo json_encode($carts); ?>;
$.get( "addcart.php", { cart: result } );
});
I'm assuming by ARRAY you mean to include the braces {}?
If so, your problem is actually the php part. json_encode is creating a proper json object. Which then is being added onto the url AS the object itself, and NOT a string. You actually want it to be a string.
this line: var cart = <?php echo json_encode($carts); ?>; is the main issue.
convert it to something like: var cart = "<?php echo json_encode($carts); ?>";
Use $.param() function to convert params to get query string.
You are directly initialising Json to param but not converting to query string.
Above function will convert Json to query string
Try to use the javascript function JSON.stringify() to convert to json.
Note: Don't sent long data over a URL. There is a limit for sending data via url and it will end up in a corrupted data if exceeded the limit. For large data, use POST method.

Decode json and display in table

I have a HotUKDeals API which when using the URL bellow gives me some JSON.
Im trying to use PHP to display it in a table but if i try and use a loop to go through the JSON i get errors.
If i try and decode i get "Object of class stdClass could not be converted to string"
So far I have this which i no gets the json and stores it in the variable .
I also have some JS which will go through JSON and put it in a table , but im having difficulties getting the JSON in the php variable into the JS.
Needed to remove code for work reasons !
To get the JSON into your jQuery code you'll have to use AJAX:
PHP file -
<?php
$tester = file_get_contents('http://api.hotukdeals.com/rest_api/v2/?key=d2c088ea340558b3b3517396963a341c&results_per_page=2&output=json');
echo $tester;
?>
jQuery AJAX -
$.get( "hotukdeals.php", function( data ) {
// now you can work with `data`
var JSON = jQuery.parseJSON( data ); // it will be an object
$.each(JSON.deals.items, function( index, value ) {
console.log( value.title + ' ' + value.description );
});
});
NOTE: The JSON that is returned has complex construction, so you will have to take care about how you extract during the loop and then place in the table.

How to use outputs of php that is called by ajax in our file

I have an app that sends latitude, longitude values to my postgresql database. And i want to plot the updated points accordingly on my OpenLayers map using jquery,ajax. But here is where i am stuck at: When I click the button, the php file with database connection and saving the last entry of the table in an array is happening.
But when i try using the outputs in markers, nothing is happening.
How to use the output values of the php in my function?
Here is the code that i am trying to use.
php file:
<?php
$conn = pg_connect("host=xxx port=xxx dbname=xx user=postgres password=xxx");
$result = pg_exec($conn,"Query goes here");
$numrows = pg_numrows($result);
for($ri = 0; $ri < $numrows; $ri++)
{
$row = pg_fetch_array($result, $ri);
$data = array(); // create a variable to hold the information
$lat_latest[] = $row["latitude"];
$long_latest[] = $row["longitude"]; // add the row in to the results (data) array
}
pg_close($conn);
$js_lat = json_encode($lat_latest);
echo "var javascript_lat1 = ". $js_lat . ";\n";
$js_long = json_encode($long_latest);
echo "var javascript_long1 = ". $js_long . ";\n";
?>
My page code is :
function init(){
//openlayers map code is here.
$("button").click(function(){
$.get("dataconn.php",function(data,status){
alert("Data:"+data+"Status:" +status);
var extra_point = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(parseFloat(javascript_long1[0]),parseFloat(javascript_lat1[0])),
{some:'data'},
{externalGraphic: 'images1/marker-gold.png', graphicHeight: 16, graphicWidth: 16});
vectorLayer1.addFeatures([extra_point]);
});
});
}
</script>
</head>
<body onload='init();'>
<div id="map" style = 'width: 1075px; height: 485px'>
<button> Update </button>
</div>
and the alert i am getting when clicking update button is
Data:
var javascript_lat1 = ["output of the query"];
var javascript_long1 = ["output of the query"];
Status : success
Is the way i am trying to access the values of query output correct? Please help.
Sorry if this is a dumb question. I am new to jquery.
When your php script sends a string like:
'var javascript_lat1 = ["output of the query"];'
back to your code, that does not mean that your code has a variable called javascript_lat1 in it.
Your php script is sending strings back to your javascript code from which you must extract the information that you want to use in your code. It is up to your javascript code to know what format the strings are in. But since you wrote the php script you can send the strings back in any format you want. Then your javascript code can dissect the strings with regexes, split(), etc. to extract the parts of the strings that you want to use in your code. A very simple format that your php code could use is:
"output of query 1, output of query 2"
Then you can split() on the comma to separate the two pieces of data e.g.:
var pieces = data.split(', ');
Then you can use pieces[0] and pieces[1] in your javascript code.
Another option is to send a request to your php script using the $.getJSON() function. If you do that, your php script should send back a json formatted string, e.g.:
"{lat1: 'blah blah blah', long1: 'foo bar foo bar'}"
Then the $.getJSON() function will automatically convert the string into a javascript object and pass the js object to your callback function. Inside the callback function you can access the data using:
some_func(data.lat1, data.long1);

how to store php object to access its data on click with javascript

I'm trying to figure out the least obtrusive and least computationally expensive way to store PHP objects coming from my MySQL database such that their data can be rendered by JavaScript on click by a user.
Currently, I'm storing the data as custom attributes on a button. But this generates a lot of code and I've heard is "slow". I'm wondering if I should JSON encode my PHP object, $items (see below), and how that JavaScript would then look. Note I'm using Codeigniter for the PHP so that's what up with the alternate foreach loop syntax.
Here's where I'm at so far with the HTML/PHP:
<img id="img"></img><a id="url"></a> <!--elements where data is rendered on click-->
<? foreach($items as $item):?>
<button data-id="<?=$item->id?>" data-url="<?=$item->url?>" data-img="<?=$item->img?>">click<?=$item->id?></button>
<?endforeach;?>
And here's my JS:
$(document.body).on('click', 'button', function(){
var $this=$(this), id=$this.data('id'), url=$this.data('url'), img=$this.data('img');
$('#img').attr('src', img);
$('#url').attr('href', url).html(url);
});
Most of my site's data is coming from PHP via MySQL and I've long been confused by the issue of when should I convert that data to a JavaScript array/JSON or not.
If you json_encode your $items array (assuming it only consists of data you will want in JS), you can assign this to a JS variable:
<script>var items = <?php echo json_encode($items); ?></script>
You can then remove the data-url and data-img attributes. Then, within your JS code:
var $this = $(this), id = $this.data('id'), url = items[id].url, img = items[id].img;
// the rest of your code
Edit: when you move the click handler in a separate file, you would get something like this:
function setup_click(items) {
var $img = $('#img'), $url = $('#url');
$('button').click(function(evt) {
var id = $(this).data('id'),
url = String(items[id].url),
img=String(items[id].img);
$url.attr('href', url).html(url);
$img.attr('src', img);
});
}
here's a JSfiddle showing off the javascript/JSON part: http://jsfiddle.net/fz5ZT/55/
To call this in one shot from your template:
<script src="[your ext script file path].js"></script>
<script>setup_click(<?php echo json_encode($items); ?>);</script>
Hope that helps :)

Pass a JSON array from PHP to Dynatree

I'm using Dynatree for the first time and wrote a PHP script that returns a properly formatted JSON array.
I've read the Dynatree documentation, but can't figure out how to pass in the JSON array from my PHP script so its contents can be loaded as the tree structure.
At the top of my HTML file, I'm using <?php include('tree.php') ?> which automatically returns the formatted JSON array (named $categories). I'd also be fine with calling a function from JavaScript to retrieve the tree if that makes it easier.
Can someone show me how to deliver my array to Dynatree?
You can use a data- attribute, like this:
<?php
$dynaConfig = array('children'=>array(
array('title' => 'Alice'),
array('title' => 'Bob')
));
$dynaConfigJSON = json_encode($dynaConfig);
// HTML head goes here
echo '<div id="tree" data-dyna="' . htmlspecialchars($dynaConfigJSON) . '">';
?>
<script>
$(function() {
var dtConfig = $.parseJSON($('#tree').attr('data-dyna'));
$('#tree').dynatree(dtConfig);
});
Here's a live example, and the corresponding full source code.
You can also separate the code of php in a file like tree.php and then call it in javascript.
<div id="tree"> </div>
<script type="text/javascript">
$(function(){
$("#tree").dynatree({
initAjax: {
url: "tree.php"
}
}
}
</script>

Categories