-1

I am trying to embed some JavaScript into a php page with the intention of getting Jquery to work. The php is in a wordpress site. This will eventually form the basis of a plugin. I have used <script> tags to embed a call to an alert function, which does work well. Problem is if I try to add some jquery code e.g $(document).ready(function(){}); it doesn't work, any consequent alerts don't work, no errors or anything!

I've tried googling the problem and there's loads of advice but nothing is working

echo "<script>alert('This works')</script>"

echo "<script>
$(document).ready(function(){

alert('But this doesn't');});
</script>"

The first alert appears fine, but the second doesn't.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150

2 Answers2

1

In your code, you have 2 issues, first of all, you are not terminating your first alert:

echo "alert('This works')"

you must need to terminate with ; otherwise it will give you javascript error.

Second, in your second alert you have quotation issue, you are using single quote inside a single quotes.:

alert('But this doesn't'); // remove single quotation from here.

I tried this and its working fine:

echo "alert('This works');"; // terminate the first line
echo "$(document).ready(function(){
alert('But this does not'); 
});";
devpro
  • 16,184
  • 3
  • 27
  • 38
0

This is really bad codding. You should separate logic and view layers into script and template files.

But if you have no other option try Heredoc strings:

echo <<<EOT
<script>
    $(function() {
        alert("this will work with > ' < char included");
        alert('this will work with > \' < char included');
        alert('this will work with');
        alert("this will work with");
    });
</script>
EOT;
WebHQ
  • 711
  • 8
  • 21