View Full Version : pass a variable from php file to javascript? surey this is simple?

05-14-2009, 08:39 PM
Hi guys I ahve had a good look around and cant seem to find a simple answer to something I feel is really simple.

I have my own Ajax call to a php file, this php file quieries the database and then gives a variable one of three different results.

I basically then need javascript to read the value of that variable and perform a task.

Everything is working but I cant seem to send a varialbe from php to javascript.

For instance I can echo the variable from the php file, which is then placed by javascript via innerHTML into a div, I can then do an indexOf on the innerHTML and then perform the relevant other Javascript functions depending on the result.

But this really isnt ideal....

How can I simply pass a php variable into javascript?

I dont really want to use eval (not sure why but I have heard its bad!)

Philip M
05-14-2009, 08:53 PM
JavaScript cannot actively read variables from the server, but when a page loads, PHP can pass variables to JavaScript by writing to the page the JavaScript is on.

$username = "Philip";

<script type="text/javascript">
var sStr = "My name is <?php echo $username ?>.";
document.write(sStr); // My name is Philip.

If there are only three possible results (values) then I would use a regex.

if (/Philip/gi.test(sStr)) { // do something
if (/Peter/gi.test(sStr)) { // do something else

"Before a man speaks it is safe to assume that he is a fool. After he speaks it is seldom necessary to assume". - H.L. Mencken 1880-1956, American Editor, Author, Critic, Humorist

05-14-2009, 09:13 PM
Thanks. I am looking into JSON it seems to fit the bill a little better. What do you think?

Old Pedant
05-14-2009, 09:20 PM
Make up your mind: Do you want to do this via an AJAX call--for which JSON might be appropriate, but not if it's just for a single value--or do you want to do it by creating the JavaScript from PHP code?

Philip's answer had nothing to do with an AJAX call, by the by.

And if you can "echo the variable from the php file, which is then placed by javascript via innerHTML into a div" then you *MUST* have had the value from PHP in JS variable. So you must have already done this.

05-14-2009, 09:31 PM

I want to have a variable from an ajax call that calls a php file and then returns a qury from the database so i can then peform a task in Javascript

So currently yes I am echoing the variable from php, into a div.innerHTML and then I am readin the innerHTML of the div and performing an action on the contents.

What I want to do is to echo a variable from php, which then will be placed into div.innerHTML and then
I can use Javascript on completion of the ajax call to perform an action

if variable == 'option1' then do this.

To me it seems a little wrong to be placing an echo into a div and then either using indexOf or regex to read this and perform an action, it feels cleaner to use a variable? (if possible)

And yes JSON looks pretty cool I will look into but as you pointed out this is only returning a single variable so no point and I have used phillips idea before but as you pointed out it istn for this situation.

Whats your suggestion on the best way to go? Thanks

Old Pedant
05-14-2009, 09:42 PM
I'm still mystified. HOW are you "echoing the variable from php, into a div.innerHTML"???

How about showing some code?

If you are doing something like

<textarea name="foobar"><?= $somePHPvariable ?></textarea>

then, yes, you could surely do as Philip showed you and just code

var jsFoobar = "<?= $somePHPvariable ?>";

(And yes, <?= $x ?> is just PHP shorthand for <? echo $x; ?> ... How come so few PHP people use the shorthand notation?)

05-14-2009, 10:13 PM
Ajax Call

var emailResponse = document.getElementById('email_response');

url: "invite.php",

type: "POST",

info: info,

onError: function(){
//do something error wise

onSuccess: function(html){

emailResponse.innerHTML = html;

if( emailResponse.innerHTML.indexOf('variablefromphp'){
//do something with the variable


//do something time out wise

Php file invite.php

#AJAX RESPONSE FOR CHECKING NEW EMAIL. if its in the db, once (wheather its one of two differnt types), or if its in the db twice

$email = $_POST['inemail'];

$OK = false;

$email = "SELECT id, other
FROM users
WHERE blah= ?";

$stmt = $conn->stmt_init();
if ($stmt->prepare($email)){
$stmt->bind_param("s", $email, $otherRtn);
$OK = $stmt->execute();
$numRows = $stmt->num_rows;

if (isset($stmt) && !$OK){
echo "<span class='red'><img src='../images/exclamation.png' alt='' class='exclamation'/> Problem speaking with database</span>";

if ($numRows == 1 ){//the email is in the db

if( $otherRtn != ''){
echo "option 1";
echo "option 2";

}else if($numRows == 2 ){ //the email is not in db
echo "option 3";



hope that helps

Old Pedant
05-14-2009, 10:47 PM

It's *YOUR CODE*!!!

You *CHOSE* to do

onSuccess: function(html){

emailResponse.innerHTML = html;

All you had to do, instead, was declare some variable global to the page, say

var getAjaxResponse;

and then do

onSuccess: function(html)
getAjaxResponse = html;

Or you could call some function as part of onSuccess. Or or or...

Nobody ever said you *had* to dump the returned value into a form field!

If you *want* it there, as well as in the variable, you could simply do:

onSuccess: function(html)
emailResponse.innerHTML = getAjaxResponse = html;

But I can't make much sense out of this, in any case.

The value returned from that AJAX call is going to be one of five possible values:

<span class='red'><img src='../images/exclamation.png' alt='' class='exclamation'/> Problem speaking with database</span>
option 1
option 2
option 3
[a blank string...no text]

Why would you want to dump *any* of those values into a <textarea> on the web page???

On top of that, the PHP code doesn't make sense:

$email = $_POST['inemail'];
$email = "SELECT id, other
FROM users
WHERE blah= ?";

So when you do that second assignment to the variable $email, you just wiped out whatever value you got from the AJAX call.

Even your comment doesn't make sense:

}else if($numRows == 2 ){ //the email is not in db

HUH? If $numRows is 2, then the email is in the db *twice*, I think.

And what about if it's in the DB 3 or more times? Or zero times? You don't handle those cases, so in those ever happened, you would return NOTHING AT ALL from the AJAX query.

If this thing works at all, as it is, I don't understand how.

You really have a DB field named blah??

05-14-2009, 11:01 PM
Sorry I forgot to mention that quite tiredly i have edited and changed the code to place it on the site. The code works fine that wasnt the point of this thread, it is the theory of how i could be doing the task rather than the syntax.

I havent mentioned a textarea - i was/am placing items into a div.

Yes ok so - in the onSuccess function I will assign this result to a variable, then do a quick check and perform the task there and then.

Ok cheers slightly tired and was thinking about this in totally the wrong way. Get it before it goes into the div rather than after!

P.s no i dont have a db field named blah (lol lol)


*edit (ha ha I can see how bad this looks - I can imagine you had a bit of a heart attack seeing this code)

Old Pedant
05-15-2009, 12:05 AM

Glad it's not as bad as it looked.

I dunno where I came up with "textarea" since the code clearly says innerHTML. Blame it on senility.

Philip M
05-15-2009, 10:06 AM
“I am in the prime of my senility” .
Joel Chandler Harris (American Writer, 1848-1908)

rnd me
05-15-2009, 04:23 PM
if you're going to use json in php, it's simpler to use the native json functions, and you can cross domains, which can be one les thing to worry about.

for example:

$ray = "That's \"JS\" for you!";
echo "callback(" . json_encode($ray) . ")";
//shows: callback("That's \"JS\" for you!")

$ray = array( name=>"fred", age=>21);
echo "callback(" . json_encode($ray) . ")";
//shows: callback({"name":"fred","age":21})

to call the php script, use a script tag adder:

function addScript(u){
var scr=document.createElement('script');

function callback(data){ //do something with php info here:

addScript("info.php?") //call php with this command. you can tack on GET params to talk to php...

using callbacks, you don't need eval, or DOM operations, and the data arrives as a javascript variable(s), of the right type and everything, all ready to go.