Bom dia. Estou a tentar construir um formulário em que o input é validado por um ficheiro PHP através de uma chamada via AJAX, mas estou a ter problemas na forma como recebo o "data" no callback.
Esta é a minha chamada via AJAX:
$('#submit').click(function(e){
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var msg_subject = $("#msg_subject").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "process_test.php",
dataType: "json",
data: {name:name, email:email, msg_subject:msg_subject},
success : function(data){
if (data.code == "200"){
alert("Success: " +data.msg);
} else {
alert( data);
}
}
});
});
E este o ficheiro PHP onde é efectuada a validação:
<?php
$errors = array();
/* NAME */
if (empty($_POST["name"])) {
$errors["name"] = "The name is required";
} else {
$name = $_POST["name"];
}
/* EMAIL */
if (empty($_POST["email"])) {
$errors["email"]= "The email is required";
} else if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
$errors["email"] = "The email contains invalid characters";
}else {
$email = $_POST["email"];
}
/* MSG SUBJECT */
if (empty($_POST["msg_subject"])) {
$errors["subject"]= "Subject is required";
} else {
$msg_subject = $_POST["msg_subject"];
}
if(empty($errorMSG)){
$msg = "Name: ".$name.", Email: ".$email.", Subject: ".$msg_subject.", Message:".$message;
echo json_encode(['code'=>200, 'msg'=>$msg]);
exit;
}
echo json_encode(['code'=>400, $errors);
?>
O objectivo era usar o método "json_encode" do php para devolver a resposta em formato de objecto pois preciso de acessar as posições para formatar os campos do formulario que tiverem erro, algo como este exemplo:
$obj = {
"name":"Jose",
"email":"something@hotmail.com",
"assunto":"bla bla bla"
}
Contudo, apesar de estar a usar o json_encode, a resposta vai sempre em formato "string". Não consigo perceber o que estou a fazer mal. Agradeço toda a ajuda
EDIT Alterei o código no AJAX para o seguinte:
$.ajax({
type: "POST",
url: "process_test.php",
dataType: "json",
data: {name:name, email:email, msg_subject:msg_subject},
success : function(data){
if (data.code == "200"){
console_log(data.msg.name)
alert("Success: " +data.msg.name);
} else {
console_log(data.err.name)
}
}
});
mas não tenho qualquer output na consola nem qualquer erro. Estou a dar em louco
EDIT Resultado do output com formulario vazio:
ajax.php:99
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
abort: ƒ (a)
always: ƒ ()
complete: ƒ ()
done: ƒ ()
error: ƒ ()
fail: ƒ ()
getAllResponseHeaders: ƒ ()
getResponseHeader: ƒ (a)
overrideMimeType: ƒ (a)
pipe: ƒ ()
progress: ƒ ()
promise: ƒ (a)
readyState: 4
responseText: "<br />↵<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>↵<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined variable: name in C:\wamp64\www\Test\process_test.php on line <i>31</i></th></tr>↵<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>↵<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>↵<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0002</td><td bgcolor='#eeeeec' align='right'>404648</td><td bgcolor='#eeeeec'>{main}( )</td><td title='C:\wamp64\www\Test\process_test.php' bgcolor='#eeeeec'>...\process_test.php<b>:</b>0</td></tr>↵</table></font>↵<br />↵<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>↵<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined variable: email in C:\wamp64\www\Test\process_test.php on line <i>31</i></th></tr>↵<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>↵<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>↵<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0002</td><td bgcolor='#eeeeec' align='right'>404648</td><td bgcolor='#eeeeec'>{main}( )</td><td title='C:\wamp64\www\Test\process_test.php' bgcolor='#eeeeec'>...\process_test.php<b>:</b>0</td></tr>↵</table></font>↵<br />↵<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>↵<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined variable: msg_subject in C:\wamp64\www\Test\process_test.php on line <i>31</i></th></tr>↵<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>↵<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>↵<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0002</td><td bgcolor='#eeeeec' align='right'>404648</td><td bgcolor='#eeeeec'>{main}( )</td><td title='C:\wamp64\www\Test\process_test.php' bgcolor='#eeeeec'>...\process_test.php<b>:</b>0</td></tr>↵</table></font>↵{"code":200,"msg":{"name":null,"email":null,"subject":null}}"
setRequestHeader: ƒ (a,b)
state: ƒ ()
status: 200
statusCode: ƒ (a)
statusText: "OK"
success: ƒ ()
then: ƒ ()
__proto__: Object
$msg
você concatenou os valores. Você deveria fazer umaarray
associativa e o JavaScript iria receber como objeto, como já faz com o restante da resposta. Aliás, o colega @WeesSmith já formulou uma resposta resolvendo isso! ;)