Jquery taking much time to run in mobile chrome - javascript

i have a website its working fine in desktop but when i run it into mobile Browser specially chrome. and adding books to wishlist's it takes about 1 minute to process. its working great in Firefox.
website link - bookwise.co.in
my code is :
class BaseClass {
constructor() {
if (this.constructor === BaseClass) {
throw new Error("Can't instantiate abstract class!");
}
}
post(data, success, failure) {
var endpoint = this.endpoint;
showLoader();
$.ajax({
url: SITE_URL + endpoint,
data: data,
type: 'POST',
headers: {
'X-API-KEY': globalUser.accessToken
},
success: function(data) {
hideLoader();
if (typeof(success) == 'function') {
success(data)
}
},
error: function(err) {
hideLoader();
if (typeof(failure) == 'function') {
failure(err)
}
}
});
}
delete(data, success, failure) {
var endpoint = this.endpoint;
showLoader();
$.ajax({
url: SITE_URL + endpoint,
data: data,
type: 'DELETE',
headers: {
'X-API-KEY': globalUser.accessToken
},
success: function(data) {
hideLoader();
if (typeof(success) == 'function') {
success(data)
}
},
error: function(err) {
hideLoader();
if (typeof(failure) == 'function') {
failure(err)
}
}
});
}
}
class Wishlist extends BaseClass {
constructor(endpoint) {
super();
this.endpoint = endpoint ? endpoint : 'wishlist';
}
}
function bindWishListToggle() {
$(".wishlist-toggle-btn").unbind('click').bind('click', function() {
var id = $(this).parents(".similar-book-item").data("id");
var isWishList = $(this).data("wishlist");
var _this = this;
var wishlist = new Wishlist();
var successCb = function() {
$(_this).find("img").attr("src", isWishList ? "assets/images/heartempty.png" : "assets/images/heartfull.png");
$(_this).data("wishlist", !isWishList);
};
var failCB = function(data) {
if (data.status == 401)
$("#myModal").modal();
}
if (isWishList) {
wishlist.delete({
bookId: id
}, successCb, failCB);
} else {
wishlist.post({
bookId: id
}, successCb, failCB);
}
});
}
above are my code i don't know why its happening only in chrome.

Related

How to avoid repeating code in if/else statement inside AJAX

I'm trying to do if/else inside Ajax , but as you can see in my script I'm repeating my code and i think it is better way do archive this in one line or doing if/else before Ajax and to be honest i don't know how exactly should i do Can anyone please help me or point me in the right direction!
Thanks in advance :)
function RMAfunction() {
var model = {
Serienummer: $("#notavailable").val(),
SelectedSerieText: $("#ddlSerial option:selected").text(),
Kundenavn: $("#Kundenavn").val(),
Ordrenummer: $("#Ordrenummer").val()
}
if (model.Serienummer === 'not available') {
$.ajax({
type: 'POST',
url: '#Url.Action("ProcessRequestRMA", "Account")',
dataType: 'json',
data: {
Serienummer: model.Serienummer,
Kundenavn: model.Kundenavn,
Ordrenummer: model.Ordrenummer,
},
success: function (status) {
if (status) {
status.Serienummer = model.Serienummer;
status.Kundenavn = model.Kundenavn;
status.Ordrenummer = model.Ordrenummer;
}
else {
alert("Something Wrong");
}
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
else {
$.ajax({
type: 'POST',
url: '#Url.Action("ProcessRequestRMA", "Account")',
dataType: 'json',
data: {
Serienummer: model.SelectedSerieText,
Kundenavn: model.Kundenavn,
Ordrenummer: model.Ordrenummer
},
success: function (status) {
if (status) {
status.Serienummer = model.SelectedSerieText;
status.Kundenavn = model.Kundenavn;
status.Ordrenummer = model.Ordrenummer;
}
else {
alert("Something Wrong");
}
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
}
The only change is whether you use the Serienummer or SelectedSerieText in the properties of model based on the original value of Serienummer. As such, you can just use a ternary expression where that value is used. Try this:
function RMAfunction() {
var model = {
Serienummer: $("#notavailable").val(),
SelectedSerieText: $("#ddlSerial option:selected").text(),
Kundenavn: $("#Kundenavn").val(),
Ordrenummer: $("#Ordrenummer").val()
}
var hasSerieNummer = model.Serienummer === 'not available';
$.ajax({
type: 'POST',
url: '#Url.Action("ProcessRequestRMA", "Account")',
dataType: 'json',
data: {
Serienummer: hasSerieNummer ? model.Serienummer : model.SelectedSerieText,
Kundenavn: model.Kundenavn,
Ordrenummer: model.Ordrenummer,
},
success: function(status) {
if (status) {
status.Serienummer = hasSerieNummer ? model.Serienummer : model.SelectedSerieText;
status.Kundenavn = model.Kundenavn;
status.Ordrenummer = model.Ordrenummer;
} else {
alert("Something Wrong");
}
},
error: function() {
console.log('something went wrong - debug it!');
}
});
}
This could potentially be further reduced by using a function in the model object to contain the logic which determines which identifier to return:
function RMAfunction() {
var model = {
Serienummer: $("#notavailable").val(),
SelectedSerieText: $("#ddlSerial option:selected").text(),
Kundenavn: $("#Kundenavn").val(),
Ordrenummer: $("#Ordrenummer").val(),
GetIdentifier: function() {
return this.Serienummer === 'not available' ? this.Serienummer : this.SelectedSerieText;
}
}
$.ajax({
type: 'POST',
url: '#Url.Action("ProcessRequestRMA", "Account")',
dataType: 'json',
data: {
Serienummer: model.GetIdentifier(), // usage here
Kundenavn: model.Kundenavn,
Ordrenummer: model.Ordrenummer,
},
success: function(status) {
if (status) {
status.Serienummer = model.GetIdentifier(); // and here
status.Kundenavn = model.Kundenavn;
status.Ordrenummer = model.Ordrenummer;
} else {
alert("Something Wrong");
}
},
error: function() {
console.log('something went wrong - debug it!');
}
});
}
Try this also correct,
var model = {
Serienummer: $("#notavailable").val(),
SelectedSerieText: $("#ddlSerial option:selected").text(),
Kundenavn: $("#Kundenavn").val(),
Ordrenummer: $("#Ordrenummer").val()
}
if (model.Serienummer === 'not available') {
var data = {
Serienummer: model.Serienummer,
Kundenavn: model.Kundenavn,
Ordrenummer: model.Ordrenummer,
};
}else{
var data = {
Serienummer: model.SelectedSerieText,
Kundenavn: model.Kundenavn,
Ordrenummer: model.Ordrenummer
};
}
$.ajax({
type: 'POST',
url: '#Url.Action("ProcessRequestRMA", "Account")',
dataType: 'json',
data: JSON.stringify(data);
success: function (status) {
if (status) {
if (model.Serienummer === 'not available') {
status.Serienummer = model.Serienummer;
}else{
status.Serienummer = model.SelectedSerieText;
}
status.Kundenavn = model.Kundenavn;
status.Ordrenummer = model.Ordrenummer;
}
else {
alert("Something Wrong");
}
},
error: function () {
console.log('something went wrong - debug it!');
}
});

jquery triggerhandler not being called

the trigger below never call. The alert on call never pop up.
It was triggered by these statements. See second block.
$('#sCart').trigger('add', {
stock_id: stock_id
$('#sCart').on('add', function(event, data) {
alert('on add');
$.ajax({
url: '$subCartUpdate'.replace('$tokenHolder', Math.random()),
type: 'GET',
dataType: 'json',
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader('if-Modified-Since', '0');
},
success: function(success, statusText, jqXHR) {
alert(statusText);
$('#sCart').trigger('clear');
$('#sCart').html(success.subCart);
if(timerId === null) {
$('#sCart').queue('add', function() {
$(this).fadeIn(function() {
$(this).dequeue('add');
});
});
} else {
clearTimeout(timerId);
}
timerId = setTimeout(function() {
$('#sCart').fadeOut();
timerId = null;
}, 7000);
$('#sCart').queue('add', function() {
var updatedItemSelector = '#stock_'+data.stock_id;
var updatedItem = $(updatedItemSelector).fadeOut(500);
updatedItem.fadeIn(2000, function() {
$(this).dequeue('add');
});
});
if(success.reservedTimeStamp) {
$('#sCartTimer').trigger('start', {timer: success.reservedTimeStamp});
}
$('#sCart').dequeue('add');
},
error: function(jqXHR, statusText, errors) {
var i = 0;
}
});
});
It was triggered from code below.
$.ajax({
url: '$addUrl',
type: 'POST',
data: {
id: stock_id,
amount: amount
},
success: function(success, statusText, jqXHR) {
alert(statusText);
if(success.reload) {
location.reload(true);
} else if(success.redirect) {
location.href = success.redirect;
} else {
$('#sCart').trigger('add', {
stock_id: stock_id
});
$('.product-amount').val(1);
//$('.type .selected').first().trigger('click');
$('.stock_left').trigger('update');
$('.purchase').trigger('unblock');
}
},
error: function(jqXHR, statusText, error) {
var i = 0;
}
});

Want to get an access_token from Twitter Oauth api using oauth.js plugin

I am trying to get a Twitter access token from their oauth api. The plugin I am using is this https://code.google.com/p/oauth/source/browse/#svn%2Fcode%2Fjavascript. So far I only get "401 failed to validate signature and token".
Strange thing is that my ajax call becomes 'GET' request even though I set type:'POST'. Seems like jquery is changing the type from POST to GET. I don't know why it does that. I am running it on my Mac. I appreciate your help/hints/suggestions/advises. Thanks!
$(function() {
function myCallback(resp) {
console.log(resp);
}
var TwitterAPI;
TwitterAPI = (function() {
var consumer_key = null;
var consumer_secret = null;
function TwitterAPI(cons_key, cons_secret) {
this.consumer_key = cons_key;
this.consumer_secret = cons_secret;
}
TwitterAPI.prototype._url = function (data) {
if (typeof data == 'array') {
return array_map([ // TODO
this, '_url'], data);
} else if ((/boolean|number|string/).test(typeof data)) {
return encodeURIComponent(data).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
} else {
return '';
}
}
TwitterAPI.prototype.myCallback = function(resp) {
console.log(resp);
}
TwitterAPI.prototype.getRequestToken = function() {
var accessor = {
consumerSecret: this.consumer_secret, //this.consumer.consumerSecret,
tokenSecret: ''
};
var message = {
method: "POST",
action: "https://api.twitter.com/oauth/request_token",
parameters: {
oauth_signature_method: "HMAC-SHA1",
oauth_consumer_key: this.consumer_key, //this.consumer.consumerKey
oauth_callback: this._url("http://127.0.0.1/foobar/libs/oauth/wtf.html"),
}
};
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
var target = OAuth.addToURL(message.action, message.parameters);
message.parameters.oauth_signature = this._url(message.parameters.oauth_signature);
console.log(message.parameters);
$.ajax("https://api.twitter.com/oauth/request_token",
{ url: "https://api.twitter.com/oauth/request_token",
type: 'POST',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: "myCallback",
data: message.parameters,
success: function(data, textResp, xhr) {
console.log(data);
},
error: function(xhr, text, err) {
console.log(text);
}
});
};
return TwitterAPI;
})();
api = new TwitterAPI(key, secret);
$('button#request').on('click', function(e) {
e.stopPropagation();
api.getRequestToken();
});

Javascript OOP inheritance not working

So I am writing something using augment for inheritance and for some reason I can run this.setButtons(type) and console.log(this.buttons) in that method, but when I run my this.getButtons() it comes back as undefined, even though getButtons just returns this.buttons. Any help would be greately appreciated. I will post up all the code I have so far, because maybe I'm not inheriting properly. Thank you in advance.
var ContextMixin = function () {};
ContextMixin.prototype = {
createElements: function (el, mode, type) {
var m;
if (mode == 'exact') {
$("#" + el).append("<ul id='contextmenu'>");
} else {
$(el).each(function () {
m = $(this).append("<ul id='contextmenu'>");
});
$('body').append(m);
}
$("#contextmenu").css({
'position': 'absolute',
top: 13,
left: 13
});
var new_buttons = this.getButtons();
$.each(this.buttons['buttons'], function () {
m.append("<li id='" + this + "'>" + this + "</li>");
});
},
attachEvents: function () {
functions = this.getFunctions(type);
buttons = this.getButtons();
for (index in buttons['buttons']) {
addEvent(buttons['buttons'][index], this.functions[index][0], this.functions[index][1]);
};
},
setFunctions: function (type) {
var callback = {
success: function (msg) {
this.functions = msg;
},
failure: function () {
alert('Error getting functions')
}
};
$.ajax({
type: 'GET',
url: 'function_list.php?type=' + type,
success: function (msg) {
this.functions = msg;
}
});
},
getFunctions: function () {
return this.functions;
},
setType: function (value) {
this.type = value;
},
getType: function () {
return this.type;
},
setButtons: function (type) {
$.ajax({
type: 'GET',
url: 'button_list.php?type=' + type,
success: function (reply) {
this.buttons = reply;
}
});
},
getButtons: function () {
return this.buttons;
}
}
function createMenu(el, type, mode) {
this.setButtons(type);
this.setFunctions(type);
this.createElements(el, mode, type);
}
augment(createMenu, ContextMixin);
function augment(receivingClass, givingClass) {
if (arguments[2]) { //Only give certain methods.
for (var i = 2, len = arguments.length; i < len; i++) {
receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
}
} else { //Give all methods
for (methodName in givingClass.prototype) {
if (!receivingClass.prototype[methodName]) {
receivingClass.prototype[methodName] = givingClass.prototype[methodName];
}
}
}
}
Because this in the callback to the AJAX request is not your object.
Here's a common fix...
setButtons: function(type) {
var self = this; // keep a reference to this
$.ajax({
type: 'GET',
url: 'button_list.php?type=' + type,
success: function(reply) {
self.buttons = reply; // use the reference here
}
});
},
...but a better fix is to use the context: property of the $.ajax request...
setButtons: function(type) {
$.ajax({
type: 'GET',
context: this, // set the context of the callback functions
url: 'button_list.php?type=' + type,
success: function(reply) {
this.buttons = reply;
}
});
},
If you change
ContextMixin.prototype = {
createElements
to
ContextMixin.prototype.createElements
it should work.
this is not what you think it is in your ajax callback—instead of being your current object, it's actually the global object the XHR object. All your callback is doing is putting a buttons property onto the xhr object.
You need to save this before your function runs:
setButtons: function(type) {
var self = this;
$.ajax({
type: 'GET',
url: 'button_list.php?type=' + type,
success: function(reply) {
alert(reply);
self.buttons = reply;
}
});
},

How to use Jquery UI in my Custom Function? (Autocomplete)

I want to create a function to simplify configuration of jQuery UI AutoComplete. Here is my function code:
(function($) {
$.fn.myAutocomplete = function() {
var cache = {};
var dataUrl = args.dataUrl;
var dataSend = args.dataItem;
$.autocomplete({
source: function(request, response) {
if (cache.term == request.term && cache.content) {
response(cache.content);
}
if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(cache.content, function(value) {
return matcher.test(value.value)
}));
}
$.ajax({
url: dataUrl,
dataType: "json",
type: "POST",
data: dataSend,
success: function(data) {
cache.term = request.term;
cache.content = data;
response(data);
}
});
},
minLength: 2,
});
}
}) (jQuery);
but when I'm using this function like:
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { term: request.term, category: $("input#category").val() }
});
It's give me an error:
Uncaught ReferenceError: request is not defined
Perhaps the error is referring to request.term in
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { term: request.term, category: $("input#category").val() }
});
Sorry for the trouble, I'm not adept at using jquery. Here's the final working code.
(function($) {
$.fn.myAutocomplete = function(opt) {
var cache = {};
this.autocomplete({
source: function(request, response) {
if (cache.term == request.term && cache.content) {
response(cache.content);
}
if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(cache.content, function(value) {
return matcher.test(value.value)
}));
}
opt.dataSend.term = request.term;
$.ajax({
url: opt.dataUrl,
dataType: "json",
type: "POST",
data: opt.dataSend,
success: function(data) {
cache.term = request.term;
cache.content = data;
response(data);
}
});
},
minLength: 2,
});
return this;
}
}) (jQuery);
To use this function just write code like this:
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { category: $("input#category").val() }
});
Thanks Jeffery To for sharing with me to solve this problem.. ^_^

Categories