Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
110
rated 0 times [  111] [ 1]  / answers: 1 / hits: 25607  / 12 Years ago, mon, october 29, 2012, 12:00:00

I'm doing something which I need to pass an array from my php to a function on an external javascript. I'm currently doing some test right now which looks like this:



<input type=text onclick=show_error_message('<?php echo $array_sample ?>') readonly=readonly>


and the javascript function is this one:



function show_error_message(test) {
alert(test)
}


my $array_sample contains data which is array(1,2,3); but the return alert would be Array and whenever I change the $array_sample into $array_sample[0] when passing the parameters I got a data which is 1 as alert. I wonder how can I pass the whole array on this to be fetched also by an array in javascript. Well as you can see, I intended it to be a popup message for error handling which is why I need it to be dynamic.


More From » php

 Answers
20

Use json_encode



onclick='show_error_message(<?php echo  json_encode($array_sample) ?>)'


or



onclick=show_error_message(<?php echo htmlspecialchars(json_encode($array_sample)) ?>)


Notice the lack of quotes(') around the php code, this way an array literal is passed to show_error_message and not a string.


[#82304] Friday, October 26, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
collinisaaka

Total Points: 194
Total Questions: 105
Total Answers: 104

Location: Tonga
Member since Tue, Nov 30, 2021
3 Years ago
;