passing php object via javascript in magento - php

Here is what I'm trying to do:
In "app/design/frontend/default/default/template/catalogsearch/advanced/form.phtml"
I have the following php statement
<?php $x=$this->getStoreCategories(); ?>
If I am not wrong $x would be an object and when i display it in php I am able to view it.
I need to convert this object into a javascript object (JSON) as i need to pass it using jQuery Ajax
But when I execute
<script>
var obj = JSON.parse('<?php echo json_encode($x) ?>');
alert(obj.toSource());
</script>
The alert gives me an empty object
Can anyone please help me out
Thanks in advance

You could do;
<script>
var obj = <?php echo json_encode($x) ?>;
</script>
When the page outputs, your JSON object will be in the page. Or am I missing something about what you want to do?

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.

Get data array from PHP to JavaScript

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>

Unable to parse a string into JSON object, unable to display an alert box from javascript

EDIT: SOLVED. Use any of the solutions below, but document.onload needs to be changed to window.onload. Also works without needing window.onload function anyway.
Here is the test.php file that i'm working with
<?php
include("conn.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<script src="js/jquery.js"></script>
<script type="text/javascript">
document.onload = function (){
var jsonString = '<?php echo json_encode($rowarr); ?>';
var jsonObj = jQuery.parseJSON( jsonString );
console.log(jsonObj);
alert( jsonObj.Auckland );
};
</script>
</body>
</html>
I have verified in Chrome Developer tools the value of jsonString to be
'{"Auckland":37616,"Wellington":35357,"Christchurch":29818}'
After that I don't get any log on the console or any alert box. I have also tried JSON.parse method instead of jQuery.parseJSON to no avail.
I'm trying to get this JSON into a datatable format used for google charts geo chart which looks like this bit of code
var data = google.visualization.arrayToDataTable([
['City', 'Population', 'Area'],
['Rome', 2761477, 1285.31],
['Milan', 1324110, 181.76],
['Naples', 959574, 117.27],
['Turin', 907563, 130.17],
['Palermo', 655875, 158.9],
['Genoa', 607906, 243.60],
['Bologna', 380181, 140.7],
['Florence', 371282, 102.41],
['Fiumicino', 67370, 213.44],
['Anzio', 52192, 43.43],
['Ciampino', 38262, 11]
]);
If you don't put it as a string it would be an object and you would not have to parse it
var jsonObj = <?php echo json_encode($rowarr); ?>;
instead of
var jsonString = '<?php echo json_encode($rowarr); ?>';
var jsonObj = jQuery.parseJSON( jsonString );
It looks like document.onload doesn't fire/already fired? you should use window.onload or $(document).ready() instead.
Since you are actually inserting the JSON with a php echo right inside the script tag in the actual html page, it technically becomes an object literal. There is no need to go through the extra parsing step in JavaScript.
So in your case, the value you assign to jsonString is actually already an object.
You need to parse JSON only if it really is in the form of a string. So the actual script part sent to the browser should look like this:
var cities = {"Auckland":37616,"Wellington":35357,"Christchurch":29818};
console.log(cities);
alert( cities.Auckland );
You don't get the alert box because most likely your code throws a JavaScript error and simply stops executing after you try to parse the object.
I guess the handler function is never fired: There is no load event on the document object (see window.onload vs document.onload). You don't need to wait for that anyway, because you have nothing in the handler that interacts with the DOM - and you execute it in the bottom of your <body> tag (see Is the 'onload' necessary when the code is at the bottom?).
As JSON is a subset of JavaScript, you can directly output it into a script as a object literal:
var jsonObj = <?php echo json_encode($rowarr); ?>;
console.log(jsonObj);
alert( jsonObj.Auckland );
No need to parse it. Especially, when your JSON had contained an unescaped apostrohe, this would have broken your string literal.

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 :)

How to get dynamically-generated JSON into PHP

I've got a JSON value that has been converted from a JavaScript object using JSON.stringify. I'm trying to parse the contents of the JSON using PHP, but I haven't had any luck. I'm sure I'm doing something really basic wrong.
In file1.php, I've got something like:
<html>
<head>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script src='/json2.js'></script>
<script>
var irxmlnewsreleases = new Array();
irxmlnewsreleases[0]={
"attachmentfileid":12039
};
var news_release = JSON.stringify(irxmlnewsreleases);
$(document).ready(function () {
$("#response").text(news_release);
});
</script>
</head>
<body>
<div id="response"></div>
</body>
</html>
I'm then trying to read this data from file1.php using json_decode in file2.php.
I tried first (wrongly) using file_get_contents and have been bashing at this for a while without success. I guess the issue is obviously that the JSON value doesn't exist until the JavaScript is run, so PHP is of course never able to read the value of the jQuery-generated div content. What I don't know is how to get that value.
The JSON is being generated successfully in file1.php and is valid JSON (I've run it through jsonlint).
What's a better way of getting the value of that dynamically-generated JSON into PHP?
$(document).ready(function () {
$("#response").text(news_release);
$.post('file2.php', { php_post_var1: news_release }, function (data) {
//do something with the PHP script output here if you want
});
});
Then in your PHP script file2.php do something like
<?php
$news_release = $_POST['php_post_var1'];
echo 'PHP received ' . $news_release;
?>

Categories