简体   繁体   中英

AJAX response is not returning in codeigniter

I am new in codeigniter. I am writing a code. AJAX response is not returning.

Here is my controller:

public function getValue()
    {
        $this->load->helper('url');

        $data = array(
        'username' => $this->input->post('username'),
        'email'=>$this->input->post('email'),
        'address'=>$this->input->post('address')
        );
        echo json_encode($data);
        die;
    }

and it is view code:

$( document ).ready(function() {
    $('#btn_submit').on("click", function(event){
        event.preventDefault();
        var username = $('#username').val();
        var email = $('#email').val();
        var address = $('#address').val();

        $.ajax({
            type: "POST",
            url: "<?php echo base_url(); ?>" + "index.php/MyApp/getValue",
            dataType: 'json',
            async:true,
            crossDomain:true,
            data: {username: username, email: email, address: address},

            success: function ( data) {
                        console.log(data);
                    },
                    error: function ( data ) {
                        console.log('error');
                    }

        });

    });

});

I am new with codeigniter, so I don't know how to return response and work with AJAX. I have coded with the help of web but still getting errors. Please guide me how to fix this. Thanks

Simple answer remove die; from the getValue() function.

Codeigniter does not actually output anything until after the controller finishes execution. The call to die; short circuits the normal operation of the framework and so nothing gets output. In other words, echo json_encode($data); never actually happens.

Please try after setting content-type for the response like below.

header('Content-Type: application/json');
echo json_encode($data);
die;

Ajax response expects json data since your code set dataType: 'json'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM