简体   繁体   中英

Passing php array to javascript function from external php file

I'm working on autofilling an html form based on data from a sqlite database. I'm using a modified version of the code from this site and in its basic feature it works as expected. The main input element calls, "onkeyup", a javascript function called "lookup", that in turn calls a external php script passing the current string to query the database.

The script returns a string to update the input form:

echo '<li onClick="fill(\''.$result->value.'\');">'.$result->value.'</li>';

The javascript function "fill" is as follows:

function fill(thisValue) {
    $('#inputString').val(thisValue);
    setTimeout("$('#suggestions').hide();", 200);

"#inputstring" is simply an input element.

What I would like to do instead of returning a string is to return an array and parse it inside the "fill" function to assign the different values to different elements in html. The problem is that to pass the php array to javascript I have to convert it somehow. I've tried to make it a json string as suggested many times here on stack, but for what I suppose is a problem of quotes, it always return a null value. I've tried:

$valuetopass = json_encode($query_result);

whithout

echo '<li onClick="fill('.$valuetopass.');">'.$query_result['text'].'</li>'; 

and with quotes

echo ''.$query_result['text'].'';

And both fail.

I'm aware that similar question have been already asked 1 , 2 ,ecc... But all of the answers suggest to embed php when assigning the javascript variable. In my case the php is called from the function "lookup" and from that php script I want to return to the function "fill".

How can I produce from inside php a string that includes a json string with a format that can be passed to the "fill" function?

Or alternatively how can I rework the problem so that I don't need to do it at all?

Your JSON string is likely to contain " , so of course you get a syntax problem when you insert that into onClick="fill(...);" untreated.

Using PHP's htmlspecialchars should be able to fix this in this instance.


In the long term, you might want to look more into the separation of code and data though.
Attaching event handlers using inline HTML attributes is kinda “old-school”, today that should rather be done from inside the script, using addEventListener resp. whatever wrapper methods a JS framework might provide for that. The JSON data could then for example be put into a custom data attribute, so that the script can read the data from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM