Calling Javascript Function From Php Not Working
Solution 1:
Seems like you're having two pieces of code in two separate script blocks. That won't work.
In order for function hoisting to work, they need to be in the same tag (the hoisted function needs to be defined there).
Here is a similar question with a more detailed answer: Why is my javascript function not being called in my div?
UPDATE (per request)
The browser reads one block of JS at a time, so hoisting works only within the same block (or if the function is defined before, of course). In your case, probably the easiest solution would be to assign the code to a PHP variable, and then just echo it in the same script block:
PHP
$js = '';
if ($confirmation){
$data = $membership->get_data("assump");
$js .= 'var data = '. json_encode($data) .';
var dataLoaded = ' . json_encode(false) . '; loadData();';
}
HTML
<scripttype="text/javascript"><?=$js?>// or <?phpecho$js; ?>functionloadData(){
// Do stuff with the data
}
</script>
Note that this allows you to inject several lines/parts of JS via PHP, that's why I used $js .= ...
instead of just $js = ...
.
Note that this won't work with external .js files unless you make PHP parse them as well first (nothing to worry about in your code since your JS is in the HTML file which is parsed normally).
Post a Comment for "Calling Javascript Function From Php Not Working"