Recently I purchased a chat script which works fine in Firefox, but not in Chrome. I have located the error, but cannot solve it. The code is ...
function checknew(){
$.ajax({
url: "user_chat/chat.php?action=checknew",
type : "GET",
contentType: "application/json",
cache: false,
dataType: "json",
async: false,
error: alert('error');
success: function(data) {
When I check it in firefox, everything is working fine. But in Chrome the alert message triggers. Can anyone please tell me what is wrong here?
The error attribute expects a function reference, but this is a call.
So, replace:
error: alert('error');
with:
error: function () {
alert('error');
},
This assigns an anonymous function to error, that calls alert('error'), instead of trying to call it when a definition was expected.
Try changing this
async: false,
error: alert('error');
success: function(data) {
to this:
async: false,
error: function(xhr, Status, Error){
alert('Status: ' + Status); //Add a breakpoint (see below)
alert('Error: ' + Error);
},
success: function(data) {
Also, you should get out of the habit of using alert() and learn to use a debugger. Chrome comes with one built in, Firefox does too but IMHO the Firebug addon is better.
In Chrome, press F12. Go to the Sources tab, use the menu # the left to find your page and double-click on the line indicated above. This will add a breakpoint.
Now, when the javascript runs, when it gets to that line, it will stop and let you look at variables, error messages, etc...
Also, the Network tab shows every web request made by that page (download images, get css, AJAX calls, etc). You can see if they succeeded or not, what error was returned by the server, etc...
There is a really in-depth guide on using the Chrome tools here. Firebug for FF is almost identical to use (although IMHO a slightly more intuitive interface).
Finally, all the dev tools mentioned have a "Console" where certain information (like recent warnings and errors) are shown. You can even output your own messages there (google Javascript Console.Log.
Related
I have an Ajax request that is sent over to a file to grab information and return JSON.
Here is my request example:
$.ajax({
url: "admin/actions/ifp_get_events.php",
type: "post",
dataType: "json",
data:
{
'elevation_name' : 'global',
'function' : 'elevation_restrictions_events',
'parent_id' : d.ifp_id
},
success: function(data){
......do stuff
},
error:function(){
alert("error occured, please try again.");
}
});
Now I've been developing using Google Chrome and it works perfect but when I go to try this in Firefox or IE I am getting the following error:
The alert of coarse is being triggered and I have a response text of:
responseText:"
{
"status":"error",
"message":"You have been logged out due to inactivity."
}
{"status":"found","code":1,"original_request":
{"elevation_name":"global","function":"elevation_restrictions_events","parent_id":"26"},"data_retrieved":[{"evt_for":"Game Room","evt_restriction":"","evt_select_ability":"hide","evt_active_ability":"disable"},{"evt_for":"Bedroom 5 w\/ Bath 5","evt_restriction":"Craftsman Entry, Kitchen","evt_select_ability":"show","evt_active_ability":"enable"}]}"
Note that once the error message was given the new status section is the correct response I needed. I am just uncertain as to why this is happening in Firefox and IE?
Suggestions, thoughts?
If you need any more information please ask me.
Browser sessions aren't shared across browsers. In your case, you were logged in Chrome and hence the code was working as expected.
However, when trying out with FF and IE, you weren't logged in and hence the output was different.
add this line :
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
},
after your data.
Since the valid csrf token is not going its logging you out of the site.
I'm trying to use jQuery JSONP AJAX requests in a bookmarklet and I'm finding that the requests work on some pages, but not on others. Here's example code:
jQuery.ajax({
url: "http://echo.jsontest.com/key/value/one/two",
type: "GET",
dataType: "jsonp",
cache: false
}).done( function(data){
console.log(data);
}).fail(function(jqXHR, textStatus, errorThrown){
console.log("errorThrown: " + errorThrown);
});
If you go to the following Amazon page:
http://www.amazon.com/dp/B00336EUTK?psc=1
And execute the above code in your console, you'll find that it works. However, if you go to this Amazon page:
http://www.amazon.com/dp/B00E5UHSYW?psc=1
And execute the above code in your console, the following error appears:
TypeError: Cannot call method 'done' of undefined
What is causing this problem and how can it be fixed?
EDIT: One interesting thing I've noticed is that on pages where the AJAX requests works, the callback parameter always seems to look like this:
callback=jQuery1640586556919850409_1390439428297
On pages where it fails, it always seems to look like this:
callback=jsonp1390439502398
I've tried this on a bunch of different Amazon pages and it seems like that behavior is consistent.
Maybe it's just a coincidence, but I thought it might be worth pointing out.
Different versions of jQuery
Believe it or not, those two pages are using different versions of jQuery.
You can determine this yourself by typing this into the console: $().jquery
the first page is running v1.6.2
the second page is running v1.2.6
Looking at the jQuery docs for jQuery.ajax()(here), it looks like it was not added to jQuery until v1.5
Hope that helps.
If you run a console.log(jQuery.ajax); in console, you'll see that the second link you referenced does not contain a done function in the jQuery.ajax class (since they are two different versions). You can do a version check and handle two different solutions depending on whether or not jQuery has that class method. This works for both links you posted:
//get the jQuery version
var version = jQuery.fn.jquery,
parts = version.split('.');
//piece together a version integer
version = parseInt(parts[0]+parts[1]+parts[2],10);
if (version >= 150) {
//new method
jQuery.ajax({
url: "http://echo.jsontest.com/keyu/value/one/two",
type: "GET",
dataType: "jsonp",
cache: false
}).done( function(data){
console.log(data);
}).fail(function(jqXHR, textStatus, errorThrown){
console.log("errorThrown: " + errorThrown);
});
} else {
jQuery.ajax({
url: "http://echo.jsontest.com/keyu/value/one/two",
type: "GET",
dataType: "jsonp",
success: function(data){
console.log(data);
},
error: function(e){
console.log(e);
}
});
}
I've got a really weird problem on a customer's server.
I'm using code like the one posted below in several scripts.
The $.ajax configurations are almost identical (i.e. only file, data and success function change) and always use type:POST.
This works most of the times, but for the case below POST always fails.
Changing the type to GET works without a problem.
I'm a little bit clueless what happens here.
var parameter = {
password : $("#password").val()
};
$.ajax({
type : "POST",
url : "query/submit_password.php",
dataType : "xml",
async : true,
data : parameter,
success : function(aXHR) { /* ... */ },
error : function(aXHR, aStatus, aError) { alert("Error:\n" + aStatus + "\n"+ aError); }
});
This code always results with an alert "NetworkError: A network error occurred.".
Again - other cases with almost identical code work without a problem.
Chrome and Firefox dev tools report a POST error without any further explanation.
Any idea what happens here?
A few more details.
The client's site is hosted on GoDaddy
The same piece code works well on other servers
Yes, the file does exist as a GET request works
All browsers I tried this on have no blocker plugins (like adblock) installed
HTTPScoop shows the following results
(3 attempts, the red status says "Connection closed by communications partner"):
Chrome shows the following:
Almost solved.
The apache log showed a status 403 on the request.
It also showed a returned size of 0 which probably is the reason why chrome, etc. showed a failed request.
Why this happens is still not clear but it is definitely a server side configuration problem (most likely a mod_rewrite problem or sth. like that).
try add contentType: "application/json; charset=utf-8" to your ajax call
$.ajax({
type : "POST",
url : "query/submit_password.php",
contentType: "application/json; charset=utf-8",
dataType : "xml",
async : true,
data : parameter,
success : function(aXHR) { /* ... */ },
error : function(aXHR, aStatus, aError) { alert("Error:\n" + aStatus + "\n"+ aError); }
});
if it doesn't help try what benhowdle89 says, stringify(parameter).
I has encountered this problem when using jquery ajax on IE8 (not happen in IE9+, Chrome or Firefox). After researching for a while, still cannot figure out what was the problem.
A bit on the background, the website was built on Yii PHP framework, jQuery version is 1.8.3 (from Yii core). Here are my code:
$.ajax ({
url: url, // url = "/webapp/vote/apicreate"
type: 'post',
cache: false,
dataType: "json",
contentType: "application/json",
data: {
video_id : video_id,
vote_num : vote_num
},
success: function(response){
alert('success'); // for demonstration only
},
error: function(xhr, textStatus, err){
if (typeof console !== "undefined") console.log(textStatus);
}
}
Okay, with this I always received "Type Error: Could not complete the operation due to error 80070005". Both 'readyState' and 'status' are 0. A bit of frustration, cos I neither know what it mean nor how to fix it. Have tried to use the pure javascript solution which yields the same result...
Last thing to note is I'm on a Mac, testing IE8 using Wine. Can it be related somehow ?
Use the following steps to troubleshoot:
Change the url value to 127.0.0.1
Use alert(response.responseText) instead of 'success'
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.