Jquery Deferred + Ajax - javascript

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
});
}
})
);

Related

Error : Uncaught TypeError: this.source is not a function

I tried to create Autocomplete using jQuery Ajax. Basically, I want to make autocomplete search with dynamic field added. But while I type in the input field then it gave me this error.
JS Code
$(document).ready(function() {
var arrayReturn = []
$.ajax({
url: "/suppliers",
async: true,
dataType: 'json',
success: function(data) {
for (var i = 0; i < data.length; i++) {
var id = (data[i].id).toString();
arrayReturn.push({'value' : data[i].name, 'data' : id})
}
printSupplier(arrayReturn);
}
});
function printSupplier(suppliers) {
$('#purchase_item_search').autocomplete({
lookup: suppliers,
onSelect: function (result) {
$('#autocom-box').html(result.value);
}
});
}
});
Problem Solved.
$(document).ready(function() {
$("#purchase_item_search").on('keyup', function() {
var arrayReturn = []
$.ajax({
url: "/suppliers",
dataType: 'json',
success: function(data) {
// console.log(data['suppliers'].length);
for (var i = 0; i < data['suppliers'].length; i++) {
var id = (data['suppliers'][i].id).toString();
arrayReturn.push({
'value': data['suppliers'][i].name,
'data': id
})
}
printSupplier(arrayReturn);
}
});
function printSupplier(options) {
$('#purchase_item_search').autocomplete({
source: options,
onSelect: function(result) {
// $('#autocom-box').html(result.value);
console.log(result);
}
});
}
});
});

ajax loading before document despite using when().then() function with leaflet JS

Here is what the console reads:
Uncaught TypeError: Cannot read property 'addTo' of undefined
I am currently working with leaflet JS and before the page loads, there is quite a number of Ajax calls going on so that the website can render the acquired data for the user.
I have used two particular methods to synchronize certain ajax calls which rely on the previous. One method is passing the next ajax call into the complete function, whilst another is the when().then() function
The objective with the function below, which is called with the window.onload method, is to determine the users location using the javascript navigator, set the map, and proceed with the ajax calls as mentioned above.
$(window).on('load', function() {
//Pre-loader Jquery
if ($('#preloader').length) {
$('#preloader').delay(200).fadeOut('slow', function() {
$(this).remove();
});
}
//Determine users location, initiate leaflet map, synchornised ajax calls to retreive country core information
navigator.geolocation.getCurrentPosition((success) => {
const crd = success.coords;
onLoadLat = crd.latitude;
onLoadLng = crd.longitude;
currentMap = L.map('map').setView([onLoadLat, onLoadLng], 5);
mapTileLayer.addTo(currentMap);
$.ajax({
url: "libs/php/openCage.php",
type: "POST",
dataType: "JSON",
data: {
latLng: onLoadLat + "+" + onLoadLng
},
success: function(data, textStatus, jqXHRs) {
iso_a2 = data["results"][0]["components"]["ISO_3166-1_alpha-2"];
},
complete: function() {
//Retreive GeoJson file, mark polygon and set initial map for to reflect user location
$.ajax({
url: "libs/php/getCountryBorder.php",
type: "POST",
dataType: "JSON",
data: {
countryCode: iso_a2
},
success: function(geoData, txtSt, jq) {
//Reference details of existing country for further API's and functionality
nameOfCountry = geoData["properties"]["name"];
//Use the index to target the array and create polygon border on map
targetMapData = L.geoJSON(geoData, {
style: borderStyle
});
targetMapData.addTo(currentMap);
currentMap.fitBounds(targetMapData.getBounds(), {
padding: [50, 50],
});
},
complete: function() {
$.ajax({
url: "libs/php/keyCountryInfo.php",
type: "POST",
dataType: "JSON",
data: {
country_code: iso_a2
},
success: function(data, textStatus, jqXHR) {
capitalCity = data["capital"];
currencyCode = data.currencies[0].code;
coordinates = [...data.latlng];
$("#timezoneList").empty();
$("#countryName").text(data["name"]);
$("#region").text(data["region"]);
$("#sub-region").text(data["subregion"]);
$("#countryFlag").attr("src", data["flag"]);
$("#population").text(numeral(data["population"]).format(0, 0));
$("#capital").text(data["capital"]);
$("#timezoneList").text(data["timezones"][0]);
},
complete: function() {
$.when(**getPopularCities()**, getCityWeatherList(), getWikiEntries(onLoadLat, onLoadLng), getGeoNameId(), getCountryImages(), getPublicHolidays(), getLatestExchange(), populateSelect()).
then(function(data, textStatus, jqXHR) {
infoEasyBtn.addTo(currentMap);
wikiEasyBtn.addTo(currentMap);
currencyEasyBtn.addTo(currentMap);
covidEasyBtn.addTo(currentMap);
newsEasyBtn.addTo(currentMap);
weatherEasyBtn.addTo(currentMap);
airportMarkers.addTo(currentMap);
cityMarkers.addTo(currentMap);
siblingMarkers.addTo(currentMap);
});
}
})
}
})
}
})
})
});
within the onload function above, is the getPopularCities() method, which is where the issue is. I have set markers to be shown on the map, but there is one group of markers which do not load, from within that function
Get Popular Cities Method
function getPopularCities() {
let cityPopulation = [];
cityMarkers = new L.MarkerClusterGroup();
if (mainLayer) {
currentMap.removeControl(mainLayer);
}
$.ajax({
url: "libs/php/getCountryCities.php",
type: "POST",
dataType: "JSON",
data: {
getCountryIso: iso_a2
},
success: function(success, textStatus, jqXHRs) {
$("#top10CityTable").empty();
let cityList = success["cities"]; //grab all the cities from the response
//create an array in global variable named cityPopulation, to contain all the markers
cityList.sort((a, b) => {
if (a["population"] > b["population"]) {
return -1
} else {
return 1
}
})
cityList.forEach((element, index) => {
let formatedPop = numeral(element["population"]).format(0, 0);
//depending on how many citys have returned, title the heading accordingly
if (cityList.length < 10) {
$("#top10CityHeading").text("Major Cities")
}
if (cityList.length >= 10) {
$("#top10CityHeading").text("Top 10 Most Populated Cities");
}
//stop index at 9 to get data of top 10 most populated cities for modal section
if (index <= 9) {
$("#top10CityTable").append(`<tr><td>${element["name"]}</td><td>${formatedPop}</td></tr>`)
}
cityMarkers.addLayer(L.marker([element["latitude"], element["longitude"]], {
icon: populatedCities
}).bindPopup(`<h3>${element["name"]}</h3></br>Population: ${formatedPop}`));
})
//create a new overlay prop/value pairing in the global overlays variable
overlays["Major Cities"] = cityMarkers;
},
error: function(text, xh, errorThrown) {
console.log(errorThrown);
},
complete: function() {
let siblingsMapArr = [];
siblingMarkers = new L.MarkerClusterGroup();
$.ajax({
url: "libs/php/getCountrySiblings.php",
type: "POST",
dataType: "JSON",
data: {
countryGeoId: geoNameId
},
success: function(success, textStatus, jqXHRs) {
$("#countrySiblings").empty();
let siblingsArr = success["geonames"];
siblingsArr.sort((a, b) => {
if (a["population"] > b["population"]) {
return -1
} else {
return 1
}
})
let top10Sib = siblingsArr.slice(0, 10);
top10Sib.forEach((element, index) => {
let formatedPop = numeral(element["population"]).format(0, 0);
let rank = index + 1;
siblingMarkers.addLayer(L.marker([element["lat"], element["lng"]], {
icon: citySiblings
}).bindPopup(`<h3>${rank}. ${element["countryName"]}</h3><br/>Population: ${formatedPop}`));
$("#countrySiblings").append(`
<tr>
<td>${element["countryName"]}</td>
<td>${formatedPop}</td>
<td>${element["lat"]} / ${element["lng"]}</td>
</tr>`)
})
overlays["Top 10 Siblings (By Population)"] = siblingMarkers;
},
complete: function(success, data, jq) {
$.ajax({
url: "libs/php/getAirports.php",
type: "POST",
dataType: "JSON",
data: {
countryCode: iso_a2
},
success: function(success, txtStatus, jqXHR) {
let airportsArr = [];
airportMarkers = new L.MarkerClusterGroup();
const airportsList = success["data"];
airportsList.forEach((element) => {
airportMarkers.addLayer(L.marker([element["location"]["latitude"], element["location"]["longitude"]], {
icon: airportIcon
}).bindPopup(`<h3>${element["name"]["original"]}</h3></br>ICAO: ${element["icao"]}</br>Elevation: ${element["elevationFeet"]}<br/>Classification: ${element["classification"]}`));
})
overlays["Airports"] = airportMarkers;
mainLayer = L.control.layers(baseMaps, overlays);
mainLayer.addTo(currentMap);
airportMarkers.addTo(currentMap);
cityMarkers.addTo(currentMap);
siblingMarkers.addTo(currentMap);
}
})
}
})
}
})
}
The markers saved in the variable airportMarkers and cityMarkers appear on the map as well as the leaflet control panel, but the siblings markers do not.
So Im guessing the safe bet is that it is not bringing the data back in time before the page loads? Does anyone have a solution for this or perhaps I have done something wrong in my code?

How to determine if the java script function still running?

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);
},
})
}
}
})
}
}

Google chart ordered by stack height

I'm trying to reorder my chart after inserting some data from a json file. I've tried to sort the data array without success.
There's any plugin or easy way to reorder the stacks and show the tallest first?
Heres my code:
var ChartHelper = {
data: [],
labels: [],
datarray: [],
init: function() {
this.setupChart();
this.bindEvents();
},
bindEvents: function() {
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['bar']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(ChartHelper.drawChart);
if (document.addEventListener) {
window.addEventListener('resize', ChartHelper.resizeChart);
}
else if (document.attachEvent) {
window.attachEvent('onresize', ChartHelper.resizeChart);
}
else {
window.resize = ChartHelper.resizeChart;
}
},
drawChart: function() {
// Create the data table.
var data = new google.visualization.DataTable();
ChartHelper.data = google.visualization.arrayToDataTable(ChartHelper.datarray);
// Set chart options
ChartHelper.options = {
title: 'Usuários influentes',
width: '100%',
height: 900,
chartArea: {width: '85%', top: 50,left:10},
stacked: true
};
// Instantiate and draw our chart, passing in some options.
ChartHelper.chart = new google.charts.Bar(document.getElementById('myChart'));
ChartHelper.chart.draw(ChartHelper.data, google.charts.Bar.convertOptions(ChartHelper.options));
},
getBrands: function() {
$.ajax({
url: "./data/brands.json",
dataType: 'json',
async: false,
success: function(data) {
ChartHelper.brands = [];
$.each( data, function( key, val ) {
if(ChartHelper.labels.indexOf(val.name) === -1){
ChartHelper.labels.push( val.name );
ChartHelper.brands.push(val);
}
});
}
});
// push brands
Object.keys(ChartHelper.brands).filter(function(index) {
ChartHelper.datarray.push([ChartHelper.brands[index].name]);
});
},
getUsers: function() {
$.ajax({
url: "./data/users.json",
dataType: 'json',
async: false,
success: function(data) {
ChartHelper.users = [];
$.each( data, function( key, val ) {
ChartHelper.users.push(val);
ChartHelper.setupDatasets(val,key);
});
}
});
// push users
var users = [];
Object.keys(ChartHelper.users).filter(function(index) {
users.push(ChartHelper.users[index].login.username);
});
users.unshift('Marcas');
ChartHelper.datarray.unshift(users);
},
getInteractions: function() {
$.ajax({
url: "./data/interactions.json",
dataType: 'json',
async: false,
success: function(data) {
ChartHelper.interactions = [];
$.each( data, function( key, val ) {
ChartHelper.interactions.push(val);
});
}
});
},
setupDatasets: function(user,i) {
var totalInte;
var userdata = [];
var j = i+1;
$.each(ChartHelper.labels, function( key, val ){
totalInte = 0;
$.each(ChartHelper.interactions, function( key2, val2 ){
if(user.id == val2.user) {
Object.keys(ChartHelper.brands).filter(function(index) {
if(ChartHelper.brands[index].id == val2.brand && ChartHelper.brands[index].name == val)
totalInte++;
});
}
});
if(totalInte > 0)
userdata = totalInte;
else
userdata = '';
ChartHelper.datarray[key][j] = totalInte;
});
},
setupChart: function() {
ChartHelper.datarray = [];
this.getBrands();
this.getInteractions();
this.getUsers();
},
getRandColor: function(){
var brightness = 4;
var rgb = [Math.random() * 256, Math.random() * 256, Math.random() * 256];
var mix = [brightness*51, brightness*51, brightness*51]; //51 => 255/5
var mixedrgb = [rgb[0] + mix[0], rgb[1] + mix[1], rgb[2] + mix[2]].map(function(x){ return Math.round(x/2.0)})
return "rgb(" + mixedrgb.join(",") + ")";
},
resizeChart: function() {
ChartHelper.chart.draw(ChartHelper.data, ChartHelper.options);
}
};
$(document).ready(function() {
// ready
ChartHelper.init();
});
Tried many options for different charts and I'm still reading the docs to find a solution, please help me!
Here's a demo:
DEMO
sort the data table before drawing the chart...
// sort data table on value column
ChartHelper.data.sort([{column: 1}]);
ChartHelper.chart.draw(ChartHelper.data, google.charts.Bar.convertOptions(ChartHelper.options));

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