jQuery, Ajax, JSON, PHP and parsererror

12,512

Solution 1

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.)

Solution 2

Your PHP code should probably be:

<?php
    $return = array();
    $return['msg']="Testing, testing.";
    echo json_encode($return);
?>

Solution 3

I just found out what was happening: I've got an .htaccess script for friendly URLs, and it was searching for the right PHP file, but in the wrong directory. I just added a '/' before the filename in the URL and then it worked.

Share:
12,512
Bruno Schweller
Author by

Bruno Schweller

Updated on July 09, 2022

Comments

  • Bruno Schweller
    Bruno Schweller almost 2 years

    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);
    ?>