jQuery $.ajax works with GET but fails on POST - javascript

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

Related

Inactive status error received - JQuery

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.

Send log errors to a file

I developed a website for my graduation however it still only one thing I have do. What I want is when the script is installed on a website I want to send the name of the website who has installed my script, also whenever there is an error I want to send it to my website so for example:
This website installed my script
www.security-dz.com/myscript
I want to see the path + website in an other file in other website. For example:
www.getlog.com/mylogs.php
The purpose of this is keep my customers update and give them support and see the errors that happen so I can fix them in next updates.
You might want to take a closer look at the JQuery docs for ajax requests, so you can use a secure http connection for logging. This javascript code basically describes a function that sends the errors in text-format to your server-side script. This script can in turn write the error description to a file on the server. I'd recommend using a DB instead; That way you can easily write a web-client that displays all reported errors (and filters and the other good stuff).
You can extract the origin url from the referer [sic] field in the ajax http get-request on the server.
(function () { // function operator, in case console doesn't exist
!console ?
(console = {}) : console;
!console.log ?
(console.log = function () { }) : console.log;
!console.info ?
(console.info = console.log) : console.info;
!console.error ?
(console.error = console.log) : console.error;
}());
// Uses JQuery
function reportError (errDesc) {
var path = "www.getlog.com/mylogs.php";
$.ajax({
url: path,
type: "GET",
async: true,
cache: false,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
crossDomain: true,
data: errDesc,
dataType: "jsonp",
error: function (req, type, errObj) {
console.error("Reporting error failed: " + type + "\nAt url: " + path + "\n" + errObj);
// In case you need to debug the error reporting function
},
succes: function (res) {
console.info("Reported error to server:\nRequest:" + errDesc + "\nResponse: " + res);
// extra error logging facility on client-side, invisible to most users
},
global: false // prevent triggering global ajax event handlers
});
return errDesc; // in case you want to reuse the errDesc
}
Code has been validated with jshint. Please let me know if there are still issues, because I didn't take the time to completely replicate your setup (setting up 2 different domains etc.)
Addendum: Some useful reading if you're having issues with cross-domain messaging, JSON is not a subset of javascript, Cross-origin resource sharing, JSONP.
What you could do is post both the name of the website that uses your script and the error code variable with AJAX through URL to your logging website, which will then get the variable and name from the URL and use these to add to your log.
You should, however, by using this tactic, also make use of some URL validation, otherwise this will leave you wide open to injection attacks.
it is easy when your script installed , get the site info and send by socket and http request with get method and then recive it on your server.
for errors, php has some method to control error logs so custom it.

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.

Failed to load resource + $.ajax call in Chrome

I am having a very strange issue with Chrome and AJAX, I have an autocomplete form that has been working for a while. I fired up Visual Studio this morning and it doesn't work anymore. It works fine in production (with Chrome) and works fine locally if I use Firefox or IE, for chrome it doesn't!
I get the error:
Failed to load resource
in Developer tools, When I expand on the error I get:
f.support.ajax.f.ajaxTransport.sendjquery-1.7.1.min.js:4
f.extend.ajaxjquery-1.7.1.min.js:4
$.autocomplete.sourceCreate:217
a.widget._searchjquery-ui-1.8.17.custom.min.js:127
a.widget.searchjquery-ui-1.8.17.custom.min.js:127
(anonymous function)jquery-ui-1.8.17.custom.min.js:127
I placed a breakpoint in the callback function on the server but it doesn't even make it to the server. The error is definitely on the client side, here is the client-side code:
$("#LocationTxt").autocomplete({
minLength: 4,
source: function (req, resp) {
$.ajax({
type: "GET",
url: "/Ad/SearchLocations",
data: "term=" + req.term,
contentType: "application/json; charset=utf-8",
success: function (data) {
resp($.map(data, function (value, key) {
return { data: value, label: data[key].Name, value: data[key].Name };
}));
},
error: function (data) {
alert(data.statusText);
}
});
},
select: function (e, ui) {
var cityId = ui.item.data.Id;
$('#AdListing_LocationID').val(cityId);
}
});
Also the error event gets triggered, and the statusText property is simply "error". Not very helpful. I am running Chrome version: 17.0.963.46 (I have the latest version as on 2/9/2012). I believe my Chrome updated this morning when I fired up my PC, but I am not sure. Is there a log to tell when my chrome was updated?
If you are working on a local copy of the code, make sure you are working from within a web-server such as localhost. If you are working directly from the file system, google chrome will not allow you to make ajax requests to files on the file system for security reasons.
A few more things...
Remove this:
contentType: "application/json; charset=utf-8",
You aren't sending json, you are sending a GET request. Instead, add this
dataType: "json",
so that jQuery expects to receive json.
It also may help to have your server return headers setting the contentType to application/json with the proper charset utf-8.

Problem with jQuery.ajax with 'delete' method in ie

I have a page where the user can edit various content using buttons and selects that trigger ajax calls. In particular, one action causes a url to be called remotely, with some data and a 'put' request, which (as i'm using a restful rails backend) triggers my update action. I also have a delete button which calls the same url but with a 'delete' request. The 'update' ajax call works in all browsers but the 'delete' one doesn't work in IE. I've got a vague memory of encountering something like this before...can anyone shed any light? here's my ajax calls:
//update action - works in all browsers
jQuery.ajax({
async:true,
data:data,
dataType:'script',
type:'put',
url:"/quizzes/"+quizId+"/quiz_questions/"+quizQuestionId,
success: function(msg){
initializeQuizQuestions();
setPublishButtonStatus();
}
});
//delete action - fails in ie
function deleteQuizQuestion(quizQuestionId, quizId){
//send ajax call to back end to change the difficulty of the quiz question
//back end will then refresh the relevant parts of the page (progress bars, flashes, quiz status)
jQuery.ajax({
async:true,
dataType:'script',
type:'delete',
url:"/quizzes/"+quizId+"/quiz_questions/"+quizQuestionId,
success: function(msg){
alert("success");
initializeQuizQuestions();
setSelectStatus(quizQuestionId, true);
jQuery("tr[id*='quiz_question_"+quizQuestionId+"']").removeClass('selected');
},
error: function(msg){
alert("error:" + msg);
}
});
}
I put the alerts in success and error in the delete ajax just to see what happens, and the 'error' part of the ajax call is triggered, but WITH NO CALL BEING MADE TO THE BACK END (i know this by watching my back end server logs). So, it fails before it even makes the call. I can't work out why - the 'msg' i get back from the error block is blank.
Any ideas anyone? Is this a known problem? I've tested it in ie6 and ie8 and it doesn't work in either.
thanks - max
EDIT - the solution - thanks to Nick Craver for pointing me in the right direction.
Rails (and maybe other frameworks?) has a subterfuge for the unsupported put and delete requests: a post request with the parameter "_method" (note the underscore) set to 'put' or 'delete' will be treated as if the actual request type was that string. So, in my case, i made this change - note the 'data' option':
jQuery.ajax({
async:true,
data: {"_method":"delete"},
dataType:'script',
type:'post',
url:"/quizzes/"+quizId+"/quiz_questions/"+quizQuestionId,
success: function(msg){
alert("success");
initializeQuizQuestions();
setSelectStatus(quizQuestionId, true);
jQuery("tr[id*='quiz_question_"+quizQuestionId+"']").removeClass('selected');
},
error: function(msg){
alert("error:" + msg);
}
});
}
Rails will now treat this as if it were a delete request, preserving the REST system. The reason my PUT example worked was just because in this particular case IE was happy to send a PUT request, but it officially does not support them so it's best to do this for PUT requests as well as DELETE requests.
IE 7 and 8 do not support DELETE and PUT methods. I had a problem where IE7,8 would not follow a 302 redirect and IE would use the DELETE or PUT method for the location that it was supposed to redirect to (with a get.)
To ensure that IE7 and 8 work properly, I would use a POST with the parameters:
data: {'_method': 'delete'}
Take a look at your type attribute type:'delete'
jQuery documentation on type:
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
I would instead try and include this with your data and look for it on the server-side, like this:
data: {'action': 'delete'},

Categories