8

I've got some simple JS/jQuery code to make an AJAX call to grab some HTML and shove it into a div on my page. This works fine in Firefox but fails in Chrome.

In the Chrome console I can see the AJAX request shown with a status text of "(failed)" and type "pending".

All the searching I've done has searched is relating to cross-domain issues. This doesn't fit here, I'm running this on a webserver, with a domain name, without a port number appended.

Here's my code sample (you can see I was initially trying to use .load(), same problem):

$('#brochure2012navigation a').click(function(event)
{
    event.preventDefault();

    //$('#brochurePage').load($(this).attr('href'));

    $.ajax({
        url: $(this).attr('href'),
        dataType: 'html',
        success: function(html) {
            $('#brochurePage').html(html);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr);
            console.log(thrownError);
        },
    });
});

In Chrome's console the logged xhr object looks like this:

Object {readyState: 0, setRequestHeader: function, getAllResponseHeaders: function, getResponseHeader: function, overrideMimeType: function…}
abort: function (a){a=a||"abort",p&&p.abort(a),w(0,a);return this}
always: function (){i.done.apply(i,arguments).fail.apply(i,arguments);return this}
complete: function (){if(c){var a=c.length;n(arguments),j?l=c.length:e&&e!==!0&&(k=a,o(e[0],e[1]))}return this}
done: function (){if(c){var a=c.length;n(arguments),j?l=c.length:e&&e!==!0&&(k=a,o(e[0],e[1]))}return this}
error: function (){if(c){var a=c.length;n(arguments),j?l=c.length:e&&e!==!0&&(k=a,o(e[0],e[1]))}return this}
fail: function (){if(c){var a=c.length;n(arguments),j?l=c.length:e&&e!==!0&&(k=a,o(e[0],e[1]))}return this}
getAllResponseHeaders: function (){return s===2?n:null}
getResponseHeader: function (a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c}
isRejected: function (){return!!i}
isResolved: function (){return!!i}
overrideMimeType: function (a){s||(d.mimeType=a);return this}
pipe: function (a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()}
progress: function (){if(c){var a=c.length;n(arguments),j?l=c.length:e&&e!==!0&&(k=a,o(e[0],e[1]))}return this}
promise: function (a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}
readyState: 0
responseText: ""
setRequestHeader: function (a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this}
state: function (){return e}
status: 0
statusCode: function (a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this}
statusText: "error"
success: function (){if(c){var a=c.length;n(arguments),j?l=c.length:e&&e!==!0&&(k=a,o(e[0],e[1]))}return this}
then: function (a,b,c){i.done(a).fail(b).progress(c);return this}
__proto__: Object

Apologies that this looks a bit messy, but I think the important thing is the status of 0.

Monitoring the logs, the request isn't hitting my server.

I'm really stumped here, I'd appreciate any help!

Cheers, Al

Al Bennett
  • 428
  • 1
  • 5
  • 13
  • What version of Chrome are you using? – Joe Jan 22 '13 at 18:45
  • 3
    Does `$(this).attr('href')` give you a valid url? does going to that page directly work? what are you getting in the network tab for that ajax request? (ctrl+shift+j in Chrome) – Kevin B Jan 22 '13 at 18:51
  • 1
    did you test with a static url (instead of $(this).href) ? – mikakun Jan 22 '13 at 18:56
  • Thanks for the input guys. In answer to the questions: - Chrome 24.0.1312.52 and a Windows version of Chrome (also recent) - $(this).attr('href') does work, and I have verified the page loads correctly - I've tried hard coding a static URL, no joy there – Al Bennett Jan 23 '13 at 01:00
  • Is there any .htaccess rules in place (rewrites)? I would like to see a screengrab from Network tab of this particular request – Moseleyi Jan 25 '13 at 12:40
  • 2
    can you provide a working code sample? Either JS-fiddle or better live on your server. – Zim84 Jan 25 '13 at 12:41
  • at least show us the content of tnk link with id "brochure2012navigation". – regilero Jan 25 '13 at 12:42
  • Have you tried hardcoding a completely different URL like www.google.com? – ED-209 Jan 25 '13 at 17:08
  • 1
    Keep in mind that a subdomain is another origin. – Sindre Sorhus Jan 28 '13 at 10:12
  • If the request isn't hitting your server *at all*, that's very suspicious. Even in the case of a blocked cross-domain request, the request should hit your sever. That either means that a cross-domain preflight OPTIONS request is hitting your server instead, or maybe you have a browser cache problem. (Have you tried clearing your cache?) – apsillers Jan 29 '13 at 21:19
  • Are you accessing the HTML page from a `file://` URL? If so, see: http://stackoverflow.com/questions/3595515/xmlhttprequest-error-origin-null-is-not-allowed-by-access-control-allow-origin – apsillers Jan 30 '13 at 03:19
  • The key to this question is page url, and the `href` attribute of a clicked link... Please, show them to help us solve your problem... – Olegas Jan 31 '13 at 21:12

9 Answers9

5

It is possible that the ajax call gets blocked by the AdBlock Chrome addon.

Some URLs might get blocked, based on the keys on the adblock blacklist. On DevTools Network tab, such requests are marked as 'failed', in status 'pending'

ToC
  • 311
  • 2
  • 4
1

You code seems perfect but some typos seen in your code, i added some of the other elems

 $('#brochure2012navigation a').click(function(event){
    event.preventDefault();
    $.ajax({
       url: $(this).attr('href'),
       dataType: 'html',
       async:false, // <------------------try with adding this
       type:'post', // <------------------try adding this too
       success: function(data) {
         $('#brochurePage').html(data);
       },
       error: function (xhr, ajaxOptions, thrownError) {
         console.log(xhr);
         console.log(thrownError);
       } // <----------------------comma found here
    });
});

or you might be get interest in this:

 $('#brochure2012navigation a').click(function(event){
    event.preventDefault();
    $.ajax({
       url: $(this).attr('href'), 
       type:'POST',
       success: function(response, status, xhr){ 
             var ct = xhr.getResponseHeader("content-type") || "";
             if (ct.indexOf("html") > -1) {
                $('#brochurePage').html(data);
             }
             if (ct.indexOf("json") > -1) {
                // handle json here
             }  
       },
       error: function (xhr, ajaxOptions, thrownError) {
         console.log(xhr);
         console.log(thrownError);
       }
    });
  });
Jai
  • 74,255
  • 12
  • 74
  • 103
0

I made a small change to your code:

var url = $(this).attr('href');
$.ajax({
    url: url,
....

After that I set your code to work on a jsfiddle:

http://jsfiddle.net/kyz69/1/

I'm getting the content of /_display/ ( http://fiddle.jsshell.net/_display ) I'm linking to that because you didn't provide the url you're trying to load and that was the only page I could find that would return data because it's not cross domain.

I tested the code on Windows + Google Chrome Version 24.0.1312.52 m

Can you test the fiddle and post here the outcome?

Ferry Kobus
  • 2,009
  • 2
  • 14
  • 18
  • Putting the URL into a variable is no different. – epascarello Jan 31 '13 at 03:11
  • I know, but I want the one who askes the question to test the fiddle. If it works on his pc, it's a problem with probably cross-domain scripting / or his code. I want to pinpoint the problem.. – Ferry Kobus Jan 31 '13 at 08:32
0

could it be the trailing comma after the error function's closing brace? Usually you only would put a comma if there are additional objects...

rnirnber
  • 607
  • 7
  • 17
0

I wish I have enough reputation to post a comment to ask for more details, but I don't. So I'll give my best guess by experience.

If it was a cross domain issue, Chrome would have logged an error message in the console in red. Test in this Fiddle.

One way I know that could help is to user a sniffer. Luckily Chrome have a simple one built in the Chrome Developer Tool, by pressing Ctrl + Shift + I, I guess you probably know this as you have copied the console output, but this time go to the Network tab, make sure it stays open when you click on the link that triggers this click event handler.

You'll see a new record shown in the table, click on its name, and you can take a look at the request and respond headers, or even rendered responds. Hopefully this will give you more helpful information as I usually get mine here.

Justin Lau
  • 360
  • 3
  • 10
0

Why you don't try this

$('#brochurePage').load($(this).attr('href'),function(){
alert('Load was performed.');
});

Good Luck!

0

Last attribute of ajax or json doesn't end with comma , no doubt it was failing in chrome & IE but why run good in firefox, I am stumped :), try this:

    $('#brochure2012navigation a').click(function(event)
{
    event.preventDefault();

    //$('#brochurePage').load($(this).attr('href'));

    $.ajax({
        url: $(this).attr('href'),
        dataType: 'html',
        success: function(html) {
            $('#brochurePage').html(html);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr);
            console.log(thrownError);
        }
    });
});
Pranav Singh
  • 17,079
  • 30
  • 77
  • 104
0

Most browsers don't actually return any kind of interesting error if it is a cross-domain scripting issue. Any one I've used returns a StatusText of "error" and a readyState of 0, as you have shown. You may be thinking there is no crossdomain action happening because you are actually calling something from the same domain, maybe a different subdomain or a different port (https/non-https). It is possible you have an out-of-date version of Firefox that doesn't compensate for cross-domain restrictions. You can verify in your Chrome by looking in the Net request as past posters have suggested, and looking for the property: "Origin: null"

If indeed it turns out to be a cross-domain issue (I think it is), you will need to add the following line of PHP (or a similar header in the backend language of your choice) to the top of the file you are requesting, prior to any HTML code.

<?php header("Access-Control-Allow-Origin: example.com"); ?>

If you use jquery, you may also need:

<?php header("Access-Control-Allow-Headers: x-requested-with"); ?>
johnrom
  • 522
  • 2
  • 11
0

If your server isn't getting any request then problem must lie within the URL that you are using.

Are you typing the protocol and full URL or just partial?

What happens if you hard code a link and use it? (like follows)

$('#brochure2012navigation a').click(function(event)
{
    event.preventDefault();

    //$('#brochurePage').load($(this).attr('href'));

    $.ajax({
        url: $(this).attr('http://www.google.com'),
        dataType: 'html',
        success: function(html) {
            $('#brochurePage').html(html);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr);
            console.log(thrownError);
        },
    });
});

If i were you i would make sure that the $.ajax is really hitting its target by hardcoding a known target first.

If the hardcoded target isn't getting any request the problem lies somewhere else.

Morv
  • 355
  • 2
  • 9
  • The problem was indeed with the URL. After trying out many of the suggestions here (and much more faffing about), I found that the problem was with the URLs I was using. The exact same code worked fine with other pages on the site. My solution was to use Apache rewrites to redirect the pages I AJAXing to be /ajax/{pagename}. After doing that everything works fine. Utterly strange, I haven't had time to investigate what this is, my bodge works, but I'll try and figure it out for my own sanity. – Al Bennett Feb 02 '13 at 23:21
  • I have the same problem. Even if I change the url to http://google.com it fails exactly like yours. This is day 2 on this issue and I cannot get it to work. – Harry May 03 '13 at 14:35