I'm working on an Ajax project. Everything on my page works, including this section:
var data = {
doc: "sample",
action: "updatemsg",
dbid: 97,
message: "text"
};
$.ajax({
url: ANNOTATION_ENDPOINT,
data: data,
success: console.log,
error: console.log
});
However, on every request, it throws this error:
Uncaught TypeError: Illegal invocation jquery.js:974
fire jquery.js:974
self.fireWith jquery.js:1084
done jquery.js:7803
callback jquery.js:8518
and the console.log calls are never made. ANNOTATION_ENDPOINT is a valid URL; my other functions use it with no problem.
I've broken down the problem to this small section but I'm baffled here. Any insight?
the log function expects its context to be the console object not an jqXHR so try
$.ajax({
url: ANNOTATION_ENDPOINT,
data: data,
success: console.log.bind(console),
error: console.log.bind(console)
});
Related
I have an AJAX function that gets an error whenever it gets a JSON response from my other webpage that has an error printed at the end of the JSON response. When there is no error, the function reports normally, but I don't know how to get the AJAX function to ignore the error and just read the JSON part of the response.
HTML:
$.ajax({
url: 'https://example.com/quickstart_data.php',
type: 'POST',
dataType: 'json',
cache: false,
success: function(result) {
$("#timeToLeave").html(result['alarm']['timeToLeave']),
$("#timeToLeave").css({'color':result['background']['text']});
}
But the website responds something like this:
{"background":{"fill":"#202124","text":"White"},"event":{"unixTime":1607040000,"date":"4-12-20","day":"Fri","time":"10:30","dayFinish":"Fri","timeFinish":"11:30"}
Fatal error: Uncaught RuntimeException: Unable to find a speaker for this alarm in /var/www/html/vendor/duncan3dc/sonos/src/Alarm.php:128 Stack trace: #0 /var/www/html/vendor/duncan3dc/sonos/src/Alarm.php(74): duncan3dc\Sonos\Alarm->getSpeaker() #1 /var/www/html/vendor/duncan3dc/sonos/src/Alarm.php(660): duncan3dc\Sonos\Alarm->soap('AlarmClock', 'UpdateAlarm', Array) #2 /var/www/html/vendor/duncan3dc/sonos/src/Alarm.php(167): duncan3dc\Sonos\Alarm->save() #3 /var/www/GoogleAlarm/sonoscontroller.php(47): duncan3dc\Sonos\Alarm->setTime(Object(duncan3dc\Sonos\Utils\Time)) #4 /var/www/GoogleAlarm/quickstart_data.php(362): sonosAlarmUpdate('14', '08:54', false, '10') #5 {main} thrown in /var/www/html/vendor/duncan3dc/sonos/src/Alarm.php on line 128
**note I have removed irrelevant data in the JSON return because it is irrelevant to the problem
The "Fatal error:" part is not normally there unless there is a different error, however I still want the AJAX get JSON response to work. How do I do this? I do not want to turn it off in PHP.ini
If you really want to keep the error in the result parameter of success() but ignore it, do this before accessing the values of result :
let fatalErrorIndex = result.indexOf("Fatal error:");
if(fatalErrorIndex != -1) result = result.substring(0, fatalErrorIndex);
result = JSON.parse(result.trim());
Also, set the dataType to 'text' as you are manually parsing the JSON this way.
However, you should consider implementing ajax error handling. This way if anything wrong happens on the PHP side you'll be notified by the AJAX error callback:
$.ajax({
url: 'https://example.com/quickstart_data.php',
type: 'POST',
dataType: 'json',
cache: false,
success: function(result) {
},
error: function (xhr, ajaxOptions, thrownError) {
// Handle errors here
}
}
This is the correct way to handle errors. See the documentation for more info
I'm running jQuery 1.9.1
On certain links in a Digital Library, I have the following code:
<a class="removeLink" onclick="getDigitalLibrary('removeFromLibrary.action?itemId=1000122007&searchType=ALL')">
Which calls THIS ajax call:
function getDigitalLibrary(urltoremove) {
$.ajax({
url: 'ecom/'+urltoremove,
async: false,
success: function(data) {
$("#ajaxrequest").html($(data).find('#ajaxrequest').html());
},
error: function(data){
alert("An error occurred");
}
});
return remaining;
}
Sometimes when I load the page, I get this error:
Failed to load resource: net::ERR_CACHE_MISS
And whenever I click the link, the entire source code is returned as a
Uncaught Error: Syntax error, unrecognized expression: <!doctype html>...
What am I missing here? If I simply put the full link that is supposed to be created with the Ajax call into the URL bar of my browser.. it works fine: it reloads the page and removes the item from the library.
Use jQuery.parseHTML(data) to parse data and then pass it to $():
success: function(data) {
$("#ajaxrequest").html($($.parseHTML(data)).find('#ajaxrequest').html());
},
In your case $(data) supposes that data is a selector string. parseHTML will make data be supposed as HTML code.
http://jquery.com/upgrade-guide/1.9/#jquery-htmlstring-versus-jquery-selectorstring
I want to execute the following AJAX call (cross domain):
$.ajax({
type: 'GET',
url: url + "?callback=?",
contentType: 'application/json',
async: false,
jsonp: "callback",
dataType: 'jsonp',
success: function (json) {
alert("ok" + JSON.stringify(json));
},
error: function (json) {
alert("err" + JSON.stringify(json));
}
});
And I am getting this alert message:
err{"readyState":4,"status":200,"statusText":"success"}
Which means the code ends in the error method.
If I check the request in Firefox or Chrome, the JSON part of the response is available and clearly formatted. Is it possible to get the JSON response in the error method? Or do you have any idea why the success method isn't hit?
It's not my server unfortunately, so I can't implement any changes on the server side. I used http://jsonlint.com/ to validate the JSON output and it is Valid. Entering the same URL in the browser returns the JSON content correctly.
Thanks much in advance,
I tried a few different approaches, but still failing on the error method,
[EDIT]
SO, I am playing with different approaches, always getting the same error. If I change the error part of my call to this:
error: function (jqXHR, textStatus, ex) {
console.log(arguments);
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
Then I am getting the following error:
http://i.stack.imgur.com/ck6Sd.png
Copy paste of error for search engines:
0: Object
1: "parsererror"
2: Error
message: "jQuery11020553141210693866_1392367304225 was not called"
stack: (...)
get stack: function () { [native code] }
set stack: function () { [native code] }
proto: d
callee: function (jqXHR, textStatus, ex) {
length: 3
proto: Object
The same things apply as above, the response is readable in the browser without issues.
EDIT2
I ended up doing the JSON call the old way, embedding it into the page:
script = document.createElement("script");
script.type = "text/javascript";
script.id = "resultJSON";
script.src = url;
$(".resultsOutput").append(script);
But I have troubles retrieving the data, the script tag seems to be empty. I am getting an error on the JSON:
Uncaught SyntaxError: Unexpected token :
Anyone able to help? I am starting to get desperate on this one. It seems that the issue is that the JASON is returned without a method wrapper.
[LAST EDIT]
So, turns out the server doesn't support CORS and the returned JSON isn't wrapped in a JS function, so this approach won't work. I'll have to use some other approach to retrieve the data.. thanks everyone for reading
Andy
Is there any particular reason to:
Override random callback name jquery gives?
Set datatype to application/json?
This second one may be causing the error. If I'm correct, the server would return application/javascript mime-type, since it should return the JSON you are looking for wrapped into a callback function that shall be called once the request hast completed. Something like this:
function callback() {
return {"a","b"} //the JSON you are looking for
}
This all is handled internally by creating a tag "script" to avoid cross-domain browser restrictions, so you cannot handle JSON directly, it needs to be wrapped into Javascript code. Thus, contentType may be wrong.
Try removing the contenType property on the ajax options and see how jquery behaves (it should interpret content-type from response headers from the server).
Getting an error when trying to retrieve the amount of people someone is followed_by on Instagram.
The API is getting called properly but in line 10 I am getting an error "Uncaught TypeError: Cannot read property 'followed_by' of undefined".
Code is below.
function hello() {
var $url = 'https://api.instagram.com/v1/users/7624/?access_token={access-token}&count=100';
var $access_token = "257177111.ca91fd6.d912fbc4875d4d81abe28ee7b436d8da";
$.ajax({
method: "GET",
url: $url,
dataType: "jsonp",
jsonp : "callback",
success: function(data) {
alert(data.counts.followed_by);
},
error: function(data, error) {
alert("bad");
}
});
}
Change this:
alert(data.counts.followed_by);
to
alert(data);
alert(data.counts);
alert(data.counts.followed_by);
The first one that comes up as undefined is the one that doesn't exist & then fix your problem from there.
If is a whole lot easier to use console.log() to find these sorts of problems because you can just do console.log(data) & it gives you the whole object which you can inspect using any of the available dev tools used for that.
I have an issue with jQuery 1.7.2 and the ajax function, in that when I call the code below I get the following error in Firefox Firebug console:
NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments
[nsIDOMLocation.replace]
var weights= new Object();
// weight is then manipulated in here
$.ajax(
{
url: '/admin/countries/index.php',
data: ({action: 'sort', cid: cid, weights: weights}),
dataType: 'json',
success: function(data){
alert('suck-sess');
// do stuff in here
},
error: function (request, status, error) {
alert(request.responseText);
}
}
)
I'm not even certain that it's successfuly making the request as when I dump out $_REQUEST["action"] in my index.php PHP it comes through blank, when it should clearly be 'sort'.
When I execute the code I don't get the success or error alert, so I can't see where the error is coming from.
NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments [nsIDOMLocation.replace]
This is the kind of internal errors thrown by gecko based browsers (firefox). I don't think it's related to your code. Seems to me more like a browser bug.
It turned out that weights was the problem, as you can see it was defined as a JavaScript object, however I had to use JSON.stringify(weights) to pass it through as a JSON-encoded string.