IE SCRIPT1002 match function returns error - javascript

I have a problem, my code works correctly in all browsers except IE.
IE returns me SCRIPT1002 Syntax error.
This line:
if(data.responseText.match(/Произошла.*/)) {
On next code:
localRequest: function(period, adapter, adapterType, errText){
let _this = this;
let iRow = rowInfo.iRow;
let aboutRow = rowInfo.aboutRow;
queryState = $.ajax({
type: 'get',
url: 'api/ds/cs',
dataType: 'json',
data: {
period: period,
adapter: adapter,
adapterType: adapterType,
errText: errText,
subject: iRow.value,
body: aboutRow.value
},
}).done(function (data) {
}).fail(function(data){
**if(data.responseText.match(/Произошла.*/)) {**
let errText = data.responseText.split(')',)
let errNumb = errText[0].split('(',)
alert('Не удалось сформировать проишествие: ' + errText[1] + ' №' + errNumb[1])
} else {
alert(data.responseText);
}
})
},

Related

When I edited directly in the grid instead of the modal at the right the filter never drops but when I edit in modal and save the filter dropped

class ProductInfoDetailsViewModel {
constructor(parent, productInfoWindowId, inventoryId, productId, supplierId, store) {
this._parent = parent;
this._created = false;
this._productInfoWindowId = productInfoWindowId;
this._inventoryId = inventoryId;
this._productId = productId;
this._supplierId = supplierId;
this._store = store;
}
_getMvvmData(inventoryId, productId, supplierId) {
return new Promise(function (resolve, reject) {
$.ajax({
url: '/ProductRowInfoSite/GetInventoryControl',
data: {
'inventoryId': inventoryId,
'productId': productId,
'supplierId': supplierId,
},
dataType: 'json', // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
success: function (result) {
resolve(result);
},
error: function (jqXHR, textStatus, errorThrown) {
reject([jqXHR, textStatus, errorThrown]);
},
type: 'POST',
});
});
}
async create() {
let self = this;
let userStore = new UserStore();
//productInfoTextGrid
this._productInfoDetailsViewModel = kendo.observable({
value: {},
close: function () {
//$("#generalProductInfoWindow").data("kendoWindow").close();
//closeWindow();
},
not: function (value) {
return !this.get(value);
},
save: function (e) {
let productInfoTextGrid = $(self._productInfoWindowId + ' ' + '#productInfoTextGrid').data('kendoGrid');
/* productInfoTextGrid.saveChanges();*/
let orderUnitsGrid = $(self._productInfoWindowId + ' ' + '#orderUnitsGrid').data('kendoGrid');
let selectedRefHistProd = null;
try {
selectedRefHistProd = this.get('value.SelectedRefHistProd').ProductId;
} catch (error) {
// may be set to null and that's fine/TK.
}
var data = {
ProductId: self._productId,
InventoryId: self._inventoryId,
SupplierId: self._supplierId,
Fmean: this.get('value.Fmean'),
FMAD: this.get('value.FMAD'),
FTrend: this.get('value.FTrend'),
SelectedSeason: this.get('value.SelectedSeason').SeasonId,
MinQuantity: this.get('value.MinQuantity'),
SelectedOrderUnitNo: this.get('value.SelectedOrderUnit').UnitNo,
LeadTime: this.get('value.LeadTime'),
LeadTimeDeviation: this.get('value.LeadTimeDeviation'),
StockKeepInterest: this.get('value.StockKeepInterest'),
MaxLevel: this.get('value.MaxLevel'),
MinLevel: this.get('value.MinLevel'),
OrderQuantity: this.get('value.OrderQuantity'),
ReorderLevel: this.get('value.ReorderLevel'),
EnableManualSetRAndQ: this.get('value.EnableManualSetRAndQ'),
ForecastError: this.get('value.ForecastError'),
SelectedHistoryProductId: selectedRefHistProd,
};
var dataString = JSON.stringify(data);
$.ajax({
url: '/ProductRowInfoSite/SaveParameters',
data: {
data: dataString,
},
dataType: 'json',
// "jsonp" is required for cross-domain requests; use "json" for same-domain requests
success: function (result) {
// notify the data source that the request succeeded
//options.success(result);
self._store.dispatch({ type: ActionProductInfoWindow.Saving });
self._parent.refreshParentGrids();
},
error: function (result) {
displayAjaxError(result);
},
type: 'POST',
});
let userStore = new UserStore();
let finishSaved = userStore.translatedString('SOLOSupplier.ProductInfoWindows.FinishSaved');
displaySuccess(finishSaved);
productInfoTextGrid.saveChanges();
orderUnitsGrid.saveChanges();
},
recalc: function () {
var validator = $(self._productInfoWindowId).kendoValidator().data('kendoValidator');
var a = validator.validate();
},
products: new kendo.data.DataSource({
type: 'json',
serverFiltering: true,
pageSize: 100,
transport: {
read: function (options) {
$.ajax({
url: '/ProductRowInfoSite/GetProductInventoryList',
data:
{
'inventoryId': self._inventoryId,
'productId': self._productId,
'data': options.data,
},
//"filter": filter
dataType: 'json', // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
success: function (result) {
// notify the data source that the request succeeded
options.success(result.HistProducts);
},
error: function (result) {
// notify the data source that the request failed
options.error(result);
},
type: 'POST',
});
},
parameterMap: function (data, type) {
return kendo.stringify($.extend({ 'text': $(data.filter.filters).get(0).value }, data));
},
},
}),
isEnabled: true,
onValidate: function (e) {
console.log('onValidate');
let maxLevel = this.get('value.MaxLevel');
let minLevel = this.get('value.MinLevel');
let userStore = new UserStore();
let validationErrorMessage = userStore.translatedString('uctrlSupplierWeb.MaxLevelMinLevelWarning');
let validator = $(self._productInfoWindowId).kendoValidator({
messages: {
custom: validationErrorMessage,
},
rules: {
custom: function (input) {
if (input.is('[name=minLevelParameter]') && input.val() === '') {
return true;
} else if (input.is('[name=minLevelParameter]') && input.val() !== '' && maxLevel !== null) {
return maxLevel > minLevel;
}
if (input.is('[name=maxLevelParameter]') && input.val() === '') {
return true;
} else if (input.is('[name=maxLevelParameter]') && input.val() !== '' && minLevel !== null) {
return maxLevel > minLevel;
} else {
return true;
}
},
},
},
).data('kendoValidator');
if (validator.validate() === true) {
self._store.dispatch({ type: ActionProductInfoWindow.Changing });
} else {
self._store.dispatch({ type: ActionProductInfoWindow.Cancelling });
}
},
});
kendo.bind($(self._productInfoWindowId + ' ' + '#tabInventoryControl'), self._productInfoDetailsViewModel);
try {
let result = await self._getMvvmData(self._inventoryId, self._productId, self._supplierId);
self._productInfoDetailsViewModel.products.read();
self._productInfoDetailsViewModel.set('value', result);
if (result.UnitsOnOrderAfterLeadtime === true) {
if ($(self._productInfoWindowId + ' ' + '#valueUnitsOnOrder').data('kendoNumericTextBox')) {
let widget = $(self._productInfoWindowId + ' ' + '#valueUnitsOnOrder').data('kendoNumericTextBox');
widget.wrapper.find('input').addClass('lightRed');
}
}
if ($(self._productInfoWindowId + ' ' + '#minLevelParameterId').data('kendoNumericTextBox')) {
$(self._productInfoWindowId + ' ' + '#minLevelParameterId')
.data('kendoNumericTextBox')
.min(result.MinLevelDefault);
}
if ($(self._productInfoWindowId + ' ' + '#maxLevelParameterId').data('kendoNumericTextBox')) {
$(self._productInfoWindowId + ' ' + '#maxLevelParameterId')
.data('kendoNumericTextBox')
.min(result.MinLevelDefault);
}
var validator = $(self._productInfoWindowId).kendoValidator().data('kendoValidator');
validator.validate();
let element = $(self._productInfoWindowId);
window.kendo.ui.progress(element, false);
} catch ([jqXHR, textStatus, errorThrown]) {
displayAjaxError(jqXHR, textStatus, errorThrown);
productInfoDetailsViewModel.set('value', []);
window.kendo.ui.progress(element, false);
}
}
}
Saving edits in product info modal deletes used filters on products grid
if (productNo === null) {
let newFilter = await self._getFilterOnlyFromLocalStorage();
let totalFilter = $(self._gridId).data("kendoGrid").dataSource.filter();
totalFilter.filters.push.apply(totalFilter.filters, newFilter.filters);
$(self._gridId).data("kendoGrid").dataSource.filter(newFilter);
self._setPredefinedFilterButton(self);
}
}

Create variable in one script and use in another script. JQuery/HTML/JS

How can I turn the results from Script 1, Name, Email, Teamsinto variables I can use in script 2?
I am making an API call to fetch some JSON I then want to use certain values as text in a message I then send to slack.
Example.
$('.Name').html(data.user.name); // Returns John
$('.Email').html(data.user.email); // Returns John#John.com
$('.Teams').html(data.user.teams[0].name); // Returns JohnsTeam
var text = 'Hello my name is $Name + my email is $Email + From $Teams'
Output = Hello my name is John my email is John#John.com From JohnsTeam
Script 1
function currentUrl() {
return new Promise(function (resolve) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
resolve(tabs[0].url)
})
})
}
function userIdfromUrl(url) {
var parts = url.split('/')
return parts[parts.length - 1]
}
var authorizationToken = "xxxxxxxxxxxxxxxxxxxxxxxxx";
function myapiRequest(endpoint, options) {
$.ajax($.extend({}, {
type: 'GET',
dataType: "json",
success: function(data) {
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Teams').html(data.user.teams[0].name);
},
url: "https://api.myapi.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.myapi+json;version=2"
}
},
options));
}
currentUrl()
.then(function (url) {
return userIdfromUrl(url)
})
.then(function (userId) {
return myapiRequest('users/' + userId + '?include%5B%5D=contact_methods&include%5B%5D=teams')
})
.then(function (data) {
console.log(data.user.name)
console.log(data.user.email)
console.log(data.user.teams[0].name)
})
Script 2
$(document).ready(function(){
$('#contact-submit').on('click',function(e){
e.preventDefault();
var url = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
var text = 'This is a message'
$.ajax({
data: 'payload=' + JSON.stringify({
"text": text // What I want to dynamically change
}),
dataType: 'json',
processData: false,
type: 'POST',
url: url
});
});
});
One great solution is to set the variable you get from the response in the HTML5 localstorage as follows:
Inside ur success:
success: function(data) {
localStorage.setItem("urdata",JSON.stringify(data));
}
In the other script, u can retrieve the data like this:
var data = localStorage.getItem("urdata"); data = JSON.parse(data);

Uncaught ReferenceError: _ is not defined at causesDataService.js:56 at causesDataService.js:64

A little background. I created an ASP.MVC web app using SQL database for users and "causes" which can be added to the web app. the following faults are coming up. I will faults and code.
Uncaught ReferenceError: _ is not defined
at causesDataService.js:56
at causesDataService.js:64
Uncaught ReferenceError: _ is not defined
at _mixins.js:2
at _mixins.js:7
Uncaught SyntaxError: Unexpected token )
Ok so now below code.....:::
MIXINS
var _mixIns = (function () {
_.mixin({
numberWithCommas: function (value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
});
}());
Cases Data Service::
var httpVerbs = {
POST:'POST',
PUT: 'PUT',
GET: 'GET',
DEL: 'DELETE'
};
var causesDataService = (function () {
var ds = {
commit: function (type, url, data) {
// Remove 'id' member to perpare for INSERT
if (type === httpVerbs.POST) {
delete data['id'];
}
return $.ajax({
type: type,
url: url,
data: data,
dataType: 'json'
});
},
del: function (data) {
return this.commit(httpVerbs.DEL, '/api/causes/' + data.id);
},
save: function (data) {
var
type = httpVerbs.POST,
url = '/api/causes';
if (data.id > 0) {
type = httpVerbs.PUT;
url += '/' + data.id;
}
return this.commit(type, url, data);
},
saveImage: function (data) {
return $.ajax({
type: httpVerbs.POST,
url: '/causes/uploadimage',
processData: false,
contentType: false,
data: data
});
},
};
_.bindAll(ds, 'del', 'save');
return {
save: ds.save,
saveLocal: ds.saveLocal,
saveImage: ds.saveImage,
}
})();

How To Test Unstructured Javascript/JQuery

I'm faced with trying to add testing to a lot of code like the following. I know I can use mockjax to to intercept the ajax calls. But I don't how to test the $.ajax({...}) calls in isolation. I'd appreciate a good refactoring approach, but I'd also like to avoid rewriting the entire app.
I've gotten a start in other areas using qunit, and I like it. But I'm open to other suggestions too. How should I proceed?
function submitSync(repFrom, continuousRep, storedPassword) {
// var repTriggered = false;
if (repFrom !== '' && (storedPassword !== null || storedPassword !== "")) {
var secureHome = "http://" + homeUser + ":" + storedPassword + "#" + window.location.host + "/" + homeURL;
var theSource = repFrom.split("/");
var singleDocumentReplication = (theSource.length === 5);
/*
* DELETE existing replications. There will normally be no more than 1.
* Do not delete replications for application updates.
* Note that we don't allow the user to create continuous replications.
*/
$.getJSON(currentHost + '/_replicator/_all_docs', function (data) {
$.each(data.rows, function (i, theRow) {
$.ajax({
url: currentHost + '/_replicator/' + theRow.id,
type: "GET",
dataType: 'json',
async: false,
contentType: "application/json",
success: function (doc) {
if (doc._id !== "_design/_replicator" && (typeof doc.source !== 'undefined' && !doc.source.match(onlineBase + '/' + remoteDB))) {
$.ajax({
url: "/_replicator/" + doc._id + "?rev=" + doc._rev,
type: "DELETE",
contentType: "application/json",
success: function () {
console.log('Replication deleted: ' + doc._id + '?rev=' + doc._rev);
}
});
}
}
});
});
});
if (singleDocumentReplication) {
var theDoc = theSource[4];
var repFromBase = repFrom.substr(0, repFrom.indexOf(theDoc) - 1);
$.ajax({
url: "/_replicator",
type: "POST",
data: JSON.stringify({ "source": repFromBase, "target": secureHome,
"userCtx": { "name": homeUser, "roles": ["_admin", homeUser] },
"continuous": continuousRep,
"retries_per_request": 10,
"http_connections": 3,
"doc_ids": [theDoc]
}),
contentType: "application/json",
error: function () {
dialog(libLang.noSync);
},
success: function (message) {
if (message) {
dialog(libLang.synced);
}
repTriggered = true;
}
});
} else {
$.ajax({
url: "/_replicator",
type: "POST",
data: JSON.stringify({ "source": repFrom, "target": secureHome,
"userCtx": { "name": homeUser, "roles": ["_admin", homeUser] },
"continuous": continuousRep,
"retries_per_request": 10,
"http_connections": 3
}),
contentType: "application/json",
error: function () {
dialog(libLang.noSync);
},
success: function (message) {
if (message) {
dialog(libLang.synced);
}
repTriggered = true;
}
});
}
}
}
Looks like you've got a ton of code duplication. My recommendation would be to put your ajax calls into modules and pass the $.ajax as a dependency.
So:
function myModule(ajaxDependency, anyOtherDependency) { }
This way in your unit test you simply check to make sure your dependecies behave a certain way. And it looks like it will eliminate all your DRY issues.

django request.user.is_authenticated() isn't returning true after page refresh (sometimes)

I have a registration form. After it is submitted, the page refreshes and I get some information back based on request.user. Sometimes request.user.is_authenticated() is returning True and everything works fine.... and sometimes False seemingly randomly.
I appreciate any insight into why this might be happening.
Registration form code
$('#reg_form').submit(function(e) {
e.preventDefault();
e.stopPropagation();
var serializedData = $(this).serializeArray();
var names = serializedData.map(function(r) {
return r.name;
});
var index_user = names.indexOf("regusername");
var index_pass = names.indexOf("regpassword1");
var index_email = names.indexOf("regemail");
var data2 = {};
data2["username"] = serializedData[index_user].value;
data2["password1"] = serializedData[index_pass].value;
data2["password"] = serializedData[index_pass].value;
data2["password2"] = serializedData[index_pass].value;
data2["email"] = serializedData[index_email].value;
console.log(data2);
var serializedFormData = $(this).serialize();
$.ajax({
url: window.url_root + '/accountsjson/register/',
type: 'POST',
dataType: 'json',
data: data2,
success: function(data) {
console.log(data); //remove
if (data.hasOwnProperty('success')) {
console.log("successful registration detected!!");
utils.loginAfterRegister(data2);
$('.register').slideUp();
$('.frame').hide();
} else {
utils.showRegister();
}
},
error: function() {
console.log("ERROR posting registration request. Abort!");
},
});
Function called from loginAfterRegister which has the refresh
function sendRating(rating, reload_on_return) {
$.ajax({
type: "POST",
dataType: 'json',
url: window.url_root + "/savecommentrating/1/" + rating.cid + "/",
data: {
"rating": rating.r2 / 100.0
},
success: function(data) {
if (data.hasOwnProperty('success')) {
console.log("data was sent!");
if (reload_on_return) {
location.reload();
}
}
},
error: function() {
console.log("rating didn't get sent!!");
}
})
}
mobile function within views.py
def mobile(request):
create_visitor(request)
os = get_os(1)
disc_stmt = get_disc_stmt(os, 1)
return render_to_response('mobile.html', context_instance = RequestContext(request, {'url_root' : settings.URL_ROOT,
'loggedIn' : str(request.user.is_authenticated()).lower(),
'client_data': mobile_client_data(request),
'client_settings': get_client_settings(True),
}))
create_visitor()
def create_visitor(request):
# See if we need to create a visitor here
if not request.user.is_authenticated() and not request.session.get('visitor_id', False):
visitor = Visitor()
visitor.save()
request.session['visitor_id'] = visitor.id

Categories

Resources