search

Home  >  Q&A  >  body text

Can I set a javascript variable to a string containing the output of the php code?

I'm trying to set a javascript variable equal to the output of the php code:

var name = '<?php global $email; echo json_encode(passthru("python Backend/User/getName.py $email"));?>';

When it runs, it returns the correct value, but it also appends a null value:

var name = 'name
null';

This causes the code to treat the value as null instead of the returned name.

P粉754473468P粉754473468262 days ago606

reply all(1)I'll reply

  • P粉218361972

    P粉2183619722024-04-05 00:31:26

    As mentioned above, passthru returns null on success and false on failure.

    What you want to get is the contents of the file, so an easy way is to use output buffering.

    You can use a simple function to return the value of the script like this:

    
    sssccc
    

    === just incase you didn't know what the shorthand annotation means.

    This will get the value of the python script and then set it to the js value.

    This will return an empty string on failure, so you may need to do some exception handling depending on your needs.

    reply
    0
  • Cancelreply