Is using a hidden <input> with its value set to something in php to then pass to jquery bad?

I am developing a wordpress theme and I have a contact form that uses jquery to check for errors and then show a confirmation message if the email was sent successfully.

Before the confirmation email is shown, I want to show a loading.gif so the user knows it is doing something. My problem is assigning the img SRC url in jquery, as I do not want it to be fixed.

Read More

I want to set it to get the site url and then add the image name to it.

As you cannot parse PHP in js I thought that maybe I could cheat and do the PHP on the form page using a hidden input that passes the data to JS.

So i’d have a

<li class="hiddenurl">
    <input name="hiddenurl" value="<?php bloginfo('url'); ?>">
</li>

and then in jquery i’d set the value to a variable and then in JS:

$(this).parent().append('<img src="'+variable+'/library/images/loading.gif" etc

Is this a bad way of doing it?

Related posts

Leave a Reply

3 comments

  1. As you cannot parse PHP in js

    Wrong.

    <script type="text/javascript">
        var myvar = <?php echo json_encode($some_php_variable); ?>;
    </script>
    

    json_encode makes any PHP variable (except Resources) instantly parseable by JavaScript. It’s sort of like var_export but for use in JavaScript instead of PHP.

  2. It’s not necessarily a ‘bad’ way of doing it, but jQuery provides the .data() method to accomplish exactly this. You can use it to add your own “data-” annotations in the HTML and then retrieve/set them in your JS code.

    See the jQuery Docs here: http://api.jquery.com/jQuery.data/

    So I would use this to add the url to the image and in the JS grab it out..

    If you were looking to just pass the URL as a variable in the JS, then @Kolink has the correct answer for this.

  3. this cant be bad , as it doesnt harm anything .. but if you only want to get the url then why not ..

    window.location
    

    like so

    window.location.pathname // outputs "/questions/14526659/is-using-a-hidden-input-with-its-value-set-to-something-in-php-to-then-pass-to"
    
    window.location.origin  // outputs http://stackoverflow.com