Inactive status error received - JQuery - javascript

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.

Related

Error with Jquery, json in Chrome

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.

jQuery $.ajax works with GET but fails on POST

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).

jQuery and Ajax - cannot POST

I am trying to login to a website using a known username and password and to get some data displayed from the site for a specific user account on that website. I am using jQuery and Ajax for this purpose. This is my code:
$.ajax({
async: false,
cache: false,
type: 'POST',
dataType: 'json', // json...just for example sake
data: ({
'login_username': username,
'secretkey': password
}),
url: 'https://mail.someserver.com/src/redirect.php',
success: function (data) {
alert("SUCCESS!")
if (data === '1') { // server returns a "1" for success
// success!
// do whatever you need to do
} else {
// fail!
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// something went wrong with the request
alert("Failed!");
}
});
I've already made my search around the web and I know that browsers do not permit cross server ajax calls to prevent security issues, but I've already tried to use "jsonp" as dataType to no avail :(
So, what am I doing wrong?
Be sure that your url is not breaking the same origin policy -- that is, the request coming from the client cannot request data from a server from a different domain (there are exceptions to this rule, namingly CORS, but that requires that you make changes to the server/application you're talking to).
The solution to your problem would be to make the request from some server-side script, then in turn having your client application query that script, based on the same machine that's serving the application to the web.
My fault isn't at the code above, my fault was that in my manifest file (I am building a Google Chrome extension) I didn't have set proper permissions (https://*).
Sorry for the frustration!

ajax that worked repeatedly in jquery 1.3.2 only works first time in 1.7.1

Here's the code:
$(document).ready(function() {
$().ajaxStart(function(){
alert("in ajaxStart")
//tried removing $.blockUI( below, same thing. don't see alert
//$.blockUI({ message: '<h1><img src="images/ajax-loader.gif" /> Running query...</h1>' });
});
$().ajaxStop(function(){
$.unblockUI()
});
...
$("#frmQUERYSUBMIT").submit(function(e) {
...
$.ajax({
type: "POST",
url: '/execquery/' + jsonQuery,
//datatype: JSON, //original, incorrect
datatype: "json", //still get same problem with correct usage
success: function(data, textStatus) {
$("#status p").html(data);
},
async: true
});
...
});
});
In 1.3.2, this worked fine, reached the server, gave me back the data I expected. When I upgraded to 1.7.1, it works once (per opening of browser), but all subsequent executions do nothing. If I step thru the code in firebug, it shows it going from line to line every time, but only actually does something the first time. Also, in 1.7.1, $().ajaxStart( is also only run the first time, not any subsequent times.
TIA
EDIT: I had originally posted that my server logs showed no connection on subsequent attempts. This was an error. The logs show that a connection is made, and a response given. It just doesn't show up in the browser.
EDIT: FWIW, in 1.3.2, the data comes back as "{"queries":{"f.sp":{"1d":{"show_results":{"19820611":-2.6893769610040343,..."; but in 1.7.1, it comes back as Document, and says that the type is application/xml
JSON is not a valid datatype, try giving datatype: 'json'
Issue #1, the data not being available to javascript was solved by this: https://stackoverflow.com/a/250245/403748,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
and issue #2 was solved by https://stackoverflow.com/a/4034337/403748
$(document).ajaxStart(
instead of
$().ajaxStart(
Sorry for the time-waster...

firefox ajax call returning NS_ERROR_DOM_BAD_URI or jsonp false error

In relation to can't debug hanging $.post in firefox extension
can anyone tell me why my extension https://builder.addons.mozilla.org/addon/1022928/latest/ is with this ajax call:
var url = 'http://e-ønsker.dk/wishlist/ajax/add/';
$(this).hide();
//show icon loading
$("#icon").show();
$.ajax({
type: "POST",
url: url,
data: {title:$("#txtTitle").val(), url:encodeURIComponent(taburl)},
success: function(data, textStatus) {
if(data.code > 0)
{
$("#icon").removeClass().addClass('accept');
}
else
{
$("#icon").removeClass().addClass('error');
if(data.code == '-1')
alert('kunne ikke finde din ønskeseddel på e-ønsker.dk - besøg e-ønsker.dk, og prøv derefter igen');
}
},
error: function(data, textStatus) {
alert(textStatus);
$("#icon").removeClass().addClass('error');
}
});
is returning the error NS_ERROR_DOM_BAD_URI. HttpFox says it's a 500 error which would indicate an internal error, but this exact call works from both chrome and safari in their extensions, so I'm suspecting the error to be related to firefox specifically.
UPDATE
So I added dataType: "jsonp" and that did some of the magic, now I get a 200 response, but I still get a parsererror.
Weirdest thing is that after I modify my server to accomodate JSONP jquery chooses the error method, and the xhr.statusText that I show here alert(xhr.statusText); gives me an alert with the statustext "success" why won't jquery choose the success method when it actually works??
You cannot get data from a different domain from the one you are currently on using AJAX -> http://en.wikipedia.org/wiki/Same_origin_policy
If you are using the same domain then use relative paths ... I suspect that Firefox is encoding the e-ønsker.dk part of the url - making it look like a different domain.

Categories