Alternative to inline js with php


I currently have some inline javascript in a php loop.

To make things simple, here is an example.

while($loop_data) {
echo $post_id;
alert(“<?php echo $post_id ?>”);
<? } ?>

Is there a way to stop the javascript from being the in the loop?
The reason is because im using a .load function and this stops the script from executing.

  1. why are you using inline JavaScript rather than keeping it in its own separate file where it belongs. If the JavaScript needs to be generated from PHP then give theJavaScript file a PHP suffix and set the correct MIME type for the file using a PHP header.

  2. If you attach the JavaScript to the bottom of the page where it belongs you will not need to use a load function.

  3. alert() is for debugging purposes only - you should replace it before your page goes live.

1.) I’m using inline javascript because it needs be in the loop. It is basically for a video player.

2.) This makes no sense. The load function has nothing to do with where my javascript is located. I’m using the .load function to load more posts.

3.) Once again, the code I posted above is an EXAMPLE to make things simple. Would you rather have me post 100 lines of code?

The JavaScript can still be in a separate file even if it does use a loop.

The JavaScript should go just before the </body> regardless.

Each separate JavaScript should be in a separate anonymous function - then they cannot clash with one another unless they both try to update the same piece of content in contradictory ways.


Thank you for your response.

I’ve now put the javascript in a seperate file and I am passing the php data through data attributes.

Now I have another simple problem. How can I put variables inside the jquery settings?


image = " "

How do I put a variable in those quotes. Obviously, I can’t simply put the variable straight in there because it wouldn’t read the data inside the quotes.

image = " “+variablename+” "

simply exit out of the quotes to specify the variable name and concatenate using +

that’s extremely basic JavaScript which is way below the level needed to be able to use JQuery. Sounds like you need to learn a bit more beginners JavaScript if you are going to use JQuery - that library needs a reasonable level of JavaScript knowledge to be able to use it properly (without the required JavaScript knowledge people tend to use half a dzen JQuery statements to do what a single line of JavaScript can do (which is the exact opposite of what JQuery is for).