Reputation:
i'm trying to validate a form using jquery, ajax and json using codeigniter's validation, this is what I've tried:
this is my controller:
function cadastrar(){
$this->load->library('form_validation');
$this->form_validation->set_rules('nome', 'Nome', 'required|min_length[3]|max_length[15]');
$this->form_validation->set_rules('sobrenome', 'Sobrenome', 'required|min_length[3]|max_length[15]');
$this->form_validation->set_rules('senha', 'Senha', 'required|matches[confirmar]');
$this->form_validation->set_rules('confirmar', 'Confirmação de senha', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if ($this->form_validation->run() == FALSE)
{
echo '{"mensagem": "Erro", "nome_erro": "' . form_error('nome') . '", "sobrenome_erro": "' . form_error('sobrenome') . '", "email_erro" : "' . form_error('email') . '", "senha_erro" : "' . form_error('senha') . '", "confirmar_erro" : "' . form_error('confirmar') . '" }';
}
else
{
echo '{"mensagem": "Registro com sucesso !", "nome_erro": "", "sobrenome_erro": "", "email_erro" : "", "senha_erro" : "", "confirmar_erro" : "" }';
}
}
and this is my jquery function:
$(document).ready(function(){
$('.cadastrar_enviar').click(function(){
var nome = $('.cadastro_nome').val();
var sobrenome = $('.cadastro_sobrenome').val();
var email = $('.cadastro_email').val();
var senha = $('.cadastro_senha').val();
var confirmar = $('.cadastro_confirmar').val();
var mensagem = "";
$("#loading").show();
$.post('../index.php/usuario/cadastrar', {
"nome" : nome,
"sobrenome" : sobrenome,
"email" : email,
"senha" : senha,
"confirmar" : confirmar
}, function(data){
$('#loading').hide(500);
$('span#nome_erro').html(data.nome_erro);
$('span#sobrenome_erro').html(data.sobrenome_erro);
$('span#email_erro').html(data.email_erro);
$('span#senha_erro').html(data.senha_erro);
$('span#confirmar_erro').html(data.confirmar_erro);
alert(data.confirmar_erro);
$('#mensagem_oi').html(data.mensagem).show(500);
}, "json");
});
});
and I get nothing on errors, form_error() isn't returning anything, can anyone give me a hint? thanks
Upvotes: 0
Views: 2833
Reputation: 629
jquery is expecting the controller to return a json page, but the controller is responding with an ordinary html page. You should specify the output format in the header, in Codeigniter the code looks something like:
$this->output
->set_content_type('application/json')
->set_output(json_encode(array("mensagem"=> "Registro com sucesso !", "nome_erro"=> "", "sobrenome_erro"=> "", "email_erro" =< "", "senha_erro" => "", "confirmar_erro" => "")));
Look at output class: http://codeigniter.com/user_guide/libraries/output.html
This way you should see something, but I don't know if the validation will work.
Upvotes: 1
Reputation: 564
CI validation triggers on form submit.
Try to submit form.
$('.cadastrar_enviar').submit(function(){
});
Upvotes: 0