1

Is it possible to assign a class from a php variable to a new appended div in jquery?

$newItems = $('<div class="PHP VARIABLE PRINTS HERE A CLASS"></div>');

In my case, for other things, I am defining a var to defign what I then append in jquery but I need to get the class of the newly inserted div from a php variable. Is it possible?

8
  • 1
    Only if you are printing out this string with PHP, but if you have to do this then you're doing it wrong Commented Feb 10, 2013 at 0:25
  • That depends how you are processing the JavaScript file to start with. If it is passing through the PHP processor or it is static content Commented Feb 10, 2013 at 0:25
  • 1
    <?php echo "class";?> ? And @ExplosionPills, what's wrong with echoing php inside js? Commented Feb 10, 2013 at 0:25
  • @ExplosionPills, There are reasons why you might want to write JavaScript with PHP. Commented Feb 10, 2013 at 0:25
  • @DamienPirsy so in jQuery this is valid? $newItems = $('<div class="<?php echo "class";?>"></div>'); Commented Feb 10, 2013 at 0:26

3 Answers 3

4

In PHP

<?php
    // First you need to have the variable with the name of classe
    $myClass = 'name_of_my_classe';
?>

 

In Javascript:

$newItems = $('<div class="<?php echo $myClass; ?>"></div>');
Sign up to request clarification or add additional context in comments.

3 Comments

bingo! Thanks a lot. Didn't know I could simply put a php like that inside jQUery
If you're on newest PHP shortag should be enabled by default: class="<?= $myClass; ?>"
Remember that if you use shorttags you must set short_open_tag = on in PHP.ini
1

There are two different ways I would imagine doing this.

Firstly you could use Ajax to get the variable earlier on, from the php variable, or you could simply echo the variable there inline from a function within the file.

The first way of doing this, using Ajax, is perhaps a more standard way of doing this, whereas I would count the latter method as a little bit quick and dirty.

Comments

0

I think that hardcore mixing of PHP and JavaScript code is an anti-pattern and can lead to confusion. I would limit PHP emissions to build HTML and use the JavaScript code to parse said HTML to get your desired client result:

//php
echo '<span hidden id=class-container data-class=name_of_my_class>';

//JavaScript
$("<div>").addClass($("#class-container").data('class'));

3 Comments

I am creating and appending the div with jQuery, not php tho
but it also prints it with php? i mean what happens to the echo? That'll print too no?
It prints the span with PHP. The JavaScript can be in a separate file with the rest of your JS (recommended), or you can also print it out with PHP I suppose

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.