1
Hello everyone and I thank you
Have the form validation class where you take all form errors:
// Validação final do cadastro
public function validateFinalCadastro($arrVar) {
if(count($this->getErro())>0){
$arrResponse=[
"retorno"=>"erro",
"erros"=>$this->getErro()
];
}else{
$arrResponse=[
"retorno"=>"success",
"erros"=>null
];
}
return json_encode($arrResponse, JSON_UNESCAPED_UNICODE);
}
Here I have the Controller that switches to view:
public function teste() {
//echo 'esse é um teste';
$this->recVariaveis();
$validate = new ClassValidate();
$validate->validateFields($_POST);
$validate->validateEmail($this->Email);
$validate->validateIssetEmail($this->Email);
$validate->validateData($this->DataNascimento);
$validate->validateCpf($this->Cpf);
$validate->validateConfSenha($this->Senha,$this->SenhaConf);
$validate->validateStrongSenha($this->Senha);
$validate->validateCaptcha($this->gRecaptchaResponse);
$validate->validateFinalCadastro($this->arrVar);
}
If I echo, print or vardump $validate->validateFinalCadastro($this->arrVar); I can pass it to the view and present the error ...it displays after closing the html of the page...
{"return":"error","errors":["Email already registered!" "Use a stronger password!" "Security system has been activated! Refresh the page and try again or wait a little longer."]}
Here is the ajax without datatype: 'json'
No datatype: 'json' I enter the Success rest more caio on Else, because the Response.return is without the datatype: 'json'.
$('#Formcadastroclientes'). on('Submit', Function(Event){ Event.preventDefault(); var data=$(this). serialize(); console.log(data);
$.ajax({
url: getRoot()+'CadastroClientes/teste',
type: 'post',
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
data: dados,
success: function (response) {
$('.retornoCad').empty();
if(response.retorno == 'erro'){
getCaptcha();
$.each(response.erros,function(key,value){
$('.retornoCad').append(value+'');
});
}else{
$('.retornoCad').append('Dados inseridos com sucesso!');
}
},
error: function (response, jqXHR, request, status, errorThrown, erro) {
console.log(response);
//alert(dados);
console.log(dados);
//alert(jqXHR);
console.log(jqXHR);
//alert(request);
console.log(request);
//alert(status);
console.log(status);
//alert(errorThrown);
console.log(errorThrown);
//alert(erro);
console.log(erro);
},
complete: function (jqXHR, textStatus) {
//colocar aqui algo que deseja que faça ao terminar todo o processo (finnaly)
}
});
Ajax with datatype: 'json' cannot enter Success it already falls into error
$('#FormCadastroClientes').on('submit', function(event){
event.preventDefault();
var dados=$(this).serialize();
console.log(dados);
$.ajax({
url: getRoot()+'CadastroClientes/teste',
type: 'post',
dataType: 'json',
data: dados,
success: function (response) {
$('.retornoCad').empty();
if(response.retorno == 'erro'){
getCaptcha();
$.each(response.erros,function(key,value){
$('.retornoCad').append(value+'');
});
}else{
$('.retornoCad').append('Dados inseridos com sucesso!');
}
},
error: function (response, jqXHR, request, status, errorThrown, erro) {
console.log(response);
//alert(dados);
console.log(dados);
//alert(jqXHR);
console.log(jqXHR);
//alert(request);
console.log(request);
//alert(status);
console.log(status);
//alert(errorThrown);
console.log(errorThrown);
//alert(erro);
console.log(erro);
},
complete: function (jqXHR, textStatus) {
//colocar aqui algo que deseja que faça ao terminar todo o processo (finnaly)
}
});
Comments: - I can put everything in the bank okay. - I can display rertun json_encode directly in the view - I can enter the ajax Success without using datatype: json I do not enter if to read the array but enter Else.
I get these errors in the console.log
In Response I would have to receive the json_encode Return and I don’t get it. What I get is the view html.
ajax is expecting a json return and not the html of the page.
parsererror Syntaxerror: "JSON.parse: Unexpected Character at line 1 column 1 of the JSON data"
Thank you all..... sponcipently
Just to be sure, the
dataType
defined in AJAX refers to the body format of the requisition not of the answer– Costamilam
What is the return of Ajax?
– Sam
Hello William, when I give Ubmit in the form I take the data with serialize and add in var = data ok... url: getRoot()+'Customer registration/test', is where I send to the controller, type: 'post', is the method I send to controller, dataType: 'json', is the return of the controller if it does not pass some validation, date: data is the data that sent to the controller to insert in the database... .. json does not receive errors from the controller
– jonas
Sam the responsta is here...
– jonas
readyState: 4 --------------- b is here instead of receiving the json Return I get the html from theview------------------- responseText: "<! doctype html> n n n n<html lang="en">..." ----------------------------- setRequestHeader: Function setRequestHeader() state: Function state() status: 200 statusCode: Function statusCode() statusText: "OK" then: Function(then) <prototype>: Object { ... }
– jonas
parsererror Syntaxerror: "JSON.parse: Unexpected Character at line 1 column 1 of the JSON data"
– jonas
That’s the problem. Ajax should call a return page only the JSON, and not a common page with HTML and everything.
– Sam
Sam what recommends... create a view with nothing, um...I use the layout with the tags goals/header/html ...I do not know...
– jonas
Um. gave fatalcrash in my memory.... rsrrs
– jonas
You will create a file only with the code that returns the JSON and call this file in Ajax.
– Sam
I’ll do it here and I’ll be right back
– jonas
Sam.... I got it just like you said. inside my controller had a Construct that renders it all layout and so it brought the html from the page first, deletes the Construct from the layout and worked... thanks for the help I’ll improve my shop hugs....
– jonas
That’s right. It’s because Ajax returns everything on the page. It’s like you’re opening the page directly. What you have in the source code is what Ajax returns.
– Sam
Thank you ........ :)
– jonas