Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Javascript Uncaught SyntaxError: Unexpected token ILLEGAL

Tags:

jquery

php

I have this PHP script and it does not work properly. What is the mistake?

<?php
if ( isset($success) || isset($failure) ) {
?>
<script>
    $(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 there must be a problem with quotes:

" . $failure

has the message, but the JavaScript does not put it in HTML div:

div.aler

I get this error message in the Chrome console:

Uncaught SyntaxError: Unexpected token ILLEGAL

like image 763
Pmpr.ir Avatar asked Jan 13 '23 02:01

Pmpr.ir


2 Answers

The php output is not escaped for ", so instead of \" you have 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>');
    };?>
);
like image 120
inf3rno Avatar answered Jan 25 '23 23:01

inf3rno


you forgot isset in below line, its required since your using "||" (OR) in your first if statement, php throwing an error and thats breaking your javascript

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

change this to...

$("div.aler").html( "<?php echo ( isset( $success ) ) ? '<p class=\"success\">'.$success.'</p>' : '<p class=\"failure\">'.$failure.'</p>'; ?>");
like image 41
bystwn22 Avatar answered Jan 26 '23 00:01

bystwn22