Skip to content
Advertisement

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.

Advertisement

Answer

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);
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement