Jump to content

how to use php associative array in JS


Go to solution Solved by Jacques1,

Recommended Posts

I have taken an PHP array that looks like this:

 

$arr = ('key1'=>'value1','key2'=>'value2','key3'=>'value3');

 

and run it thru json_encode() to assign it to a JS var:

 

<script type='text/javascript'>

var ar = <?php echo json_encode($arr, JSON_PRETTY_PRINT); ?>;

 

 

Now I am trying to figure out how to use this JS array (object?) variable and find values based on the keys in it. Basically if given a key, I want to find out if it exists in the array and what the value of that key is. Not having much luck.

Link to comment
https://forums.phpfreaks.com/topic/301019-how-to-use-php-associative-array-in-js/
Share on other sites

Inserting JSON-encoded data into a script element is unsafe. There's a FAQ article about the security problems of this approach and reasonable alternatives.

 

The existence of properties in a JavaScript object can be checked with hasOwnProperty(). The value can be accessed with the dot or bracket syntax (foo.bar or foo['bar']).

See the article. There's a complete example at the bottom (starting with “If you're into micro-optimization ...”).

 

The idea is to JSON-encode the data, HTML-escape it, put it into a hidden HTML element and then parse it with JSON.parse(). Or you simply use Ajax.

Well, I thought I pieced it together but no luck.

 

Before I begin outputting any of the html/JS code I do this:

$json = json_encode($_SESSION['atts_ar']); // encode my array
$json_object = htmlspecialchars($json,ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8');

 

Then I created a JS function:

function getJsonData()
{
   atts = JSON.parse(document.getElementById('json_data').innerHTML);
   alert("atts is "+atts);
}
which gets output as part of my web page.

 

At the bottom of my html/web page I output this:

echo "<div id='json_data' class='json_data'>";
echo $json_object;
echo "</div>";

where the class is defined as visible so I can see the data which looks like this:

 

{"055":"Bluman, Anthony","148":"Duncan, Paul",.....

 

Then in my body tag I added an onload to call the JS function:

<body onload='getJsonData()
So to summarize:

I created the proper json object;

I buried it in my html

I wrote a JS function to grab the buried data

I called the function on the page load.

Net result is that the alert shows that the end result is an object

 

Is this what I should expect? And if so, how do I search this array/object based on the key elements?

Solved! The code that I had to do a search was outside a function and therefore executed out of sequence.

 

Thank you very much Jacques! Once again..... well, you know.

 

 

OOPS - last question. Here is my search function:

 

	function keyExists(key, search)
	{
		for (k in search)
		{
			alert("checking "+k+" - "+search[k]);
			if (k === key)
			{
				return true;
			}
		}
		return false;
For my test I use the Bluman code - 055 - which I can see on screen as being the first element of the array/object yet I watch search function begin with the 2nd element and finally get to the first one LAST! What's that about? Edited by ginerjm

I know I marked this as 'Answered', but I have a followup question.

 

My script receives user input that my js code adds to the object that my json code created. For debugging purposes I have made the div that holds the php array visible so I can see what my json object contains. I have managed to get the js code to add a new element to the object which I verify with the hasOwnProperty after adding it. What I can't seem to do is get the div to be refreshed with the updated contents of the object. I try to set the value or innerHTML props of the div but all it displays "[object Object]".

 

Can I not do this?

You have to JSON-encode the object again and put it into a text node within the div element. Don't use innerHTML, because this will interpret HTML tags.

 

However, there are much easier ways of debugging (like the JavaScript console).

Edited by Jacques1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.