Operation of "Alert" in javascript

Asked

Viewed 53 times

1

I would like to know why the code below works when the field only has digits (numbers), but it does not work that there is at least one letter in its contents. For example, if the field NUM_ORDEM (varchar) have a letter, the alert does not work, but if all digits are alert works, even being a field type varchar.

<script>
function menu_fim() {
    <?php
        $w = $total - 1;
        mysqli_data_seek($dados,$w);
        $linha = mysqli_fetch_array($dados);
        $x = $linha['ITEM'];
        $h = $linha['NUM_ORDEM'];
    ?>
    alert(<?php echo $x ?>);
    alert(<?php echo $w ?>);
    alert(<?php echo $h ?>);
}
</script>
  • I wouldn’t recommend doing it this way, use ajax instead to return the necessary information

  • I do not recommend using this way because the structure is messy (the ideal would be to divide its parts with some Pattern design, but I don’t think using Ajax is necessarily better, it may be that yes, it depends on the context of this code and the rest of the application

  • Thank you so much for the support. I hadn’t really noticed the error. It’s software with many details in the syntheses.

  • I read about Ajax. I’ll start learning.

1 answer

5


If you have text in your variable $h, the code generated by PHP will be something like this:

alert(Caracteres);
//    ↑↑↑↑↑↑↑↑↑↑
// Sintaxe Inválida

Invalid in Javascript syntax.

You need to treat it like a string:

alert('<?php echo $h; ?>');

And to ensure that possible quotes do not make the code create an error, it is worth using the function addslashes. We will then:

alert('<?php echo addslashes($h); ?>');
  • Thanks for the tip. It worked perfectly. Thanks a lot!

  • Glad you helped, @David! Don’t forget to click on the check icon ( ) to mark the answer as accepted, if desired. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.