1

I cannot figure out how to grab a PHP variable and use it as a jQuery variable.

So, I've got for example this variable:

$content = "bla bla bla";

And it is inside a DIV:

div id='contentWrapper'

$content = "bla bla bla";

/div

I know how to grab the ID, class and content (text) of the DIV contentWrapper, but how do I grab $content? I hope I am being clear enough :)

3
  • var myVar='<?php echo $content;?>'; ? Commented Apr 5, 2013 at 16:31
  • a little confused... when you grad the id of the dic you probably mean in javascript... there is no $content...one is a client language and the other one a server language... am I right ? maybe I did not understand what you meant Commented Apr 5, 2013 at 16:32
  • what does your div look like? When do you want to grab the data in the div? Once you grab the div you use .html() or .text() usually to get any content Commented Apr 5, 2013 at 16:33

3 Answers 3

2

You can't. The PHP runs on the server. The output of the PHP gets sent to the browser. JavaScript runs in the browser. JavaScript has no access to the internals of the script that generated the page it is running in.

You would have to modify the PHP to output the information you want to make available to JS so that it appears in the page.

Sign up to request clarification or add additional context in comments.

Comments

1

In the javascript, you can do:

Edit:

Based on @Marc B's comment.

var jsvar = <?php echo json_encode($content); ?>

5 Comments

no. you can't. one single JS-metachar and you've killed the entire JS block. ALWAYS output php->js via json_encode: var jsvar = <?php echo json_encode($phpvar); ?>;.
But what if there is more then one instance of $content on the page. How do I get $content specifically from the inside a specific div.
you can just access the html from the classname/id of the wrapper div
So something like: $("#contentWrapper").<?PHP echo json_encode($phpvar); ?> ?
No.. that would not work. Once the page renders, you can do $('.class_name_of_the_div').html()
0

According to what I believe PHP is server side scripting which is hidden from browser and Jquery script is executed by browser. So to obtain the variable value you need to echo and show your content to browser to complete JQuery. Use the method provided by Jonathan Sampson

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.