AJAX "Error: callback was not called" appears randomly - javascript

I'm pretty new to ajax and I faced issue, that is not solvable by any of available stackoverflow's threads. I've got array with streams names and I use ajax to get detailed info about them by using Twitch API. For some of those requests I get following error:
Error: callback was not called
at Function.error (VM11084 jquery.min.js:2)
at b.converters.script json (VM11084 jquery.min.js:4)
at Nb (VM11084 jquery.min.js:4)
at A (VM11084 jquery.min.js:4)
at HTMLScriptElement.c (VM11084 jquery.min.js:4)
at HTMLScriptElement.dispatch (VM11084 jquery.min.js:3)
at HTMLScriptElement.q.handle (VM11084 jquery.min.js:3)
I found it peculiar that generated url (check url variable in code below) is ok and when I paste it in chrome's search bar, it leads to proper result. The most confusing part is that it works properly for 4 strings in streamsNames array and for others it does return this error code. I googled a lot however I cannot find proper solution or just explanation of this behaviour.
Here's the relevant part of the code:
function updateStreamInfo() {
streamsNames.forEach(function getStreamsCurrentData(streamName) {
var url = 'https://wind-bow.glitch.me/twitch-api/streams/' + streamName;
console.log(url);
$.ajax({
url: url,
dataType: 'JSONP',
jsonpCallback: 'callback',
type: 'GET',
success: function (data) {
console.log(data);
var stream;
if(data.stream === null) stream = new Stream(streamName, "", "");
else stream = new Stream(streamName, data.stream.game, data.stream.channel.logo);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError);
}
})
})}
And one more thing: this whole things runs in codepen.io but I do not know if that has any influence on anything in this case.
Any ideas what might be the issue?

Related

POST (url) net::ERR_BLOCKED_BY_CLIENT

I am getting the below below when i try to the url
https://www.cshippers.com/orderManagement/OrderManagementReportAction.action?actionCommand=submit&menuRef=REP_APP005_0001MT
The error:
POST (url) net::ERR_BLOCKED_BY_CLIENT
The JavaScript Function:
$.ajax({
url:targetUrl, //supposed to be the url as mentioned in question
data: formData.serialize(),
cache: false,
type: 'POST',
success: function (dataofconfirm) {
openPage( url.substring(0, url.indexOf(".",2)) + ".action?menuRef="+menuRef );
/*hideLoader();*/
},
error: function (xhr, ajaxOptions, thrownError) {
hideLoader();
console.log( thrownError );
}
});
Usually, there are two problems:
Related to adblocker and you need to turn it off
You need to add an extra segment at the end of your URL
For example "https://--your api--/movie.json". You need to add the target node in your database, here it is movie, at the end of the URL.
Firebase needs this .json at the end of the URL you are sending requests to, otherwise your request will fail.
If you are using Firebase, it could solve your problem.
You can test your API with one of the online open API testing.

Ajax request works on local server but not online

I have built my first website and it works on local server but not online. The problem is loading a json file with Ajax. In the published version I get the error message that my object is undefined.
This is a (simplified) version of my code that shows the problem:
$.ajax({
url: "json/torp.json",
contentType: "application/json",
success: function (data) {
torp = data;
console.log('great success!');
console.log(torp.items[3]);
},
error: function (/* request, error */) {
console.log('Network error has occurred please try again!');
}
This is the message in the console when running on local server:
great success! main.js:37:13
Object { id: "brunskar", title: "<h2>Brunskär</h2>", image: "img/countryside.jpg" }
But when I publish online this is what I get:
great success! main.js:37:13
TypeError: torp.items is undefined
In the Utilities Net section I get status code 200 and the whole content of the JSON file is readable under the "reply" tab, so it seems like the file is loaded. But I don't understand why my object is undefined.
Sounds like an asynchronous issue (your page is loading before your ajax call can return the data, therefor it is returned as undefined) one way to solve this is to put a function inside your ajax call that fires your page functions that use the data being returned by the call.
$.ajax({
url: "json/torp.json",
contentType: "application/json",
success: function (data) {
torp = data;
console.log('great success!');
console.log(torp.items[3]);
function usePageData (); <----calls webpage function utilizing
data
},
error: function (/* request, error */) {
console.log('Network error has occurred please try again!');
}
Hope that helps!
Problem solved by changing
contentType: "application/json"
to
dataType: "json"!
I used the tip from Patrick Evans in one of the comments. Thank you for the help!

Jquery ajax Delete not working in IE

this is the below code which i am using for delete functionality.At Server side there is RestAPICall. But i can see the request is not at all going to back-end and neither i am getting any error in IE.It's working in FF,Chrome but not in IE9.
var delURL = "url call to restful webservices";
$.ajax({
type: "DELETE",
url:delURL,
contentType: "application/json",
data: sendUserData(),
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (data) {
console.log("inside error method->" + data);
}
});
var sendUserData = function(){
return JSON.stringify(userData);
};
Everytime when i am trying to delete some records there is no request is going to back-end, instead immediately the alert statement in error method will get executed.
I had tried and googled some blogs. But not able to get the solution.
Before marking duplicate Let me list down what all i tried:-
1.IE does not support JSON object (e.g.: JSON.stringify()) but the json2.js plugin should compensate for that, and I see that is included in my code. So I have not found the answer yet why still not working.
JSON.stringify and JSON.parse not working in IE9?
JSON.stringify does not work in IE
2.I also read that Jquery.Ajax with delete method not working in IE.
Problem with jQuery.ajax with 'delete' method in ie

The error function not working

Hi I just tried testing if the error function would return an alert but it didn't fire. I altered the url link hoping that it would generate an alert since it won't be able to find or get json data. All I am getting is "Uncaught TypeError: Cannot read property 'length' of undefined jquery-1.9.1.min.js:3"
$(document).on('pagebeforeshow', '#blogposts', function () {
//$.mobile.showPageLoadingMsg();
$.ajax({
url: "http://howtodeployit.com/api/get_recent_po",
dataType: "json",
jsonpCallback: 'successCallback',
async: true,
beforeSend: function () {
$.mobile.showPageLoadingMsg(true);
},
complete: function () {
$.mobile.hidePageLoadingMsg();
},
success: function (data) {
$.each(data.posts, function (key, val) {
console.log(data.posts);
var result = $('<li/>').append([$("<h3>", {
html: val.title
}), $("<p>", {
html: val.excerpt
})]).wrapInner('');
$('#postlist').append(result).trigger('create');
return (key !== 4);
});
$("#postlist").listview();
},
error: function (data) {
alert("Data not found");
}
});
});
I think the problem is that, when you make the AJAX request your code is executing the success callback, not the error callback. Thus when you execute:
$.each(data.posts, function(key, val) {
The $.each function is trying to get the length of data which is NULL.
It doesn't look right that you have defined a jsonp callback function and yet your still using the success and error callbacks. This SO question might help a bit :
Use of success / jsonpCallback with ajax request
Maybe here $.each(data.posts, data.posts is undefined and that's why you get an error. Log data in success callback and see what it contains.
I created a clean Fiddle. Opening the given URL gives a 301 redirect followed by a 200 JSON response. The HTTP status code says that everything is fine, so jQuery doesn't know there was an error.
You mixed up two different concepts here: jQuery's error callback is for network errors and all these things. If you transport error states inside your JSON with HTTP status code 200 you have to deal with it on your own inside the success callback.
Sorry, SO doesn't allow JS-Fiddle links without code:
beforeSend: function() { console.log('beforeSend'); },
complete: function() { console.log('complete'); },
success:function (data) { console.log('success') },
error: function(data) { console.log('error') }
Thanks everyone for your input. I did take on-board all suggestions. Recommendation from Jason seems to had made more sense so while investigating his suggestion I came to this site to read up more about jasonCallback. removing the jasonCallback option though did not fix the issue but strangely this issue seems to do with the url I was using for my json caalback.
What I then did was to change the url from "http://howtodeployit.com/api/get_recent_po" to "http://howtodeployit.com/category/daily-devotion/feed/?json=recentstories" and it worked. Even though both returned error in the console but the second was the one that triggered the error function. Why I am looking into it.

Chrome jQuery AJAX failing, not a cross-domain issue

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
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'
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);
}
});
});
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?
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...
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.
Why you don't try this
$('#brochurePage').load($(this).attr('href'),function(){
alert('Load was performed.');
});
Good Luck!
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);
}
});
});
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"); ?>
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.

Categories

Resources