what is best way to pass php variable to jquery besides setting valud to id or attribute

Posted on 2009-12-29
Last Modified: 2013-11-10
Sorry for what seems to be such a basic question but this small little detail is alluding me. What is the best way to pass a php variable to jquery without setting the value within the DOM structure? Is there another way besides setting a variable so that jquery can use the variable?

An example would be the value of a mysql database count i.e. 5 animals, 2 vegetables, and 1 rock.  <div id="animalCount"><?php echo $theAnimalCount;?></div>

Question by:kent3800
    LVL 58

    Accepted Solution

    <script type="text/javascript">

    $(document).ready(function() {
        var AnimalCount = <?php echo $theAnimalCount;?>;
        //Use AnimalCount
    LVL 82

    Assisted Solution

    You can use cookies, but if the user's browser has disabled cookies, your application will not work.
    Another alternative would be to use hidden fields:
      <div id="animalCount"><input type='hidden' name='animals' id='animals' value='<?php echo $theAnimalCount;?' /></div>

    you can then retrieve the value with:

    Lastly, you can initialize some javascript variable:
    var animals=<?php  echo $theAnimalCount;?>;
    LVL 4

    Author Closing Comment


    Featured Post

    Free Trending Threat Insights Every Day

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    Part of the Global Positioning System A geocode ( is the major subset of a GPS coordinate (, the other parts being the altitude and t…
    In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
    The viewer will learn how to count occurrences of each item in an array.
    The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now