up vote 0 down vote favorite

I have been mis-interpreted. I have created a JSON Object in PHP. I just need access to that object in Javascript. thats all.

i just learned that many of my problems can be solved by using JSON. now how to use JSON is another problem, though ;-)

suppose this is the code in PHP:

$row = array()
while ($row = mysql_fetch_object($result)
{
    $data[] = $row;
}
$javascriptFriendlyData = json_encode($data);

now how to access the $javascriptFriendlyData in javascript. i tried using JQuery but cant really figure out much...

if it helps, the JSON Data structure is somewhat like this:

[{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}...

]

link|flag

79% accept rate

9 Answers

up vote 4 down vote

Try this:

<script>
<?php
echo 'var data = '.$javascriptFriendlyData;
?>
// now the JSON data is stored in the data variable
console.log(data);
</script>

I'm assuming you are running PHP in the HTML template here:

<html>
<head>
<script><?php echo 'var data = '.$javascriptFriendlyData; ?></script>
<script src="some_js_file.js"></script>
</head>
<body>

etc...

In the some_js_file.js, you can now access the data variable.

If it's an array of simple data as you describe, there is little reason to eval() it, but you might consider it anyway.

link|flag
how am i supposed to use this in a javascript file? would it even recognize the <?php tags? – amit Dec 21 '09 at 0:06
1  
A JavaScript file doesn't have <script> tags inside it... It's a sample PHP page. :P – Dustin Dec 21 '09 at 0:11
1  
Just add this to your HTML file before using the data variable in other scripts. – David Dec 21 '09 at 0:18
amit, if you are trying to use this data in a separate js file, you will either have to set the variable in JavaScript before you load the JavaScript file or you would have to make your JavaScript run through the PHP interpreter. – Chris Gutierrez Dec 21 '09 at 0:19
Naturally, I assume you are running PHP in the HTML template. Updated my answer to clarify this. – David Dec 21 '09 at 0:27
up vote 3 down vote

From the official JSON documentation:

var myObject = eval('(' + myJSONtext + ')');

Now you can use it like any other Javascript object.

link|flag
2  
Be careful using this method. The eval function should only be used with caution, otherwise it can easily become a security risk. – TommyA Dec 21 '09 at 0:26
up vote 2 down vote

If you are creating the JSON encoded data in your PHP script and echoing in your JavaScript, you don't even have to call eval because it is already in a native JavaScript format.

So taking your code...

$row = array()
while ($row = mysql_fetch_object($result)
{
    $data[] = $row;
}
$javascriptFriendlyData = json_encode($data);

Then, in your Javascript code you can do something like...

<script type="text/javascript">
var data = <?php echo $javascriptFriendlyData; ?>;
</script>

Then when the page is rendered, the data is already parsed and ready to use. It is when you are handling AJAX requests that return data that it needs to be evaluated. Otherwise, it is no different then using JavaScript notation inline.

eg:

<script type="text/javascript">
var somevar = [{objVar1:"SomeVal"},{objVal2:"SomeVal2"}];
</script>

If you are trying to have your JavaScript in a separate file, then you will need to set this variable in your JavaScript before you load your JavaScript file or run the JavaScript file through the PHP interpreter.

link|flag
up vote 1 down vote

JSON is just a notation for Javascript data. Which means you can have this kind of JS code :

var data = [{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}];

Which will just put your data in the data Javascript variable.


Considering that [] symbolize an array, and {} symbolize an object, you can use this to access the title property of the first element of the data array :

alert(data[0].atitle);

And you'll get

Ameya R. Kadam


And, to loop over each elements of the data array, you can use something like this :

var i;
for (i=0 ; i<data.length ; i++) {
    alert(data[i].aid + ' : ' + data[i].atitle);
}

(Absolutly no need for jQuery for such a task, btw)

link|flag
up vote 0 down vote

If your array is in a variable called data:

$.each(data, function(){
  alert(this.aid);
  alert(this.atitle);
});
link|flag
up vote 0 down vote
var arr = [{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}];

$.each(arr, function() {
    alert(this.aid)
    alert(this.atitle)
})

Or

var arr = [{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}];

$.each(arr, function(i,o) {
    alert(o.aid)
    alert(o.atitle)
})
link|flag
up vote 0 down vote

I have found that the JSON.org Json2.js library to come in handy for going from JSON to JS and back from JS object to JSON. For example, instead of:

var obj = eval('(' + jsonString + ')');

with the JSON.org library you use:

var obj = JSON.parse(jsonString);

You can also specify a second parameter that allows you to work with the results of the JSON being revived as an object.

To go back to a JSON string just call:

var jsonString = JSON.stringify(obj);

This also takes optional arguments to help control JSON string creation.

link|flag
up vote 0 down vote

JSON basicalle represents a Data Structure right, so essentially it's an Object, or instance of a Class, so to use it you do this:

var MyJSonObject = eval("(" + jSonString + ")");

UPDATE

hey Amit, you can't access PHP objects from javascript. What you have to do is somehow construct the JSON string in PHP, but then write it out to the client. I'm not sure how you'd do it in PHP, but this how you'd do it in ASP. The idea is the same, the syntax will be different in PHP.

<html>
	<head>
		<script type="text/javascript">
			var MyObject = eval("(" + <%= Response.Write(strServerSideVariable) %> + ")");
		</script>
	</head>
	<body>
	</body>
</html>

Note that in ASP/.NET the tags "<% %>" denote server side, not client side, code. This is what you have to do with PHP amit

link|flag
i dont think u understand my problem. i have already made a JSON object in PHP. i just need access to it in JS. – amit Dec 20 '09 at 23:42
2  
I don't think you understand andy's answer -- he's giving you a line of Javascript. MyJSONObject ends up being your JSON object, accessible as any Javascript object would be. – delfuego Dec 20 '09 at 23:46
updated my answer. – andy Dec 20 '09 at 23:52
what is jSonString. do i need to replace it with something. how does it find the php object that contains the JSON data? – amit Dec 20 '09 at 23:53
no amit, jSonString is the string representation of the JSON. as is: {"aid:1"}. To get the JSON into Javascript, you don't need a PHP JSON object, you just need the String. – andy Dec 20 '09 at 23:55
show 2 more comments
up vote 0 down vote

It's worth noting that some browsers now provide a set of native functions for JSON decoding and encoding: JSON.parse() and JSON.stringify(). They are safer than using the eval() function and only works if the JSON data is well-formed, whereas eval() would evaluate things like the following:

{
  'hello': (undefined
            ? 'world'
            : ('number ' + Math.floor (40.235)))
}

What's wrong with that? The JavaScript value `undefined' is not available in JSON (only true, false, null, strings and numbers are allowed); single quotes are used everywhere when only double quotes are valid in JSON; you can't call JavaScript functions or perform string concatenation in JSON.

Obviously the last one is a big problem because you could receive some malicious JSON, possibly a value from a form input, that attempts to tamper with things. So when possible, use JSON.parse() and JSON.stringify()...because eval() is dangerous.

Edit:

I misread the original post. If you have a JSON object in PHP and you want to use it in JavaScript, you would need to convert the JSON object to a string and pass it on to JavaScript. The only way to do that would be to make your JavaScript code actually ask for the newly created JSON string in the first place. PHP would return a string, JavaScript would use eval() or JSON.parse() on the string, and you'd have your object in JavaScript. I'm not sure if there is a non-AJAX way to do this without making your JavaScript files into PHP files, setting the Content-Type header, etc., but I know that AJAX would work in this situation.

link|flag

Your Answer

 
get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.