pass variable from php to be used in jq

时间:2015-07-28 23:58:52

标签: javascript php jquery ajax

Im trying to pass a php variable from php page and use that variable in jq.

trying to assing to the image a class that is a php variable

the php code:

var pattern = /(\w'\w)|&/;

and that image class $id I want to use in my jq code

while($row = $results->fetch_assoc()) {
$id = bin2hex(openssl_random_pseudo_bytes(8));
$pro_makat=$row["product_makat"];
$pro_id = $row['product_id'];
$products_list .= <<<EOT

<li>
<form class="form-item">
<h3 id="title" style="color:#cc00cc;">{$row["product_title"]}</h3>
<div><a href=""><img id="image" src="admin_area/product_images/{$row['product_image']}" class="$id" ></a></div>

how is it possible to make it work?

2 个答案:

答案 0 :(得分:0)

to echo an variable inside html/javascript just do:

undef

...assuming you are OUT of the EOT

答案 1 :(得分:0)

You almost had it but for a syntax error.

var data = {
        labels : ["January","February","March","April","May","June","July"],
        datasets : [
            {
                fillColor : "rgba(220,220,220,0.5)",
                strokeColor : "rgba(220,220,220,0.8)",
                highlightFill: "rgba(220,220,220,0.75)",
                highlightStroke: "rgba(220,220,220,1)",
                data : [DATA FROM MY PHP ARRAY IN ANOTHER FILE WOULD GO HERE...]
            }

Should be

 $('.".$id"').click(function(e) { 
 ....

Notice the missing $('.".$id."').click(function(e) { .... which is like the . in javascipt or the concatenation operator. But you still will need the css selector such as + for class and . for id, and be sure to not forget the # single quote for the javascript. Although I am pretty sure because you have a ', you could get away with just doing this instead HEREDOC or $(."{$id}")... maybe even just $(.'{$id}')...

I know it gets a bit confusing with all these different languages using different symbols, or using them for different things. Personally I'm not a big fan of PHP using the $(.'$id')..., but because of the loose typing the . is out because you can actually add string values in php such as + so you see that is one of the reason PHP uses that instead of the plus. What should PHP do in that case add them or make it '1' + 1 = 2? So they use the dot.

That is assuming this is all within the heredoc 11 otherwise you'll need to use <<<EOT

I love heredocs ... just saying. What is the advantage of using Heredoc in PHP ?

Just for clarity when using the HEREDOC or NEWDOC you have to end them on their own line. So you have to do them like this

<?php echo $id; ?>

OR

$a = array(
    'content' =>  <<<DOC


DOC
);

Same for NEWDOC with is like the $content = <<<DOC DOC; single quote in that there is no variable interpolation so

'

So the first prints

$novar = 'Hello';

echo  <<<'DOC'
$novar
DOC;

echo  <<<DOC
$novar
DOC;

But the second prints

 $novar