PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, March 14, 2022

[FIXED] JSON between JQuery/AJAX and PHP w/ CodeIgniter

 March 14, 2022     ajax, codeigniter, jquery, json, php     No comments   

Issue

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.


Solution

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);
    }
  });


Answered By - Gabtheviking
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing