4

I'm trying to send a form build with CodeIgniter via AJAX and trying to get the response with JSON. However, I only see the respond when I open my developer tab (I'm not even sure, if that's actually a respond since it's showing both of the json data's).

All it shows, is the loading spinner, and after that it vanishes.

Code have been tested without AJAX and it works, so there can't be errors in PHP.

Here's my controller for resetting the password:

<?php

Class Users extends CI_Controller {

    public function forgot_pass()
    {

    if(!$this->input->post('to_email'))
    {
    exit("No data");
    }


    $this->load->model('user');
    $email = $this->input->post('to_email');
    $email_addr = $this->user->get_email_address($email);


    if(empty($email_addr))
    {
    echo json_encode(array('pls'=>0, 'msg' => "E-mail address was not found. Try  again"));
    }

    $this->load->helper('string');
    $new_password = random_string('alnum', 8);
    $this->load->library('phpass'); 

    $update_password = array( 'password' => $this->phpass->hash($new_password));
    $update_password = $this->user->update_password($email, $update_password);

    $this->load->library('email');

    $config['newline'] = '\r\n';
    $this->email->initialize($config);

    $this->email->from('[email protected]', 'Your Name');
    $this->email->to($email);  
    $this->email->subject('New password');
    $this->email->message("Hey, " .$email_addr['name']. ". Your new password is: " .$new_password); 

    if($this->email->send())
    {
    echo json_encode(array('pls'=>1, 'msg' => "Password has been sent to given e-mail address"));
    }


}

}
?>

And here's my AJAX call written with jQuery:

$(document).ready(function() {

$("form#forget_pass_form").on('submit', function(e){

            e.preventDefault();

                $("#loading_spinner").show();
                var from = $(this);

                $.ajax({

                    url: from.attr('action'),
                    type: from.attr('method'),
                    data: $(from).serialize(),
                    }).done(function(data) {



                    if(data.pls == 0) {

                        $("#forgot-pass-success").hide();
                        $("#forgot-pass-error").show();
                        $("#forgot-pass-error").fadeIn(1000).html(data.msg);

                      }

                    if(data.pls == 1) {

                        $("#forgot-pass-error").hide();
                        $("#forgot-pass-success").show();
                        $("#forgot-pass-success").fadeIn(1000).html(data.msg);
                      }

                   $("#loading_spinner").hide(); 

                });

            return false;

        });
});
1
  • in $.ajax dataType is missing please add dataType: 'JSON' in $.ajax call; also use use die or exit to stop the execution of the script Commented Apr 17, 2014 at 4:15

3 Answers 3

10

Firstly, can you try setting the correct header in the Controller?

header('Content-Type', 'application/json');

Or better yet:

$this->output->set_content_type('application/json');

As a side note, you should make sure you are always returning JSON data, so I would remove the exit() message and put a default JSON response at the bottom of the method.

Don't forget, when you echo your JSON, you can put return; afterwards to stop any more code running afterwards in that method.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, that did the trick.. I figured it out like a minute ago. Thanks anyway. I'll mark this as a accepted answer :)
2

Most of your code is ok. But you need to change some lines, both in your js, and controller.

Change 1(In Ajax function)

Change your ajax function and add dataType: "json" option

    $.ajax({
           url: from.attr('action'),
           type: from.attr('method'),
           dataType: "json",
           data: $(from).serialize(),
          }).done(function(data) {

           ....

        });

Change 2 (In controller)

exit("No data");

to

exit(json_encode(array('pls'=>0, 'msg' => "No data")));

Change 3 (In controller)

echo json_encode(array('pls'=>0, 'msg' => "E-mail address was not found. Try again"));

to

exit(json_encode(array('pls'=>0, 'msg' => "E-mail address was not found. Try again")));

explanation

  1. First change tell your script to handle the response data as Json
  2. Second change is to keep all your return type same, if not when you sending only the no data response you are not handling this option from youe js.
  3. And the last change make sure you stop further processing when sending email fails, and stop from showing both json.

Comments

1

I would like to suggest you about json return. First in your ajax you have to use dataType: 'json'

$.ajax ({
        url: from.attr('action'),
        type: from.attr('method'),
        data: $(from).serialize(),
        dataType: 'json',
    }).done(function(data) {

           ..your code..

    });

CodeIgniter have output class, why don't you use output class to respond to ajax from CI.

$output = array('pls' => 1,
                'msg' => "Password has been sent to given e-mail address"
          );
$this->output->set_content_type('application/json')
             ->set_output(json_encode($output));

Use output class, this is more efficient then echo

I hope it will helps you for better code style.

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.