bootstrap min. js is running the request 2 times and hang until not refresh the page - ruby-on-rails

[my ajax]
when i run the code the bootstrap.min.js will run but there two isssues comes in that 1. that is hit the request two time and 2. that after the 2 hit it will have to close the popup and hang the page until it refresh the page
function add_edit_party(){
var place_id = myFunction();
var $j = jQuery.noConflict();
var estimated_wait = 0;
var no_sms = "";
var is_hd = 0;
$j('.alert-danger').removeClass('show').addClass('hide');
if($j('#'+place_id+'_wl_phone').val()){
phone_length = $j('#'+place_id+'_wl_phone').val().length;
if (phone_length!=10){
$j('#'+place_id+'_wl_phone').next().removeClass('hide').addClass('show');
return false;
}
}
if(!validateEmail($j('#'+place_id+'_wl_email').val())){
$j('#'+place_id+'_wl_email').next().removeClass('hide').addClass('show');
return false;
}
if($j('#'+place_id+'_wl_unknown_persons').val()==""){
$j('#'+place_id+'_wl_unknown_persons').next().removeClass('hide').addClass('show');
return false;
}
if($j('#'+place_id+'_wl_estimated_wait').val()=="" && $j('#serve_time').val() == "1"){
$j('#'+place_id+'_wl_estimated_wait').next().removeClass('hide').addClass('show');
return false;
}
if ($j('#serve_time').val() == "0"){
estimated_wait = 0;
}
if ($j('#serve_time').val() == "1")
estimated_wait = $j('#'+place_id+'_wl_estimated_wait').val();
}
place_party_req_id = "";
if($j('#place_party_req_id').val()){
place_party_req_id = $j('#place_party_req_id').val();
}
request_param = {
place_id : place_id,
color_update_at: "3",
name : $j('#'+place_id+'_wl_name').val(),
notes : $j('#'+place_id+'_wl_notes').val(),
phone : "0"+$j('#'+place_id+'_wl_phone').val(),
email : $j('#'+place_id+'_wl_email').val(),
unknown_persons : $j('#'+place_id+'_party_size').val(),
size : $j('#'+place_id+'_party_size').val(),
estimated_wait : estimated_wait,
color_status: 3,
party_request_id: place_party_req_id,
authenticity_token : window._token
};
$j(".loading").show();
var url='/add_party/'+place_id
$j.ajax({
type: "POST",
url: url,
async: false,
data: request_param,
dataType : 'json',
success: function(result){
if(result['party_id']){
if($j('#place_party_req_id').val()){
edit_party_request($j('#place_party_req_id').val(),'accepted');
$j('#place_party_req_id').val("");
}
party_id = result['party_id'];
if(estimated_wait=='0'){
seat_party(party_id);
return;
}
refresh_wl();
setTimeout(function(){ jQuery(".loading").hide(); }, 600);
$j('#myModal').modal('hide');
$j('.nav-tabs a:first').tab('show');
}
},
error: function(msg){
//alert("Something went wrong...");
}
});
return false;
}

see whether you have added multiple js files in your layout file.It may be application.js or jquery.js.Many a times we add js file in the view as well as in the layout as well...
Moreover there can be a chance where any custom js in application.js will also having a duplicate file already included in application.js file.Please check

Related

indexeddb on IOS devices

I have a problem with an indexeddb query with index when running on IOS devices.
$.indexedDB(dbName).objectStore(tablename).index("INDICE").each(function(itemLocal) {
itemLocal.delete();
}, [VALORINDICE]).then(function() {
callback();
}, function() {
console.log("error");
});
The problem is if there is more than one record that matches the index, it does not eliminate them, it eliminates the first one and leaves. But if for example I put console.log (itemLocal) instead of itemLocal.delete() if it shows all those that match the index. Any suggestions of something that may be leaking?
I have tried with this code and I get the same error(code without api jquery)
var request = indexedDB.open(DATABASE_NAME);
request.onsuccess = function(event) {
var db = request.result;
var transaction = db.transaction(["TABLE"], "readwrite");
var table = transaction.objectStore("TABLE");
var index = table.index("INDEX");
var req = index.openCursor();
req.onsuccess = function() {
var cursor = req.result;
if (cursor) {
console.info(cursor.value);
cursor["delete"]();
cursor["continue"]();
}
};
req.onerror = function(e) {
console.error(e, req);
};
};
request.onerror = function(e) {
console.error(e, request);
};

unable to upload files using UploadCollection in SAPUI5

I am receiving 403 Forbidden error when I try to upload a file using UploadCollection.
The code in my view.js is:
var oOUpload = new sap.m.UploadCollection("oinspupload",{
multiple : true,
sameFilenameAllowed : true,
instantUpload : false,
uploadUrl : "/sap/opu/odata/sap/ZACCBILL_SRV/FileSet",
/* uploadComplete : function(oEvent){
//alert ("File Uploaded successfully");
// oController.fileUpload(oEvent);
}, */
fileDeleted : function(oEvent){
oController.fileDelete(oEvent);
},
fileRenamed : function(oEvent){
alert ("File renamed successfully");
//oController.fileRename(oEvent);
}
});
The code in my view.controller is:
OData.request({
requestUri : sServiceUrl,
method : "GET",
headers :
{
"X-Requested-With" : "XMLHttpRequest",
"Content-Type" : "application/atom+xml",
"DataServiceVersion" : "2.0",
"Authorization" : AuthToken,
"X-CSRF-Token" : "Fetch"
}
},
function(data, response) {
debugger;
if(sap.ui.Device.browser.chrome || sap.ui.Device.browser.msie || sap.ui.Device.browser.safari){
header_xcsrf_token = response.headers['x-csrf-token'];
}else if(sap.ui.Device.browser.firefox){
header_xcsrf_token = response.headers['X-CSRF-Token'];
}
xcsrf_token_ref.header_xcsrf_token = header_xcsrf_token;
csrftoken = xcsrf_token_ref.header_xcsrf_token;
debugger;
uploadattachments(xcsrf_token_ref);
},
function(err) {
debugger;
var request = err.request; // the request that was sent.
var response = err.response; // the response that was received.
alert("Error in Get -- Request "
+ request + " Response "
+ response);
});
function uploadattachments(token){
debugger;
var uploader;
uploader= sap.ui.getCore().byId("oinspupload");
var aItems = uploader.getItems();
var slug, sequence;
for (i = 0; i < aItems.length; i++) {
sequence = i + 1;
slug = "CONTAINERID1000040100;STATUSIB;SEQUENCE" + sequence+ ";FILENAMECamera.png" ;
uploader.addHeaderParameter(new sap.m.UploadCollectionParameter({name: "slug", value: slug }));
debugger;
uploader.addHeaderParameter(new sap.m.UploadCollectionParameter({name: "X-Csrf-Token", value: token.header_xcsrf_token }));
uploader.upload();
}
}
Please don't mind the missing parenthesis as the code above is not the complete code.
The above code works fine with fileuploader. I am sure the issue is that the uploadcollection is not passing the fetched CSRF Token properly but I am unable to figure out what's wrong.
Finally Found the solution myself with the help of the following blog
http://scn.sap.com/community/developer-center/front-end/blog/2016/03/29/using-the-uploadcollection-to-uploaddownload-archivelink-files-via-gateway
Upload Collection only works with instantUpload as true and does not work with instantUpload as false as of version 1.32.X. UploadCollection is Buggy and is yet to be rectified in the future versions. Also the CSRF token validation needs to be done in the change event. Below is the code:
View.js
var oOUpload = new sap.m.UploadCollection("oinspupload",{
multiple : true,
sameFilenameAllowed : false,
instantUpload : true,
uploadUrl : "/sap/opu/odata/sap/ZACCBILL_SRV/FileSet",
fileDeleted : function(oEvent){
oController.fileDelete(oEvent);
},
fileRenamed : function(oEvent){
alert ("File renamed successfully");
},
change: function(oEvent) {
debugger;
csrftoken = xcsrf_token_ref.header_xcsrf_token;
var oUploadCollection = oEvent.getSource();
var oCustomerHeaderToken = new sap.m.UploadCollectionParameter({
name : "x-csrf-token",
value : csrftoken
});
oUploadCollection.addHeaderParameter(oCustomerHeaderToken);
},
});
All header params must be added from "change" function. If you add it after, they won't be recieved on Backend.
Also, It is possible upload files with instantUpload=false. You only need bind uploadUrl parameter with a paremeter of view's model, and dynamically, it will change when you change the url.
For example:
View element:
<UploadCollection instantUpload="false" uploadUrl="{ResourceModel>/sServiceUrl}"/>
Controller onInitFunction:
var resourcemodel = this.getOwnerComponent().getModel("ZGW_PURCHREQ_01_SRV");
var oDataResource = {
sServiceUrl: resourcemodel.sServiceUrl + "/FileSet"
};
var jsonResource = new JSONModel(oDataResource);
this.getView().setModel(jsonResource, "ResourceModel");
When you fire upload, it will send a petition to uploadUrl defined on "sServiceUrl" of "ResourceModel".
Other option is set upload url and/or new header params before fire upload function with:
var oUploadCollection = this.getView().byId("UploadCollection");
var sServiceUrl = resourcemodel.sServiceUrl + "/FileSet";
var headerBanfn = null;
for (var i = 0; i < oUploadCollection._aFileUploadersForPendingUpload.length; i++) {
headerBanfn = new sap.ui.unified.FileUploaderParameter({
name: "banfn",
value: "123456"
});
oUploadCollection._aFileUploadersForPendingUpload[i].setUploadUrl(sServiceUrl);
oUploadCollection._aFileUploadersForPendingUpload[i].addHeaderParameter(headerBanfn);
}
oUploadCollection.upload();
I hope it was useful.

addEventListener error in IE8

I'm getting an error message in ie8: Object doesn't support property or method 'addEventListener'. How can I fix this? I've seen adding an else statementand changing addEventListener to attachEvent. However, I am a bit green in the land of js and not sure where that should go, I did try a few ways.
$(document).ready(function() {
// Off canvas menu
var $slider = document.querySelector('#slider');
var $toggle = document.querySelector('.toggle-nav');
var $toggle2 = document.querySelector('nav .toggle-nav');
// var $link = document.querySelector('.link > a');
$toggle.addEventListener('click', function() {
var isOpen = $slider.classList.contains('slide-in');
$slider.setAttribute('class', isOpen ? 'slide-out' : 'slide-in');
$('#slider').animate({'right': '100%'}, 400);
});
$toggle2.addEventListener('click', function() {
var isOpen = $slider.classList.contains('slide-in');
$slider.setAttribute('class', isOpen ? 'slide-out' : 'slide-in');
$('#slider').animate({'right': '0'}, 300);
});
var toggleDataAttr = function(parentElem, toggleElem, opt1, opt2, dataAttr) {
var toggleElem = parentElem.querySelector(toggleElem);
toggleElem.setAttribute(dataAttr, toggleElem.getAttribute(dataAttr) === opt1 ? opt2 : opt1);
};
var toggle_li = document.querySelectorAll('li');
for (var i = 0; i < toggle_li.length; i++) {
toggle_li[i].onclick = function() {
toggleDataAttr(this, '.toggleContent', 'closed', 'open', 'data-state');
toggleDataAttr(this, '.toggleIcon', 'down', 'up', 'data-icon');
};
}
});
addEventListener() is not supported in IE8 and lower (more info here: http://www.w3schools.com/jsref/met_document_addeventlistener.asp), instead you need to use attachEvent() in these browsers.
You can use it like this:
if(element.addEventListener()) {
element.addEventListener('click', myFunction(), true);
} else if(element.attachEvent()) {
element.attachEvent('click', myFunction());
}
This way to do it makes it multi-browser compatible.

Select2 - adding custom choice in single selection mode (tags:false)

Is it possible to setup select2 control to accept custom choice
in single selection mode (tags:false) ?
When typing your choice in the search box instead of seeing "No results found",
just see what you typing in and select it by click or pressing enter.
Well - I finally found solution myself.
I override original SelectAdapter adding new choice every time you type in
and delete previous temporary choices:
$.fn.select2.amd.require(['select2/data/select', 'select2/utils'],
function (SelectAdapter, Utils) {
function XSelectAdapter($element, options) {
XSelectAdapter.__super__.constructor.call(this, $element, options);
}
Utils.Extend(XSelectAdapter, SelectAdapter);
XSelectAdapter.prototype.query = function (params, callback) {
var data = [];
var self = this;
var $options = this.$element.children();
var have_exact_match = false;
$options.each(function () {
var $option = $(this);
if (!$option.is('option') && !$option.is('optgroup')) {
return;
}
var option = self.item($option);
if (option.xtemp === true) {
$(this).remove(); // previously typed-in choice - delete
return;
}
if (option.term === params.term) {
have_exact_match = true; // will not choice if have exact match
}
var matches = self.matches(params, option);
if (matches !== null) {
data.push(matches);
}
});
if (!have_exact_match) {
self.addOptions(this.option({selected: false, id: params.term, text: params.term, xtemp: true}));
data.push({selected: false, id: params.term, text: params.term});
}
callback({
results: data
});
};
$('#your_select2').select2({dataAdapter:XSelectAdapter});
});

JQuery dialog box issue in Internet Explorer

I am using a UI dialog box to display a message.
It works well in Firefox and Google Chrome. However, when I test in IE versions the dialog box doesn't open.
Can any one tell what real problem is?
I had pasted my code below:
function check_selected(c) {
var count = c - 1;
var radios = document.getElementsByName('plan');
for ( var i = 0; i < radios.length; i++) {
if (radios[i].disabled) {
if (radios[i].checked) { // checked
$('#planalert').dialog({
modal : true,
autoOpen : true,
title : "Plan",
width : 650,
height : 150,
show : "blind",
hide : "scale",
});
var c = 0;
} else {
var c = 1;
}
}
}
;
if (c == 0) {
return false;
} else {
return true;
}
}
Try removing the trailing comma from the options object you're passing dialog:
$('#planalert').dialog({
modal:true,
autoOpen: true,
title:"Plan",
width:650,
height:150,
show: "blind",
hide: "scale" // <-----
});
Internet Explorer will choke on the extra comma, while other browsers may not.
Also, remove the semicolon (;) at the end of the for loop ending brace:
for (var i = 0; i < radios.length; i++) {
/* snip */
} // <--- semicolon not necessary
Additionally, you are attempting to define c multiple times inside of your function. You are passing it in to the function so your var c = ... statements actually aren't having the effect you intend. You should either use another variable (which I would recommend rather than mutating the parameter you are passed), or remove the var statements from inside the if block.
Additionally, your loop is really only setting c for the last, disabled radio button. Is this what you intended?
Anyway, here is how I would re-write it (without attempting to fix the logical error above). Be sure to use tools like JsHint to check your JavaScript for probems:
function check_selected(c){
var count=c-1;
var radios = document.getElementsByName('plan');
var isChecked = 0;
for (var i = 0; i < radios.length; i++) {
if (radios[i].disabled) {
if (radios[i].checked){ // checked
$('#planalert').dialog({
modal:true,
autoOpen: true,
title:"Plan",
width:650,
height:150,
show: "blind",
hide: "scale"
});
isChecked = 0;
} else{
isChecked = 1;
}
}
}
return isChecked;
}

Resources