0

I'm building a table who have a button. When the user click this button the stat of row changes, in the table this represents a field with 0 or 1. Fine i'd made the button but i get an error in some rows, the error is Uncaught SyntaxError: missing ) after argument list, and i get very confused because the code works on like 80% of the time.

The problem wasn't with the database because i'd already searched for some field with problems.

function enviaAssociado(CTITULAR) {
    if (CTITULAR) {
        $("#CTITULAR").remove();
        $.ajax({
            url: 'php_action/enviaAssociado.php',
            type: 'post',
            data: {
                CTITULAR: CTITULAR
            },
            success: function() {
                manageTable.ajax.reload();
                //$("#CTITULAR").val(response.CTITULAR);
            }
        });
    }
    manageTable.ajax.reload();
}

PHP

`

$CTITULAR = $_POST['CTITULAR'];


$sql = "UPDATE importsmiles4e.tb_conv
SET    STAT = CASE
     WHEN  STAT = 1 THEN 0
     WHEN  STAT = 0 THEN 1
     ELSE STAT
   END
WHERE  substring(CTITULAR,2,6) = '$CTITULAR'
";
$query = $connect->query($sql);

$CTITULAR = $_POST['CTITULAR'];


$sql = "UPDATE importsmiles4e.tb_conv3
SET    STAT = CASE
     WHEN  STAT = 1 THEN 0
     WHEN  STAT = 0 THEN 1
     ELSE STAT
   END
WHERE  substring(CTITULAR,2,6) = '$CTITULAR'";
$query = $connect->query($sql);


// close the database connection
$connect->close();

echo json_encode($sql);

`

The Table

while ($row = $query->fetch_assoc()) {

$active = '';

if($row['EMAIL'] != '') {
        $active = '<label class="label label-success">Cadastrado</label>';
    } else {
        $active = '<label class="label label-danger">Cadastrar</label>'; 
    }


$botao = '<a type="button" class="btn btn-default" onclick="enviaAssociado('.$row['CTITULAR'].') ">Alterar</a>';

$status = '';

if($row['STAT'] == '0'){
    $status ='<label class="label label-warning">Não</label>';  
}else{
    $status ='<label class="label label-success">Sim</label>';
}

$output['data'][] = array(
    $row['NOME'],
    $row['CPF'],
    $row['CEPRES'],
    $row['NROPROPOSTA'],
    $row['DTADMISSAO'],
    $row['DEPENDENTES'],
    $row['VLSMENS'],
    $status,
    $botao,
);

https://i.stack.imgur.com/KnD7w.png => error Log

https://i.stack.imgur.com/MhsDh.png => Return when error

The return when success is the same the only change is the value key and i've already check if the values are broken.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • 1
    it's a JS error .. nothing to do with the PHP (after brief look) – treyBake May 13 '19 at 13:21
  • 1
    The problem is the "onclick" attribute value, probably. What do those "CTITULAR" values look like? – Pointy May 13 '19 at 13:22
  • Look at the code which generates the error, not the which generates the code which generates the error. – Quentin May 13 '19 at 13:23
  • Welcome to Stack Overflow! Please take the [tour], have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Post code, error messages, etc. **as text**, not as a *picture* of text. Why: http://meta.stackoverflow.com/q/285551/157247 – T.J. Crowder May 13 '19 at 13:23
  • `echo json_encode($sql);` You really want to JSON encode the SQL query and return it to JavaScript? – Chris White May 13 '19 at 13:23
  • Possible duplicate of [Javascript 0 in beginning of number](https://stackoverflow.com/questions/35047982/javascript-0-in-beginning-of-number) – Nick May 13 '19 at 13:25
  • @treyBake - It's a JavaScript error caused by PHP code outputting invalid JavaScript code. – T.J. Crowder May 13 '19 at 13:26
  • 1
    @T.J.Crowder oh, didn't see that onclick ... another reason inline sucks xD – treyBake May 13 '19 at 13:27
  • 1
    Ok, so as it turns out you have an onclick - it's much better to keep your JS and PHP completely separate. They execute differently and it can lead to unexpected behaviour. Inline JS on it's own also is a bad practice – treyBake May 13 '19 at 13:28

1 Answers1

5

The problem is buried away in one of your screenshots:

enviaAssociado(0516542.00)

That leading 0 combined with the fact that there are no 8 or 9 digits in it (yes, really) makes that a legacy octal integer literal in loose mode. Since it's an integer literal, it can't have a decimal point, so as of the . it's a syntax error.

If that's meant to be a number, have your PHP code strip any leading 0s from the number. If it's meant to be a string, have your PHP code output it in quotes.

If you output data to JavaScript code from PHP, you're usually best off doing so via json_encode. If you're doing it within an attribute (which is not best practice), you also want htmlspecialchars. So:

$botao = '<a type="button" class="btn btn-default" onclick="enviaAssociado('.htmlspecialchars(json_encode($row['CTITULAR'])).') ">Alterar</a>';

Sometimes, the number will contain an 8 or a 9 and so it'll work (that's why the example you gave in a deleted comment on this answer, 0655178.00, worked). This works in loose mode, for instance:

enviaAssociado(0655178.00)

Notice the 8. (A 9 would do the same thing.) It works because the 8 is in the part of the number prior to the ., so the JavaScript parser knows that it's not a legacy octal integer literal, instead it's a (try not to laugh here) non-octal decimal integer literal, which is a specific kind of a decimal integer literal, which means it can be the first part of a decimal literal, so the . isn't a syntax error. This is one of JavaScript's deep dark corners. (And a good reason to use strict mode, which disallows non-octal decimal integer literals.)

But this is just a specific case of where the real problem is not outputting from PHP to JavaScript code correctly (and not properly escaping something being put in an HTML context, specifically in this case an attribute). So although this legacy octal integer literal thing is a deep dark corner of JavaScript, that's not the real issue. The real issue is ensuring you encode things properly when outputting from PHP to JavaScript like that, via json_encode (and in this case, htmlspecialchars).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I tried htmlspecialchars without success this is the only way to fix this without changing the structure? Also thank you at least the problem was found. – MarcoFalcao May 13 '19 at 14:12
  • @MarcoFalcao - `htmlspecialchars` definitely works. You didn't *only* use it, right? See the example in the answer. The `json_encode` part is critical. – T.J. Crowder May 13 '19 at 14:15
  • I changed and this [error](https://i.stack.imgur.com/KnD7w.png) gone but still have the same output error – MarcoFalcao May 13 '19 at 14:20
  • @MarcoFalcao - I don't know what you mean by "the same output error." If you're using the updated code from the answer, you definitely **won't** be outputting `enviaAssociado(0516542.00)` anymore. It will either be `enviaAssociado(516542)` or `enviaAssociado("0516542.00")` depending on what `$row['CTITULAR']` is. Obviously, it'll be important that whatever is output is what your ajax endpoint is expecting to see. – T.J. Crowder May 13 '19 at 14:24
  • U right now it's working totally my mistakes on doing changes miss a ')' ,i'm sorry for wasting your time but very much thank's for this u save my day i was about to get crazy! – MarcoFalcao May 13 '19 at 14:35
  • @MarcoFalcao - No worries! Glad that helped. :-) – T.J. Crowder May 13 '19 at 14:42