views:

1195

answers:

3

Hello. 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? Thanks in advance.

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);
?>
+3  A: 

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 arround msg : the key of the array-element you are creating is a string constant, so, enclosed in quotes.
If you don't put these quotes, PHP searches dor a defined constant called "msg", which probably doesn't exist.


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


(Not sure it'll solve your problem -- but it's good to know anyway)

Pascal MARTIN
A: 

Shouldn't your PHP be:

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

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. Thanks for all, guys. Pascal MARTIN, I'm giving you a grade there for your help.

Bruno Schweller
Ergh :-D Nice job : we probably wouldn't have found this one ^^ Thanks for letting us know what caused the problem !
Pascal MARTIN