geeth
geeth

Reputation: 714

AJAX response returns html content

I have an AJAX call in my codeigniter project. Here is my code:

in view :

$('#forgotPassword').click(function() {
        var base_url = '<?php echo base_url()?>'; 
        $('#forgotPasswordEmailError').text('');
        var email = $('#forgotPasswordEmail').val(); 
        console.log(email);
        if(email == ''){
            $('#forgotPasswordEmailError').text('Email is required');
        }else{
            $.ajax({
                url : base_url + 'Home/forgotPassword',
                type : 'POST',
                data : {email : email},
                success: function(data) {       
                    console.log(data);                  
                    //location.reload();
                }
            });
        }

    });

and controller :

public function forgotPassword() { 
   $email = $this->input->post('email');
   echo $email; 
}

but the response contains only the html content from my view. I couldn't identify what is happening.

Upvotes: 0

Views: 15291

Answers (3)

Wesley Montaigne
Wesley Montaigne

Reputation: 1

hi maybe i can help someone, i had the same problem, in my case the error was here "url : base_url + 'Home/forgotPassword'"

in this example i have to pass all way like this url : /anotherdirectory/Home/forgotPassword.php', take a look in your "url"

$.ajax({ url : "change here fo works"', type : 'POST', data : {email : email}, dataType:'json', success: function(data) {
console.log(data);
//location.reload(); }

Upvotes: 0

Naim Malek
Naim Malek

Reputation: 1184

change your jquery code to

$('#forgotPassword').click(function() {
    var base_url = '<?php echo base_url()?>'; 
    $('#forgotPasswordEmailError').text('');
    var email = $('#forgotPasswordEmail').val(); 
    console.log(email);
    if(email == ''){
        $('#forgotPasswordEmailError').text('Email is required');
    }else{
        $.ajax({
            url : base_url + 'Home/forgotPassword',
            type : 'POST',
            data : {email : email},
            dataType:'json',
            success: function(data) {       
                console.log(data);                  
                //location.reload();
            }
        });
    }

});

change your controller code like

public function forgotPassword() { 
   $email = $this->input->post('email');
   $response = ["email" => $email];
   echo json_encode($response);
}

Upvotes: 4

Kinshuk Lahiri
Kinshuk Lahiri

Reputation: 1500

Instead of

echo $email;

use:

$response = ["email" => $email];

return json_encode($response);

And parse JSON, on client side, using JSON.parse.

Upvotes: 0

Related Questions