Ajax returns 0 , (No internet Connection) , even with Internet Access

Viewed 218

J-query Ajax call returns 0 in error function. Usually 0 error is returned when there is no internet connection. Even though my Internet connection is perfectly fine. The problem is it works fine on friend's machine. And on friend's machine, if I turn wifi off, after loading page , as it should work it do return no internet connection on his machine.

$(document).ready(function(){
$("#forget_form").submit(function(event){
    event.preventDefault(); 
        $('#result').html('Processing...');
        $.ajax({
            url: '<?php echo base_url(); ?>Index/forget',
            type:'POST',
            data: {
                email: $("#email").val(),

            },
            success:function(data){
                        $('#result').html(data)     
            },
            error: function (jqXHR, exception) {
                        var msg = '';
                        if (jqXHR.status === 0) {
                            msg = 'There is no Internet connection.';
                        } else if (jqXHR.status == 404) {
                            msg = 'Requested page not found. [404]';
                        } else if (jqXHR.status == 500) {
                            msg = 'Internal Server Error Occured. [500].';
                        } else if (exception === 'parsererror') {
                            msg = 'Requested JSON parse failed.';
                        } else if (exception === 'timeout') {
                            msg = 'Request Time out reached.';
                        } else if (exception === 'abort') {
                            msg = 'Ajax request aborted.';
                        } else {
                            msg = 'Uncaught Error.\n' + jqXHR.responseText;
                        }
                        $('#result').html(msg);
            },
        });
});});
3 Answers

Issue can be there due to one of the following reasons.

1: Request is going through System Wide proxy which blocks it.

2: CORS issue (You might be trying to access www version of your website from non www version), remember browsers treat www.example.com and example.com as two different websites. When you buy domain names , usually you get both, what you should do is only use either www or non www version.

Jquery can return error 0, if you are on on non www version of you website and try to access www version of your website. For example you try to get www.example.com, while being on example.com's server.

As QBR SOFT has mentioned, because of CORS (Cross origin request sharing) policy, your connections can be blocked by browsers if you host your content on non www and make requests with www version and vice versa. Also if you have internet connection make sure, you dont have set a system wide proxy in internet Proxy settings.

Related