IE not reading GET success after POST - ajax

I cannot seem to find out why IE does not read my success on get after the post. I have tried cache: false, with no luck. This works in all other browsers, just not IE.
$.ajaxSetup({ cache: false });
num = $('#num').val();
phone = $('#phone').val();
$.post("post.php?"+$("#MYFORM").serialize(), {
}, function(response){
if(response==1 && codeVal == 1 && telVal == 1)
{
$("#after_submit").html('');
$("#Send").after('<label class="success" id="after_submit">Η αποστολή πραγματοποιήθηκε</label>');
change_captcha();
clear_form();
$.ajax({
type:'get',
cache: false,
url: "http://web.somesite/submit_code.php",
dataType: 'html',
data:{ user: "one", pass: "mtwo", source: "WEB", receipt: num, msisdn: phone},
success: function(data) {
var qsFull = "http://web.somesite.gr/submit_code.php?" + data;
var qs = URI(qsFull).query(true);
TINY.box.show({html:qs.message,animate:false,boxid:'error',top:5});
}
});
}
else
{
$("#after_submit").html('');
$("#Send").after('<label class="error" id="after_submit">Error! in CAPTCHA .</label>');
}
});
OK, I tried adding an error after the success and I see that I get my pop up as I should be, but the value of qs.message is 0. Why would I get error and not success, when it is successful in other browsers.

I found the answer, It has to do with IE not being flexible with cross domains and such, so I added a XDomainRequest like so
if (jQuery.browser.msie && window.XDomainRequest) {
var xdr = new XDomainRequest();
var my_request_data = { user: "M1web", pass: "m!", source: "WEB", receipt: num, msisdn: phone};
my_request_data = $.param(my_request_data);
if (xdr) {
xdr.onerror = function () {
alert('xdr onerror');
};
xdr.ontimeout = function () {
alert('xdr ontimeout');
};
xdr.onprogress = function () {
alert("XDR onprogress");
alert("Got: " + xdr.responseText);
};
xdr.onload = function() {
//alert('onload ' + xdr.responseText);
var qsFull = "http://web.web.gr/submit_code.php?" + xdr.responseText;
var qs = URI(qsFull).query(true);
TINY.box.show({html:qs.message,animate:false,boxid:'error',top:5});
callback(xdr.responseText);
};
xdr.timeout = 5000;
xdr.open("get", "http://web.web.gr/submit_code.php?" + my_request_data);
xdr.send();
} else {
}
}

I unfortunately had to do a crash course in legacy IE behavior, and this post was very helpful. Here are some other links to help those having to deal with these issues:
Microsoft's Documentation of their XDomainRequest object
An internal blog post covering some of XDomainRequest's idiosyncrasies
Here's a function I use as a fallback where necessary:
// This is necessary due to IE<10 having no support for CORS.
function fallbackXDR(callObj) {
if (window.XDomainRequest) {
var xdrObj = new XDomainRequest();
xdrObj.timeout = callObj.timeout;
xdrObj.onload = function() {
handleSuccess(xdrObj.responseText);
};
xdrObj.onerror = function() {
handleError(xdrObj);
};
xdrObj.ontimeout = function() {
callObj.xdrAttempts = callObj.xdrAttempts++ || 1;
if (callObj.xdrAttempts < callObj.maxAttempts) {
fallbackXDR(callObj);
}
};
xdrObj.onprogress = function() {
// Unfortunately this has to be included or it will not work in some cases.
};
// Use something other than $.param() to format the url if not using jQuery.
var callStr = callObj ? '?'+$.param(callObj.urlVars) : '';
xdrObj.open("get", callObj.url+callStr);
xdrObj.send();
} else {
handleError("No XDomainRequest available.", callObj);
}
}//fallbackXDR()

Related

Is there a way to show "Loading data.." option in Rally Grid(ext JS) while making the Ajax request to load the data?

I am trying to set the message to "Data Loading.." whenever the data is loading in the grid. It is working fine if I don't make an Ajax call. But, when I try to make Ajax Request, It is not showing up the message "Loading data..", when it is taking time to load the data. Can someone please try to help me with this.. Thanks in Advance.
_loadData: function(x){
var that = this;
if(this.project!=undefined) {
this.setLoading("Loading data..");
this.projectObjectID = this.project.value.split("/project/");
var that = this;
this._ajaxCall().then( function(content) {
console.log("assigned then:",content,this.pendingProjects, content.data);
that._createGrid(content);
})
}
},
_ajaxCall: function(){
var deferred = Ext.create('Deft.Deferred');
console.log("the project object ID is:",this.projectObjectID[1]);
var that = this;
console.log("User Reference:",that.userref,this.curLen);
var userObjID = that.userref.split("/user/");
Ext.Ajax.request({
url: 'https://rally1.rallydev.com/slm/webservice/v2.0/project/'+this.projectObjectID[1]+'/projectusers?fetch=true&start=1&pagesize=2000',
method: 'GET',
async: false,
headers:
{
'Content-Type': 'application/json'
},
success: function (response) {
console.log("entered the response:",response);
var jsonData = Ext.decode(response.responseText);
console.log("jsonData:",jsonData);
var blankdata = '';
var resultMessage = jsonData.QueryResult.Results;
console.log("entered the response:",resultMessage.length);
this.CurrentLength = resultMessage.length;
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:resultMessage
});
this.pendingProjects = resultMessage.length
console.log("this testcase store:",resultMessage);
_.each(resultMessage, function (data) {
var objID = data.ObjectID;
var column1 = data.Permission;
console.log("this result message:",column1);
if(userObjID[1]==objID) {
console.log("obj id 1 is:",objID);
console.log("User Reference 2:",userObjID[1]);
if (data.Permission != 'Editor') {
deferred.resolve(this.testCaseStore);
}else{
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:blankdata
});
deferred.resolve(this.testCaseStore);
}
}
},this)
},
failure: function (response) {
deferred.reject(response.status);
Ext.Msg.alert('Status', 'Request Failed.');
}
});
return deferred;
},
The main issue comes from your Ajax request which is using
async:false
This is blocking the javascript (unique) thread.
Consider removing it if possible. Note that there is no guarantee XMLHttpRequest synchronous requests will be supported in the future.
You'll also have to add in your success and failure callbacks:
that.setLoading(false);

Why do I get this error (failed) net::ERR_CONNECTION_CLOSED after ajax request?

In my localhost it works fine, but on hosting I get this error
(failed) net::ERR_CONNECTION_CLOSED.
What does this error mean and how can I solve this problem? This is a Laravel/vue project.
Code of ajax request:
var firstHalf = this.menu.slice(0, 21);
var secondHalf = this.menu.slice(21);
var result = [firstHalf,secondHalf];
this.isLoading = true;
for (let i = 0; i < result.length; i++) {
let statusCode = 200;
axios({
method: "post",
url: "/admin/menu/addMenu/",
header: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
},
params: {
menu: result[i],
startDate: this.selectedDate,
order: i + 1
}
}).then(response => {
console.log("ajax")
console.log(response.status);
console.log(response);
if (i+1>= result.length) {
this.message = response.data.message;
this.modalShow = true;
this.isLoading = false;
return;
}
});
}
What I did is the following:
var verifyIdentity = formData.get('verify_identity')
if(verifyIdentity && verifyIdentity.size === 0){
formData.delete('verify_identity')
}
Basically saying, if there is a file type attribute, but it is not filled out (meaning you never actually picked the file to submit), just remove it from form data.
It's a tad different example as I don't see what you're actually submitting, but I noticed the issue on my part was due to the type="file" input fields.

Angular get request within rails app not working

I'm trying to make (my first) angular get request within a rails app to one of my routes. I'm not sure why this is returning nothing, not even an error.
function accomplishmentController($scope, $http) {
$scope.$apply(function() {
$http({method: 'GET', url: '/api/users'}).
success(function(data, status, headers, config) {
console.log("hell0");
}).
error(function(data, status, headers, config) {
console.log("error");
});
});
$scope.accomplishments = [];
$scope.submit = function() {
$scope.accomplishments.unshift({ name: $scope.newAccomp, count: 0 });
$scope.newAccomp = '';
}
$scope.addToCount = function() {
var currentcount = this.accomp.count;
this.accomp.count = currentcount + 1;
}
$scope.delete = function() {
index = this.$index;
$scope.accomplishments.splice(index, 1)
}
}

Ajax function gives Cannot read property 'length' of undefined

This function works fine as long im on the same page where the search div imagesearch is.
If im on another site on the website, ill get the error
Cannot read property 'length' of undefined.
The console point put row 27, that's where the if statement start if(q.length..
Cant really find out whats the problem. Any ideas ?
function reloadSearch() {
if (!isLoading) {
var q = $('#imagesearch').val();
if (q.length >= 2) {
isLoading = true;
$.ajax({
type: 'GET',
url: 'core/flickr.php',
data: 'search=' + q,
dataType: 'html',
beforeSend: function () {
$('#imageresult').html(
'<img src="img/loading45.gif" alt="loading..." />');
if (!q[0]) {
$('#imageresult').html(
'');
return false;
}
},
success: function (response) {
$('#imageresult').html(
response);
}
});
// enforce the delay
setTimeout(function () {
isLoading = false;
if (isDirty) {
isDirty = false;
reloadSearch();
}
}, delay);
}
}
};
var delay = 1000;
var isLoading = false;
var isDirty = false;
$(document).ready(function () {
reloadSearch();
$('#imagesearch').keyup(function () {
isDirty = true;
reloadSearch();
});
});
change:
if (q.length >= 2) {
to
if (q !== undefined && q.length >= 2) {
this will stop the can't read value from undefined...If you code in .Net this is similar to the null reference exception.

Backbone collection fetch error with no information

I have a strange problem with the fetch of a backbone collection I am working with. In one particular instance of my code I perform a fetch (exactly how I do it in other areas of the code which all work fine), the fetch never seems to make it to the server and the developer tools shows the request as red with the word (canceled) in the status/text field.
I've walked this through into the backbone sync method and I see the $.ajax being built and everything looks fine. Has anyone run into this problem?
here is my code if it helps, this is a function that calls two .ashx services to first check for a file's existence then to open it. The part that isn't working for me is the "me.collection.fetch().
openDocument: function () {
var me = this,
fileId = me.model.get('id'),
userId = Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
fileRequest = '/genericHandlers/DownloadFile.ashx?id=' + fileId + '&userId=' + userId,
fileCheck = '/genericHandlers/CheckFileExistance.ashx?id=' + fileId + '&userId=' + userId;
//hide tooltip
me.hideButtonTooltips();
// Check for file existance
$.ajax({
url: fileCheck
})
.done(function (data) {
if (data && data === "true") {
document.location.href = fileRequest;
me.collection.fetch();
} else if (!!data && data === "false") {
"This file is no longer available.".notify('error');
}
})
.fail(function (data) {
"Something went wrong during the File Existance check".notify('error');
"Something went wrong during the File Existance check".log(userId, 'error', 'Docs');
});
},
my collection:
// docsCollection.js - The collection of ALL the documents available to a given user
// Document Collection
Dashboard.Collections.DocsCollection = Backbone.Collection.extend({
model: Dashboard.Models.DocumentUploadModel,
url: function () {
return 'apps/docs/Docs/' + this.userId;
},
initialize: function (options) {
this.userId = options.userId;
this.deferredFetch = this.fetch();
},
comparator: function (model) {
return -(new Date(model.get('expirationDate')));
},
getDaysSinceViewedDocuments: function () {
return this.filter(function (model) {
return model.get('daysSinceViewed') !== null;
});
},
getNewDocuments: function () {
return this.filter(function (model) {
return model.get('isNew');
});
},
getExpiredDocuments: function () {
return this.filter(function (model) {
return model.get('isExpired');
});
}
});
and my model:
Dashboard.Models.DocumentUploadModel = Backbone.Model.extend({
defaults: {
fileArray: [],
name: '',
description: '',
accesses: [],
tags: [],
expirationDate: ''
},
initialize: function () {
this.set({
userId: Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
expirationDate: (this.isNew()) ? buildExpirationDate() : this.get('expirationDate')
}, { silent: true });
function buildExpirationDate() {
var date = new Date((new Date()).getTime() + 24 * 60 * 60 * 1000 * 7),
dateString = "{0}/{1}/{2}".format(date.getMonth() + 1, date.getDate(), date.getFullYear());
return dateString;
}
},
firstFile: function () {
return this.get('fileArray')[0];
},
validate: function (attributes) {
var errors = [];
if (attributes.name === '' || attributes.name.length === 0)
errors.push({
input: 'input.txtName',
message: "You must enter a name."
});
if (attributes.description === '' || attributes.description.length === 0)
errors.push({
input: 'textarea.taDescription',
message: "You must enter a description."
});
if (errors.length > 0)
return errors;
return;
},
sync: function (method, model, options) {
var formData = new FormData(),
files = model.get("fileArray"),
$progress = $('progress'),
success = options.success,
error = options.error;
// Nothing other than create or update right now
if (method !== "create" && method !== "update")
return;
// Build formData object
formData.append("name", model.get("name"));
formData.append("description", model.get("description"));
formData.append("accesses", model.get("accesses"));
formData.append("tags", model.get("tags"));
formData.append("expirationDate", model.get("expirationDate"));
formData.append("userId", model.get("userId"));
formData.append("isNew", model.isNew());
// if not new then capture id
if (!model.isNew())
formData.append('id', model.id);
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
}
xhr = new XMLHttpRequest();
xhr.open('POST', '/genericHandlers/UploadDocsFile.ashx');
xhr.onload = function () {
if (xhr.status === 200) {
if (success)
success();
} else {
if (error)
error();
}
}
if ($progress.length > 0) {
xhr.upload.onprogress = function (evt) {
var complete;
if (evt.lengthComputable) {
// Do the division but if you cant put 0
complete = (evt.loaded / evt.total * 100 | 0);
$progress[0].value = $progress[0].innerHTML = complete;
}
}
}
xhr.send(formData);
},
upload: function (changedAttrs, options) {
this.save("create", changedAttrs, options);
}
});
You're assigning a value to document.location.href before you try to fetch your collection:
document.location.href = fileRequest;
me.collection.fetch();
Changing document.location.href will change the whole page and in the process, any currently running JavaScript will get shutdown so I wouldn't expect your me.collection.fetch() to ever get executed.

Resources