Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, Ajax, JSON, PHP and parsererror

I'm trying to send a form to a PHP using $.ajax in jQuery. I send the whole thing as JSON, but, when I try to get the response, I get the 'parsererror'. What am I doing wrong?

jQuery fragment:

$("form").submit(function(){
    $.ajax({type: "POST",
        url: "inscrever_curso.php",
        data: {cpf : $("input#cpf").val(),nome : $("input#nome").val()},
        dataType: "json",
        success: function(data){
            alert("sucesso: "+data.msg);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            alert ("erro: "+textStatus);
        }
    });
    return false;
});

PHP:

<?php
    $return[msg]="Testing, testing.";
    echo json_encode($return);
?>
like image 921
Bruno Schweller Avatar asked Dec 29 '22 17:12

Bruno Schweller


2 Answers

I don't know if it's the cause of your problem, but here is one thing about your PHP code:

$return[msg]="Testing, testing.";
echo json_encode($return);

Doing this, with E_NOTICE error_reporting level, you get:

Notice: Use of undefined constant msg - assumed 'msg'

If notices are enabled and displayed on your server, is will cause an output that is not valid JSON (the ouput contains the error message before the JSON string).


To avoid that notice, you must use this syntax:

$return['msg']="Testing, testing.";
echo json_encode($return);

Note the quotes around msg: the key of the array-element you are creating is a string constant, so, it is enclosed in quotes.

If you don't put in these quotes, PHP searches for a defined constant called "msg", which probably doesn't exist.

For more information about this, you can take a look at this section of the manual: Why is $foo[bar] wrong?.

(I am not sure it'll solve your problem, but it's good to know anyway.)

like image 160
Pascal MARTIN Avatar answered Jan 09 '23 12:01

Pascal MARTIN


Your PHP code should probably be:

<?php
    $return = array();
    $return['msg']="Testing, testing.";
    echo json_encode($return);
?>
like image 25
pixeline Avatar answered Jan 09 '23 11:01

pixeline