Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have to pass a php json array into a javascript function's on click event.

BEFORE JSON ENCODE PHP ARRAY STRUCTURE:

Array
(
    [group_id] => 307378872724184
    [cir_id] => 221
)

AFTER JSON ENCODE ARRAY STRUCTURE:

{"group_id":"307378872724184","cir_id":"221"}

The php json array looks like:

if(!empty($cirGrpArr))

   $jsonGrpArr = json_encode($cirGrpArr);

I need to pass the same into a javascript on click function like below:

<span onclick="Login(this,JSON.stringify('<?php echo $jsonGrpArr; ?>'))">click here</span>

The php json array is available in this page but how to pass it on click function so that i can iterate this json array to do some other stuff.

share|improve this question
1  
Why do people insist on writing JavaScript as java-script?! Nowhere, not in any documentation, or any half-decent tutorial, is it written that way. And yet it's a very common error here on SO. –  T.J. Crowder Dec 10 '13 at 12:23
    
A JSON string is in itself valid javascript. When the string is printed it can be iterated as an array, or an object if it contains key/value pairs. –  Flosculus Dec 10 '13 at 12:24
    
What is $jsonGrpArr? Don't show us PHP when you have a question about JavaScript. Show us the generated code that is sent to the browser. –  Quentin Dec 10 '13 at 12:33
    
What a convoluted way of assigning data to an event: make php print out html code with javascript inside it, make javascript dynamic by passing it json encoded php variables... all in one line. This will be a nightmare when the time for maintenance comes –  hanzo2001 Dec 10 '13 at 12:43
add comment

1 Answer

<span onclick="Login(this,'<?php echo $jsonGrpArr; ?>')">click here</span>

and

function Login(e, jsonString){
var data = JSON.parse(jsonString);
}
share|improve this answer
    
but when i try to debug data via console.log(), its throwing Uncaught SyntaxError: Unexpected token ILLEGAL in console. any idea? –  George Joffin Joy Dec 10 '13 at 12:30
    
I am sorry I was using jQuery, updated answer check now. –  Bilal Dec 10 '13 at 12:31
    
i am getting e as this object.. but when trying to debug data after parsing it is showing unexpected token error... –  George Joffin Joy Dec 10 '13 at 12:33
    
in <?php echo $jsonGrpArr; ?> I am assuming this a json string. If not then encode using json_encode() in php –  Bilal Dec 10 '13 at 12:36
    
actually i have encoded it using json_encode –  George Joffin Joy Dec 10 '13 at 12:40
show 7 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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