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
Related
So I have to send some data to a php page, and it will return me another php page based on my data.
I send the data this way:
$(document).ready(function() {
$.ajax({
url: '//www.example.com/page.php',
type: "post",
dataType: 'jsonp',
data: { myvar:myvalue },
success: function(response) { console.log("success."); },
error: function(XMLHttpRequest, textStatus, errorThrown) { console.log("error."); },
complete: function() { console.log("complete."); }
});
});
It shows an alert saying jQuery180014405992737595236_1357861668479 was not called (numbers are copied from other question)
I think the reason is that it's expecting a json result from the page, when it's not.
In Chrome it says Uncaught SyntaxError: Unexpected token < referring to the returned php page, so I assume that my code isnt expecting that kind of file to be returned.
To sum up, this works, but that jQuery alert and the console error needs to be fixed, and I think the right way would be handling properly the returned result page.
I hope you guys can help me fix it that seems quite a simple task, but Im really new to this. Thanks
Removing the dataType: 'jsonp' or changing it to 'json' turns out on my script not being executed and getting the following error:
XMLHttpRequest cannot load http://www.example.com/page.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myserver.com/myPage' is therefore not allowed access.
I think the reason is that it's expecting a json result from the page
It's expecting a JSONP response. (JSONP is not JSON). You said:
dataType: 'jsonp',
… which explicitly forces jQuery to treat the response as JSONP (and, as a side effect, GET).
the returned php page, so I assume that my code isnt expecting that kind of file to be returned.
The server shouldn't be returning a PHP page. It should be executing the PHP code and returning whatever that outputs. It looks like it is outputting HTML.
You need to either:
Not tell your script to expect JSONP. (Note that you'll probably then have to configure CORS on the server to deal with same origin issues) or
Change the PHP to return JSONP
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).
I am using jQuery ajax to render an HTML page which also contains javascript functions.
my code is:
function ChartBook() {
$.ajax({
url: '/Charts/ChartBook',
dataType: 'html',
id: 1,
traditional: true,
type: 'GET',
success: function (content) {
$(document.body).empty();
$(document.body).html(content);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('An unexpected error occured.');
}
});
}
The page Chartbook contains a function "GetChartData()".
It runs fine, but when I call another page in same manner, The Chartbook page is now not in the body, but I can still get alert message from function "GetChartData".
How can scripts be still there, while I have removed the page from html body with $(document.body).empty()?
EDIT:
Another problem is that, if I recall the "Chartbook" page and return to the previous page, The alert message comes twice from the function "GetChartData()". the number of alert message increases each time I load Chartbook page and return to previous page.
The scripts are usually placed on top of the body in a header section. Therefore they will not be removed by $(document.body).empty(); which you could also write as $('body').empty();.
Doesn't matter if you remove all html they are still in DOM check this
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)
});
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.