-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.

8
  • 1
    alert('This works') must need <script> Commented Apr 12, 2019 at 14:38
  • in php page, it will as its working in html pages <script>alert(1)</script> Commented Apr 12, 2019 at 14:39
  • 1
    Double quoted strings are parsed in PHP. It this case PHP is trying to replace jQuery $ to PHP variable. Change to single quoted string. Commented Apr 12, 2019 at 14:42
  • @WebHQ: agreed , and he also having issue with first alert as he is not terminating. Commented Apr 12, 2019 at 15:01
  • did u checked @banjoquint Commented Apr 12, 2019 at 15:25

2 Answers 2

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'); 
});";
Sign up to request clarification or add additional context in comments.

2 Comments

JS doesn't need semicolons
@Miken32 u r right but u echo both together u will get an error in console plz try
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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.