PHP Javascript Uncaught SyntaxError: Unexpected ILLEGAL Token

I have this PHP script and it is not working correctly. What mistake?

<?php if(isset($success) || isset($failure)){?> <script type="text/javascript"> $(document).ready(function(){ $('div.aler').css('display','block'); $("div.aler").html("<?php if($success){echo '<p class=\"success\">'.$success.'</p>';}elseif($failure){echo '<p class=\"failure\">'.$failure.'</p>';}; ?>"); setTimeout(function(){ $("div.aler").fadeOut("slow", function (){ $("div.aler").remove(); }); }, 5000); }); </script> <?php } 

I think the quotation mark problem is. " $failure has a message, but Javascript doesn't put it in the HTML div div.aler . I get this error message in the Chrome console:

Uncaught SyntaxError: Unexpected ILLEGAL Token

+4
source share
4 answers

you forgot isset in the line below, this is necessary since you are using "||" (OR) in your first if statement, php throws an error and this breaks your javascript

 $("div.aler").html( "<?php if( $success ){ echo '<p class=\"success\">'.$success.'</p>';}elseif($failure){echo '<p class=\"failure\">'.$failure.'</p>';}; ?>"); 

change it to ...

 $("div.aler").html( "<?php echo ( isset( $success ) ) ? '<p class=\"success\">'.$success.'</p>' : '<p class=\"failure\">'.$failure.'</p>'; ?>"); 
+2
source

Php does not exit for ", so instead of \" you need to use \\\ "or \".

Btw json_encode as a string would be much better ...

 $("div.aler").html(<?php if($success){ echo json_encode('<p class="success">'.$success.'</p>'); } elseif($failure){ echo json_encode('<p class="failure">'.$failure.'</p>'); };?> ); 
+6
source

You are trying to put it in div.alert ... but in the code you wrote "div.aler" you miss T ...

+1
source
 $("div.aler").html("<p class='<?=$success? 'success' : 'failure'?>'><?=$success? $success : $failure?></p>"); 

And, of course, exit $success and $failure before exiting.

0
source

Source: https://habr.com/ru/post/1487638/


All Articles