this is my code please help me with the query
$("#update").click(function () {
var security_code = (red[0]["id"]);
var sector_class_id = (red[0]["cid"]);
var sector_id = $("#s1").val();
$.ajax({
type: "POST",
url: "Default.aspx/update",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ security_code: security_code, sector_class_id: sector_class_id, sector_id: sector_id }),
dataType: "json",
success: function (response) {
var updatedata = (response.d);
var ud1 = JSON.parse(updatedata);
udata = $.map(ud1, function (n, i) {
var temp7 =
{
secr_code: n.SECURITY_CODE,
sect_class: n.SECTOR_CLASS_ID,
sect_id: n.SECTOR_ID
}
return temp7
});
$("#mod1").modal('hide');
display();
$("#t1").hide();
$(".alert-succcess").alert();
window.setTimeout(function () {
$(".alert-success").fadeTo(2000, 500).slideUp(500, function () {
//$("#l1").val(security_code);//label values from db
//$("#l2").val(sector_class_id);//label values from db
//$("#s1").val(sector_id);// user selects n den updates value
$(".alert-success").slideUp(500);
});
});
},
i want to show updated values in my alert message along with the previous values which were updated what should i do
what should i do??????
Related
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?
There is some data inside a table
When I press the edit button, I can edit all the data for that row.Menu Category and Menu These two data came from Dependent dropdown.
with this code the dropdown in the menu was supposed to show when the menu categories were selected.
modal.find('.modal-body #menu_category_update').val(menu_item_category_selected);
modal.find('.modal-body #menu_update').val(menu_item_selected);
This code goes through the menu category ID and selects Fastfood Dropdown.
$(document).ready(function () {
$(document).on('change','#menu_category_update',function(){
$("#menu_update").empty();
var ddl_menu1 = GetLoadApptUpdate($(this).val());
$("menu_update").empty();
$('#menu_update').select2({
placeholder: "--Select Menu--",
data: ddl_menu1,
dropdownParent: $(this).parent()
});
});
});
function GetLoadApptUpdate(id) {
var b = [];
$.ajax({
type: "GET",
dataType: "json",
cache: true,
async: false,
url: "/admin/menu/item/entry1/"+id,
success: function (response) {
b = response;
},
error: function (response) {
b = { id: 0, text: "No Data" }
}
});
return b;
};
#menu_category_update The function that is being called with this ID is working properly. But my problem is that when I click on the edit button, a dropdown is selected by default, for which the dependent dropdown is not selected.
Expected answer:
Here is the solution:
$('#menu_category_update').val(menu_item_category_selected);
modal.find('.modal-body #menu_update').val(menu_item_selected);
var menu_category_update_val = $("#menu_category_update option:selected").val();
var menu_update_val = $("#menu_update option:selected").val();
if (menu_category_update_val !== "") {
func();
$('#menu_update').val(menuItemSelected).trigger('change');
}
function func() {
$('#menu_category_update').change(function () {
$("#menu_update").empty();
var ddl_menu1 = GetLoadApptUpdate1($(this).val());
$('#menu_update').select2({
placeholder: "--Select Menu--",
data: ddl_menu1,
dropdownParent: $(this).parent()
});
}).change();
function GetLoadApptUpdate1(id) {
var b = [];
$.ajax({
type: "GET",
dataType: "json",
cache: true,
async: false,
url: "/admin/menu/item/entry1/" + id,
success: function (response) {
b = response;
},
error: function (response) {
b = {id: 0, text: "No Data"}
}
});
return b;
};
}
I'm updating quantities in an order form with predefined "packs" from the database. Updating the from fields from the "packs" dropdown in the first function works, but the second function that uses those values and multiplies them by the value in a text input does not update the fields.
Also, when looking at the console output, it looks like the ajax request from the first and second function both run when the quantity input is changed.
jQuery(document).ready(function($) {
$("[id^=packs]").on('change', function() {
var packname = this.value;
console.log("packname:"+packname);
var lineno = this.getAttribute('data-lineno');
console.log("lineno: "+lineno);
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>products/pack",
cache: false,
// ContentType : 'application/json',
data: {name: packname},
success: function(json){
try{
var obj = jQuery.parseJSON(json);
console.log(obj);
console.log("size1: "+obj.packdetail[0].size1);
$('#'+lineno+'-size1').attr("value", obj.packdetail[0].size1);
$('#'+lineno+'-size2').attr("value", obj.packdetail[0].size15);
$('#'+lineno+'-size3').attr("value", obj.packdetail[0].size2);
$('#'+lineno+'-size4').attr("value", obj.packdetail[0].size25);
$('#'+lineno+'-size5').attr("value", obj.packdetail[0].size3);
$('#'+lineno+'-size6').attr("value", obj.packdetail[0].size35);
$('#'+lineno+'-size7').attr("value", obj.packdetail[0].size4);
$('#'+lineno+'-size8').attr("value", obj.packdetail[0].size45);
$('#'+lineno+'-size9').attr("value", obj.packdetail[0].size5);
$('#'+lineno+'-size10').attr("value", obj.packdetail[0].size55);
$('#'+lineno+'-size11').attr("value", obj.packdetail[0].size6);
$('#'+lineno+'-size12').attr("value", obj.packdetail[0].size65);
$('#'+lineno+'-size13').attr("value", obj.packdetail[0].size7);
$('#'+lineno+'-size14').attr("value", obj.packdetail[0].size75);
$('#'+lineno+'-size15').attr("value", obj.packdetail[0].size8);
$('#'+lineno+'-size16').attr("value", obj.packdetail[0].size85);
$('#'+lineno+'-size17').attr("value", obj.packdetail[0].size9);
$('#'+lineno+'-size18').attr("value", obj.packdetail[0].size95);
$('#'+lineno+'-size19').attr("value", obj.packdetail[0].size10);
$('#'+lineno+'-size20').attr("value", obj.packdetail[0].size105);
$('#'+lineno+'-size21').attr("value", obj.packdetail[0].size11);
$('#'+lineno+'-size22').attr("value", obj.packdetail[0].size115);
$('#'+lineno+'-size23').attr("value", obj.packdetail[0].size12);
$('#'+lineno+'-size24').attr("value", obj.packdetail[0].size125);
}
catch(e) {
console.log('Exception while request..');
}},
error: function(){
console.log('Error while request..');
}
});
});
//multiply packs
$("[id^=packs_qty]").on('change', function() {
var pack_qty = this.value;
var packname = $(this).attr("data-name");
console.log("qty:"+pack_qty);
console.log("packname:"+packname);
var lineno = this.getAttribute('data-lineno');
console.log("lineno: "+lineno);
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>products/pack",
cache: false,
// ContentType : 'application/json',
data: {name: packname},
success: function(json){
try{
var obj = jQuery.parseJSON(json);
console.log(obj);
console.log("size1: "+obj.packdetail[0].size1*pack_qty);
$('#'+lineno+'-size1').attr("value", (obj.packdetail[0].size1*pack_qty));
$('#'+lineno+'-size2').attr("value", obj.packdetail[0].size15*pack_qty);
$('#'+lineno+'-size3').attr("value", obj.packdetail[0].size2*pack_qty);
$('#'+lineno+'-size4').attr("value", obj.packdetail[0].size25*pack_qty);
$('#'+lineno+'-size5').attr("value", obj.packdetail[0].size3*pack_qty);
$('#'+lineno+'-size6').attr("value", obj.packdetail[0].size35*pack_qty);
$('#'+lineno+'-size7').attr("value", obj.packdetail[0].size4*pack_qty);
$('#'+lineno+'-size8').attr("value", obj.packdetail[0].size45*pack_qty);
$('#'+lineno+'-size9').attr("value", obj.packdetail[0].size5*pack_qty);
$('#'+lineno+'-size10').attr("value", obj.packdetail[0].size55*pack_qty);
$('#'+lineno+'-size11').attr("value", obj.packdetail[0].size6*pack_qty);
$('#'+lineno+'-size12').attr("value", obj.packdetail[0].size65*pack_qty);
$('#'+lineno+'-size13').attr("value", obj.packdetail[0].size7*pack_qty);
$('#'+lineno+'-size14').attr("value", obj.packdetail[0].size75*pack_qty);
$('#'+lineno+'-size15').attr("value", obj.packdetail[0].size8*pack_qty);
$('#'+lineno+'-size16').attr("value", obj.packdetail[0].size85*pack_qty);
$('#'+lineno+'-size17').attr("value", obj.packdetail[0].size9*pack_qty);
$('#'+lineno+'-size18').attr("value", obj.packdetail[0].size95*pack_qty);
$('#'+lineno+'-size19').attr("value", obj.packdetail[0].size10*pack_qty);
$('#'+lineno+'-size20').attr("value", obj.packdetail[0].size105*pack_qty);
$('#'+lineno+'-size21').attr("value", obj.packdetail[0].size11*pack_qty);
$('#'+lineno+'-size22').attr("value", obj.packdetail[0].size115*pack_qty);
$('#'+lineno+'-size23').attr("value", obj.packdetail[0].size12*pack_qty);
$('#'+lineno+'-size24').attr("value", obj.packdetail[0].size125*pack_qty);
}
catch(e) {
console.log('Exception while request..');
}},
error: function(){
console.log('Error while request..');
}
});
});
});
can you please convert obj.packdetail[0].size1 and pack_qty in to Number and try,
for this you can use
parseInt(obj.packdetail[0].size1) * parseInt(pack_qty);
Please have a try..
So i have list that is created dynamically as shown
Now I need a ADD button, which on click will add new item to list automatically. Help me out with this please.
Hi this is how can you retrive data using jquery
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "URL/MethodName",
data: "{}",// you can provide parameteres to your function here
dataType: "JSOn",
success: function (data) {
for (var i in data) {
alert(data[i].Id); //assign to controls
alert(data[i].Header);// assign to controls
alert( data[i].Content) ;// assign to contols
}
alert('Data fetched Successfully');
},
error: function (result) {
alert('Data not fetched ');
return false;
}
});
return false;
});
/*************************************************************************
[System.Web.Services.WebMethod]
public ActionResult Careers()
{
List<JobOpening> job = new List<JobOpening>()
{
new JobOpening{Id = 1, Header = "Job1", Content = "edde" },
new JobOpening{Id = 2,Header = "Job2", Content = "deded" },
};
}
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