Safari Cannot Load XMLHttpRequest Due to Access Control Checks - ajax

I am running into an issue that only occurs on Safari when searching on the website. It also only occurs when a user types and presses enter faster than the search suggestions can load.
The error we receive is: "XMLHTTPRequest cannot load [URL]/?query=testing due to access control checks. All requests are on the same domain so I do not believe this is a CORS problem. Also it appears to happen during the remote function and not the prefetch due error containing /query
The typeahead configuration is found below:
$('#searchIconInput').typeahead({
hint: true,
highlight: true,
minLength: 3
},
{
name: 'searchSuggestionsShown',
source: searchSuggestionEngine
});
});
var searchSuggestionEngine = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: '#Url.Action("RetrieveSuggestedSearchItems", "Search")',
ttl: getNumberOfMillisecondsToCachePrefetchedData(),
},
remote: {
url: '#Url.Action("RetrieveAdditionalSuggestedSearchItems", "Search")/?query=',
replace: function (url, uriEncodedQuery) {
return url + uriEncodedQuery;
},
cache: false
}
});

Related

FineUploader onSubmit not being called

Using FineUploader 3.8.2 to upload PDF files to S3, I am running into an interesting issue and not sure if perhaps I'm just using the wrong syntax or not understanding how the options should work for fineUploader. Here is my code...
var uploader = $('#fine-uploader-box').fineUploaderS3({
debug: true,
button: $('#choose-file-button'),
multiple: false,
autoUpload: false,
request: {
endpoint: '(no url yet because I need to know about the file before I can construct an S3 PUT url)'
},
callbacks: {
onSubmit: function(id, name){ // function to get real endpoint url goes here },
onSubmitted: function(id, name){ // or function to get real endpoint url goes here }
},
validation: {
allowedExtensions: ['pdf']
}
});
What I am trying to do is just get a function to run once my file has been added to the list but I am not seeing the onSubmit (or onSubmitted) firing.
My goal is to have that function do some ajax-y stuff and return some information in which I will use to facilitate the rest of the upload process including getting a specialized S3 PUT url from my server to send my upload to.
Any help would be greatly appreciated. Thanks.
It appears that you are using the syntax for the non-jQuery uploader, but you are using the jQuery uploader. Check out the below:
var uploader = $('#fine-uploader-box').fineUploaderS3({
debug: true,
button: $('#choose-file-button'),
multiple: false,
autoUpload: false,
request: {
endpoint: '(no url yet because I need to know about the file before I can construct an S3 PUT url)'
},
validation: {
allowedExtensions: ['pdf']
}
}).on('submit', function (event, fileId, fileName) {
alert("File id: "+fileId);
}).on('submitted', function (event, fileId, fileName) {
alert("File id: "+fileId);
});

How to abort remote Jquery Validator method upon submit

My site is http://www.extrabux.com/users/login
When a user is logging in, Jquery Validate plugin uses a "remote" function to check whether the provided email address exists in our database as a user. If the connection and our server is fast, the user sees feedback before she even finishes typing her password.
email: {
required: true,
email: true,
remote: {//http://docs.jquery.com/Plugins/Validation/Methods/remote
url: 'check-signin-email-address',
type: "post",
data: {
emailAddress: function() {
return $("#email").val();
}
}
}
}
If the connection or our server is slow, however, this causes an undesirable delay before the form can be submitted (because the Jquery Validate plugin waits until the form is confirmed to be valid).
What I'd like is:
If the remote query finishes before the user submits the form, it should block the submission (in the case where it finds that the email address is not in the database).
If the user submits the form before the remote query finishes, the remote query validation rule should be ignored (so that there is no delay--the server-side validation will catch that the user doesn't exist).
Thoughts?
function checkEmail(){
$("#email").removeClass('email'); // this stops validation during ajax
//might want to add a loading image to let user know
$.ajax({
type: //type
url: //url to check email,
data: //email to check,
success: function (msg) {
$("#email").addClass('email'); //turns validation back on
//take away loading image
if (msg.GoodEmail != "GoodEmail" ) { //however you check for existing email
$("#email").addClass('error'); //forces failed validation
}
}
});
}
This is an example using jquery's ajax , with this you can handle events before ajax , on success , on error , a little more control this way
I think I figured this out. Instead of using the "remote" option, I used addMethod to create a rule that I call "isExtrabuxMember". I also created some global variables and used ajax bound to the change of the #email field to check whether the provided email address belonged to any existing Extrabux member.
Please comment if this helps you or if you have better ideas.
I now have this above the "validate" plugin call:
jQuery.validator.addMethod("isExtrabuxMember", function(value, element) {
var emailRemoteFuncResult = checkSigninEmailAddressResult === null ? true : checkSigninEmailAddressResult;
return emailRemoteFuncResult;
});
var checkSigninEmailAddressResult = null;
var emailXhrCheck;
$('#email').bind('change keyup', function(){
checkSigninEmailAddressResult = null;
if(emailXhrCheck){
emailXhrCheck.abort();
}
emailXhrCheck = $.ajax({
url: '/users/check-signin-email-address',
type: "post",
async: true,
data: {
emailAddress: function() {
return $("#email").val();
}
},
success: function(data){
checkSigninEmailAddressResult = data;
$("#email").valid();
}
});
});
$('#loginForm').submit(function(){
if(emailXhrCheck){
emailXhrCheck.abort();
}
});
Then within the "validate" plugin call:
rules: {
email: {
required: true,
email: true,
isExtrabuxMember: true
},
password: {
required: true,
minlength: 4
}
},
messages: {
email: {
isExtrabuxMember: function(){
var currentEmail = $('#email').val();
return $.validator.format('<b>{0}<\/b> does not yet have an Extrabux account. <a href="\/users\/register?emailAddress={0}">Sign up?<\/a>', currentEmail);
}
},
password: {
required: "Oops, you forgot to enter your password!"
}
}

Cannot get Facebook friends array on IE, but working on other browsers

This function is working on Chrome and Firefox but not on IE9, where errorHandler is logging this error message:
ERROR: getFriendsArray {"readyState":0,"status":0,"statusText":"No Transport"}
getUserAccessToken() is returning the right value. Any ideas what could it be, that only affects IE?
EDIT: seems that https://graph.facebook.com/me/friends directly on IE browser returns HTTP 400 error.
function getFriendsArray() {
var friendsArray = [];
$.ajax({
url: 'https://graph.facebook.com/me/friends',
data: {
access_token: getUserAccessToken(),
fields: 'name,picture,gender'
},
dataType: 'json',
cache: true,
async: false,
success: function(response) {
var data = '';
$.each(response.data, function(indice, item) {
friendsArray.push(item);
});
},
error: function(err) {
errorHandler('getFriendsArray', JSON.stringify(err));
}
});
return friendsArray.sort(sortByName);
}
$.ajax only supports using XMLHttpRequest or XDomainRequest (IE), the latter only supporting a few scenarios, and requiring that your page is SSL if the requested resource is SSL.
Instead, use FB.api, which handles this and much more, ensuring that the call makes it through, either by using JSONP, XHR, XDomainRequest, or Flash.

Sencha Touch AJAX Request Issue: ReferenceError: Can't find variable: request

We are building an application using Sencha Touch 1.1 and PhoneGap 1.3.0 for deployment to iOS.
Our app makes several AJAX requests to authenticate a user and retrieve data from the server. All of our requests execute correctly with the exception of attempting to authenticate using invalid credentials.
I am using Weinre to debug the app running in the iOS simulator.
In the Network pane the request hangs on "Pending", and in the console I receive the following error:
error occurred: undefined:[unknown lineno]: ReferenceError: Can't find variable: request
this error appears when the timeout value has been reached.
Here's the code for my controller:
Ext.regController('Login', {
login: function(options)
{
var loader = this.application.viewport.query('#loader')[0];
loader.show();
var string = options.user + ":" + options.pass;
var encodedString = Ext.util.Base64.encode(string) + "==";
Ext.Ajax.defaultHeaders = { Authorization: "Basic " + encodedString};
Ext.Ajax.request({
url: 'http://test.com/login.do',
method: 'POST',
timeout: 5000,
scope: this,
callback: function (options, success, response) {
if (success){
buildingStore.load({
callback: function (){
Ext.redirect('Main/loggedIn');
loader.hide();
}
});
Ext.redirect('Main/loggedIn');
}
else {
alert("failed");
console.log(response.status);
loader.hide();
var loginFailure = new Ext.Panel ({
floating: true,
centered: true,
floating: true,
modal: true,
layout: 'fit',
cls: 'loginError',
html: '<h12>Login was unsuccessful.<br>Please try again.</h12>',
});
loginFailure.show();
}
}
});
Ext.Ajax.on({
requesterror: function(conn, response, options, e){
alert("error");
},
requestexception: function(conn, response, options, e){
alert("exception");
}
});
},
});
and a screenshot of Weinre:
Thanks for your help!
Kevin
Upgrading to sencha touch 1.1 fixes this issue. Credit to #kev_additct. Just putting it in an answer rather than a comment where it already is

jquery validation - waiting for remote check to complete

When I call $("form").valid() I have a remote validation check hooked up (which all works well) however if all other fields are valid the form passes validation because the remote check hasn't return a response "quick enough".
Is there a way to either force jquery validation to wait for any remote checks to be completed or hook into the complete event of the remote check call?
I am currently using the remote validator built into the jQuery validation framework http://docs.jquery.com/Plugins/Validation/Methods/remote
one way is to introduce a variable that will be set to true when the remote call comes back
var remote_complete = false;
$.ajax({
url: "test.html",
success: function(){
remote_complete = true;
}
});
while (remote_complete == false)
{
// loop until remote_complete = true;
}
Another way is to validate your form after remote validation completes
$.ajax({
url: "test.html",
success: function(){
validate_form();
}
});
you can add a custom rule and in that custom rule you can make the ajax call.
Please check the SO post here for creating custom rules.
In that function make the ajax call.
Well, if you've setup all your rules correctly, then this shouldn't be a problem. See this demo where email is being validated remotely and the validation doesn't pass until the check comes back.
Can you post a jsfiddle that highlights your problem?
http://gloryplus.com/index.php?route=product/product&path=82&product_id=173
rules: {
name: {
minlength: 2,
required: true
},
email: {
required: true,
email: true
},
subject: {
minlength: 2,
required: true
},
message: {
minlength: 2,
required: true
}
},
highlight: function(label) {
$(label).closest('.control-group').addClass('error');
},
success: function(label) {
label
.text('OK!').addClass('valid')
.closest('.control-group').addClass('success');
}

Resources