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);
?>
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.)
Your PHP code should probably be:
<?php
$return = array();
$return['msg']="Testing, testing.";
echo json_encode($return);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With