How to determine if the java script function still running? - javascript

I have concern regarding of javascript function, The question is there any indicator to determine if the javascript function still on going or still running? because I have problem on inserting hundred of items inserting in the database. I want to condition if the javascript function still on going the insertion will stay until the condition met the else if the javascript function is not running or done, it will automatically redirect to the other page.
In my onclick of my jquery I insert the javascript function.
$('#add_to_cart').on('click', function() {
orders = [];
menu = undefined;
$('.tbody_noun_chaining_order').children('tr').each(function() {
$row = $(this);
if ($row.hasClass('condimentParent')) {
if (menu) {
orders.push(menu);
}
menu = {
'total': $row.find('.total').text(),
'name': $row.find('.parent_item').text(),
'customer_id': customer_id,
'condiments': {
'Item': [],
'Qty': [],
'Total': []
}
};
} else if ($row.hasClass('editCondiments')) {
menu.condiments.Item.push($row.find('.child_item').text());
menu.condiments.Qty.push($row.find('.condiments_order_quantity').text());
menu.condiments.Total.push($row.find('.total').text());
}
});
if (menu) {
orders.push(menu);
}
storeOrder(orders)
});
My Javascript Function
function storeOrder(data) {
var customer_id = $('#hidden_customer_id').val();
var place_customer = $('#place_customer').text();
$id = "";
$total_amount = $('.total_amount').text();
$append_customer_noun_order_price = $('.append_customer_noun_order_price').text();
$tax_rate = $('.rate_computation').text();
$delivery_rate = $('.del_rate').text();
var sessionTransactionNumber_insert = localStorage.getItem('sessionTransactionNumber');
$.ajax({
url:'/insert_customer_order_properties',
type:'POST',
data:{
'hidden_customer_id': customer_id,
'hidden_customer_address': place_customer,
'sessionTransactionNumber': sessionTransactionNumber_insert
},
success:function(data) {
$id = data[0].id;
$.ajax({
url:'/insert_customer_payment_details',
type:'POST',
data:{
'hidden_customer_id': customer_id,
'total_amount': $total_amount,
'customer_sub_total': $append_customer_noun_order_price,
'tax_rate': $tax_rate,
'id_last_inserted': $id
},
success:function(data) {
localStorage.removeItem('sessionTransactionNumber');
}
})
}
})
for (var num in orders) {
$.ajax('/insert_wish_list_menu_order', {
type: 'POST',
context: orders[num].condiments,
data: {
'append_customer_noun_order_price': orders[num].total,
'append_customer_noun_order': orders[num].name,
'customer_id': customer_id
},
success: function(orderNumber) {
$order_number = orderNumber[0].id;
$.ajax({
url:'/insert_customer_order_details_properties',
type:'POST',
data:{
'order_number': $order_number,
'data_attribute_wish_order_id': $id,
},
success:function(data) {
console.log(data);
}
})
if (orderNumber !== undefined) {
$.ajax('/insert_wish_list_menu_belong_condiments', {
context: orderNumber,
type: 'POST',
data: {
'ParentId': orderNumber,
'Item': this.Item,
'Qty': this.Qty,
'Total': this.Total
},
success: function(result) {
console.log(result);
},
})
}
}
})
}
}

Related

Only one alert for multiple execution in Ajax

I am working rails application.i need to get status of the each selected device.I am able to achieve this but after executing i am putting alert "Successfully created execution record".For every mac selection it is showing alert message.I need to give one alert in end of execution.I am calling display_result in call_endpoint method.Since it is an Ajax call,it is giving alert for every execution.i don't how to limit to single alert for this.
function display_result() {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
alert('Successfully created execution record");
}
});
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 0; i < m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result();
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
Below is changed code..
Copy below code as it is.
function display_result(total,current) {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
if(total == current)
{
alert('Successfully created execution record");
}
}
});
}
}
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 1; i <= m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result(m,i);
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
}
result and mac is not defined in display_result function. result appears intended to be the resulting value of jQuery promise object returned from $.ajax(). Am not certain what mac is indented to be.
You can substitute $.when() and $.map() for for loop, return a jQuery promise object from call_endpoint(), include error handling, chain .then() to call_endpoint() call to execute alert() once.
function call_endpoint() {
return $.when.apply($, $.map(values, function(macAdd) {
return $.ajax().then(display_result)
}))
}
callEnpoint()
.then(function() {
alert('Successfully created execution record');
}, function(jqxhr, textStatus, errorThrown) {
console.error(errorThrown)
});
function display_result(reuslt) {
..
if (if (result["response"].status == "200")) {
return $.ajax() // remove `alert()` from `success`
}
return;
}

Jquery Deferred + Ajax

Can anyone tell me why this will not update the data object in the AJAX? If I have multiple features in the geojson, it tends to only save one of the features records when looping through all the geojson features. So if geojsonFeatures has 3 records, 3 records will be pushed into ajaxDeferred but the data will be the same for all three records.
data: {
id: updatedLayerGeojsonId,
table: updatedLayerGeojsonTable,
geom: updatedLayerGeojsonGeometry
}
var geojsonFeatures = geojson.features;
var ajaxDeferred = [];
for(var a = 0; a < geojsonFeatures.length; a++){
updatedLayerGeojson = geojsonFeatures[a].geometry;
updatedLayerGeojson.crs = {
"type": "name",
"properties": {
"name": "epsg:4326"
}
};
updatedLayerGeojsonGeometry = JSON.stringify(updatedLayerGeojson);
updatedLayerGeojsonId = geojsonFeatures[a].properties.gid;
updatedLayerGeojsonTable = geojsonFeatures[a].properties.layer_table;
ajaxDeferred.push(
$.ajax({
url: window.location.origin + '/csrfToken',
success: function(response) {
$.ajax({
url: '/maplayers/saveEditedLayerRecord',
type:"post",
data: {
id: updatedLayerGeojsonId,
table: updatedLayerGeojsonTable,
geom: updatedLayerGeojsonGeometry
},
beforeSend: function(xhr, settings){
xhr.setRequestHeader('X-CSRF-Token', response._csrf);
},
success: function(data){
if(data){
numberOfEditedLayersCompleted++;
if(numberOfEditedLayers == numberOfEditedLayersCompleted){
removeLayers();
editableLayers.clearLayers();
editedLayer = false;
numberOfEditedLayers = 0;
numberOfEditedLayersCompleted = 0;
}
}
},
cache: false
});
}
})
);

jQuery post like issue

I wrote this code for like and dislike for my posts in my blog:
$(".p_like").each(function() {
$(this).click(function() {
ids = $(this).find(".pl_id").val();
t = $(this);
if ($(this).find(".bi").hasClass("bi-heart-o")) {
gfd = 'p';
$(this).find(".bi").addClass("bi-heart");
$(this).find(".bi").removeClass("bi-heart-o");
} else {
gfd = 'm';
$(this).find(".bi").addClass("bi-heart-o");
$(this).find(".bi").removeClass("bi-heart");
}
$.ajax({
type: "POST",
url: "likes.php",
data: {
ids: ids,
k: gfd
},
cache: false,
success: function(result) {
t.find(".nol").html(result);
}
});
});
});
And when I use the code, in some of the post it likes the post and then dislike it.
What is the problem of the code and how can I fix it?
use this :
$(".p_like").find(".bi").click(function(){
ids = $(this).siblings(".pl_id").val();
t = $(this);
if($(this).hasClass("bi-heart-o")){
gfd='p';
$(this).addClass("bi-heart");
$(this).removeClass("bi-heart-o");
}else{
gfd='m';
$(this).addClass("bi-heart-o");
$(this).removeClass("bi-heart");
}
$.ajax({
type: "POST",
url: "likes.php",
data: {ids:ids,k:gfd},
cache: false,
success: function (result) {
t.siblings(".nol").html(result);
}
});
});
and you maybe used this file two time!
Jquery by default query all given selectors ( here .p_like ). It's not needed to iterate over them explicitly.
Jquery methods are chanable. after you select one element you could call methods one after another: $element.addClass(...).removeClass().css(...)
Also you've leaked three variables: ids, t, gfd. maybe they're got overriten before you send em out to server so declare them to make em private to your event handler function.
$('.p_like').click(function() {
var $t = $(this),
$bi = $t.find('.bi'),
$nol = $t.find('.nol'),
ids = $t.find('.pl_id').val(),
gfd;
if ( $bi.hasClass('bi-heart-o') ) {
gfd = 'p';
$bi.addClass('bi-heart').removeClass('bi-heart-o');
} else {
gfd = 'm';
$bi.addClass('bi-heart-o').removeClass('bi-heart');
}
$.ajax({
type: 'POST',
url: 'likes.php',
data: {
ids: ids,
k: gfd
},
cache: false,
success: function(result) {
$nol.html(result);
}
});
});

Does jQuery.ajax() not always work? Is it prone to miss-fire?

I have an $.ajax function on my page to populate a facility dropdownlist based on a service type selection. If I change my service type selection back and forth between two options, randomly the values in the facility dropdownlist will remain the same and not change. Is there a way to prevent this? Am I doing something wrong?
Javascript
function hydrateFacilityDropDownList() {
var hiddenserviceTypeID = document.getElementById('<%=serviceTypeID.ClientID%>');
var clientContractID = document.getElementById('<%=clientContractID.ClientID%>').value;
var serviceDate = document.getElementById('<%=selectedServiceDate.ClientID%>').value;
var tableName = "resultTable";
$.ajax({
type: 'POST',
beforeSend: function () {
},
url: '<%= ResolveUrl("AddEditService.aspx/HydrateFacilityDropDownList") %>',
data: JSON.stringify({ serviceTypeID: TryParseInt(hiddenserviceTypeID.value, 0), clientContractID: TryParseInt(clientContractID, 0), serviceDate: serviceDate, tableName: tableName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
a(data);
}
,error: function () {
alert('HydrateFacilityDropDownList error');
}
, complete: function () {
}
});
}
function a(data) {
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
var tableName = "resultTable";
if (facilityDropDownList.value != "") {
selectedFacilityID = facilityDropDownList.value;
}
$(facilityDropDownList).empty();
$(facilityDropDownList).prepend($('<option />', { value: "", text: "", selected: "selected" }));
$(data.d).find(tableName).each(function () {
var OptionValue = $(this).find('OptionValue').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
$(facilityDropDownList).append(option);
});
if ($(facilityDropDownList)[0].options.length > 1) {
if ($(facilityDropDownList)[0].options[1].text == "In Home") {
$(facilityDropDownList)[0].selectedIndex = 1;
}
}
if (TryParseInt(selectedFacilityID, 0) > 0) {
$(facilityDropDownList)[0].value = selectedFacilityID;
}
facilityDropDownList_OnChange();
}
Code Behind
[WebMethod]
public static string HydrateFacilityDropDownList(int serviceTypeID, int clientContractID, DateTime serviceDate, string tableName)
{
List<PackageAndServiceItemContent> svcItems = ServiceItemContents;
List<Facility> facilities = Facility.GetAllFacilities().ToList();
if (svcItems != null)
{
// Filter results
if (svcItems.Any(si => si.RequireFacilitySelection))
{
facilities = facilities.Where(f => f.FacilityTypeID > 0).ToList();
}
else
{
facilities = facilities.Where(f => f.FacilityTypeID == 0).ToList();
}
if (serviceTypeID == 0)
{
facilities.Clear();
}
}
return ConvertToXMLForDropDownList(tableName, facilities);
}
public static string ConvertToXMLForDropDownList<T>(string tableName, T genList)
{
// Create dummy table
DataTable dt = new DataTable(tableName);
dt.Columns.Add("OptionValue");
dt.Columns.Add("OptionText");
// Hydrate dummy table with filtered results
if (genList is List<Facility>)
{
foreach (Facility facility in genList as List<Facility>)
{
dt.Rows.Add(Convert.ToString(facility.ID), facility.FacilityName);
}
}
if (genList is List<EmployeeIDAndName>)
{
foreach (EmployeeIDAndName employeeIdAndName in genList as List<EmployeeIDAndName>)
{
dt.Rows.Add(Convert.ToString(employeeIdAndName.EmployeeID), employeeIdAndName.EmployeeName);
}
}
// Convert results to string to be parsed in jquery
string result;
using (StringWriter sw = new StringWriter())
{
dt.WriteXml(sw);
result = sw.ToString();
}
return result;
}
$get return XHR object not the return value of the success call and $get function isn't synchronous so you should wait for success and check data returned from the call
these two lines do something different than what you expect
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
change to something similar to this
var facilityDropDownList;
$.ajax({
url: '<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>',
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
facilityDropDownList= data;
}
});

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