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.
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?
Wrong.
json_encode
makes any PHP variable (except Resources) instantly parseable by JavaScript. It’s sort of likevar_export
but for use in JavaScript instead of PHP.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.
this cant be bad , as it doesnt harm anything .. but if you only want to get the url then why not ..
like so