I'm currently attempting to use JQuery/Ajax to call a PHP (CodeIgniter) function and returning either an array or a bool using JSON and I need a little (or maybe a lot of) help.
I have a basic email form (name/email/message) in a JQuery dialog...
function emailForm() {
$('#emailDialog').dialog({
autoOpen: false,
height: 450,
width: 300,
position: ['center-top'],
show: 'fade',
title: 'Contact Us',
modal: true,
buttons: {
Send: function () {
sendEmail();
},
Reset: function() {
clearForm('email');
}
}
});
$('#emailDialog').dialog('open');
}
This uses Ajax to submit to a CodeIgniter controller that uses form_validation and either returns the PHP/CI errors in an array (with JSON) or sends the mail and returns a bool based upon it's success...
class Email extends CI_Controller {
function index() {
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('message', 'Message', 'required');
if ($this->form_validation->run() == false) {
$data = array(
'name' => form_error('name'),
'email' => form_error('email'),
'message' => form_error('message')
);
header('Content-Type: application/x-json; charset=utf-8');
echo json_encode($data);
return false;
} else {
$this->load->library('email');
$this->email->set_newline("\r\n");
$name = $this->input->post('name');
$email = $this->input->post('email');
$message = $this->input->post('message');
$this->email->from($email, '...');
$this->email->to('...');
$this->email->subject('...');
$this->email->message($message);
if ($this->email->send() == false) {
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode(false));
} else {
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode(true));
}
}
}
}
I want Ajax to parse the return and behave accordingly based on the following code however, when I submit a blank form (which should result in errors), the user agent always evaluates to the else clause (indicating the mail was sent successfully) rather than the initial if clause (parsing the JSON array and rendering the HTML). I have tried several different configurations of the if/else if/else to no avail. Also, when debugging, the Post is actually showing blank values for each of the parameters, and the Response AND JSON show what I feel to be correct data...
POST:
email
message
name
RESPONSE:
{"name":"The Name field is required.","email":"The Email field is required.","message":"The Message field is required."}
JSON:
name "The Name field is required."
email "The Email field is required."
message "The Message field is required."
I can't seem to determine why my Ajax return is always evaluating to true, so any help will be greatly appreciated. Thank you in advance!
Please don't downvote me too harshly, I'm pretty new to SO