Ilyes Ferchiou
Ilyes Ferchiou

Reputation: 583

Passing PHP variables to JavaScript as variable through jQuery-AJAX load() function

I have 2 files, main.html and search.php.

Within the main.html page, there is this piece of code :

$("#results").load("search.php",queryString,function(response,status,xhr){
... some code here
})

Within the search.phppage, there is this piece of code :

$image_id=mysql_insert_id() // getting the last ID of the last query - works perfectly

What I want to do is to echo this variable to the main.html file and store it within a JS variable called im_id that I can call through the main.html page.

I tried to do this

echo "<script type=\"text/javascript\">$im_id=".mysql_insert_id()."</script>";

but it doesn't work at all.

I found a workaround which is to store the content within a textbox like this

echo "<script type=\"text/javascript\">$(\"#textbox\").val(".$image_id.")</script>";

and then in the JScript, use

$im_id=$("#textbox").val();

and many other methods using an "intermediary" but isn't there a straight way to set the variables directly ?

Any help would be appreciated.

Upvotes: 1

Views: 1072

Answers (2)

Radu
Radu

Reputation: 8699

The reason it's not working is that php replaces variables inside double quotes with the value of your variable. This makes for easy templating. For more information see the variable parsing section of the php docs.

<?php
$juice = "apple";

echo "He drank some $juice juice.".PHP_EOL;
// Invalid. "s" is a valid character for a variable name, but the variable is $juice.
echo "He drank some juice made of $juices.";
?>

The above example will output:

He drank some apple juice.
He drank some juice made of .

Either replace the double quotes with single if you want to have a variable name in javascript that starts with a $:

echo '<script type=\"text/javascript\">$im_id='.mysql_insert_id().'</script>';

or, don't use a $ in your variable name:

echo "<script type=\"text/javascript\">im_id=".mysql_insert_id()."</script>";

Upvotes: 1

TJHeuvel
TJHeuvel

Reputation: 12608

Its not working because you output $im_id=1, you should output var im_id = 1; instead.

In your PHP:

echo "<script type=\"text/javascript\">var im_id = ".mysql_insert_id().";</script>";

If it still doesnt work look at the generated code, not the PHP source. Just go to view source in your browser, and use a debugger to find out whats wrong.

Upvotes: 3

Related Questions