0

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.

2 Answers 2

2

If you're returning false to tell the client side : Hey their is an error, i suggest you to change the response status header to 500 and then handle the error in the error section of a jquery/ajax call.

Here an exemple, i hope it'll help you

Server side :

// Set your rules

$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()) {  
  //happy happy time
}
else { 
  //well now i'm sad...

  //Important to turn that off if it's on
  $this->output->enable_profiler(false); 

  //Since you're using CI why not use CI ??
  $this->output->set_status_header('500');
  $this->output->set_content_type('application/json');

  echo json_encode(array(
      'error_msg' => validation_errors(),
  ));
} 

On the client side :

 $.ajax({
    type:    'POST',
    url:     "<?php echo site_url('your url');?>",
    data:    {the post data},
    dataType:'JSON',
    success: function(data) {
       //happy success        

    },
    error: function(data) {
      //sad error
      $("#error-message-selector").html('').append(data.responseJSON.error_msg);
    }
  });
Sign up to request clarification or add additional context in comments.

1 Comment

FANTASTICO!!!!! and thanks for turning me on to the CI way of doing it, so much easier that way!
0

why don't you use the response you get back from the controller ?

if there is an error display the error else display success message

try to always echo json_encode($data); at the end of your controller you can set a flag in $data array in your controller like

$data = array(
// keys
"success" => $success 
)

$success = false in the beginning and then if validation is successful $success = true;

i also think you dont need the header() statements at all

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.