Updating only those properties are changed - javascript

I am plotting LineStrings in Mapbox.So now I am updating the color of the lines when the property is changed.
function update_the_map(){
$.ajax({
url:"http://dataurl",
contentType : "application/json; charset=utf-8",
type: "GET",
dataformat:"JSON",
async : false,
success: function(data){
for (i = 0; i <lines.features.length; i++) {
lines['features'][i]['properties']['points']=data[i].points;
var style_update =getColor( lines['features'][i]['properties']['points']);
geojson.setFeatureStyle(lines['features'][i]['properties']['id'], style_update);
}
setTimeout( update_the_map, 10000);
console.log("updated");
},
error:function(){}
});
}
But this changes all the color of the lines and not those points are greater than 5.Because my get color function is like
function getColor(d) {
if(d==10 || d==9 || d==8 || d==7 || d==6){
return '#ff0000';
}
else {
return '#00a1ff';
}
}
So it returns red if points>5 else it returns blue.But this returns blue for everything and the whole lines color is changed.ANy help is appreciated.This is how i create the layer.
geojson = L.vectorGrid.slicer(lines, {
vectorTileLayerStyles: {
sliced: style},
maxZoom: 24, // max zoom to preserve detail on
interactive: true,
getFeatureId: function(f) {
return f.properties.id;
}
}).on('mouseover', mouseover_function).addTo(map);
My lines is a variable as below :
var lines= {
"type":"FeatureCollection","features": [{"type": "Feature","geometry":{"type":"LineString",
"coordinates":[[ 101.942139,4.252606],[101.766357,3.134346]]},
"properties": {"id":"01","points":10}},....
]};

Can you show that what is inside the line.features array OR check the value of d in console, passed to getColor function.

The following did make the update work like a charm. So insteading of passing only the color I passed the weight and opacity and color It worked fine.
function update_the_map(){
$.ajax({
url:"http://dataurl",
contentType : "application/json; charset=utf-8",
type: "GET",
dataformat:"JSON",
async : false,
success: function(data){
var style_update; //changed declaration here
for (i = 0; i <lines.features.length; i++) {
lines['features'][i]['properties']['points']=data[i].points;
style_update = {
weight: 2,
opacity: 1,
color: getColor(links['features'][i]['properties']['score']),
fillOpacity: 0.7
};//added this whole for variable style update
geojson.setFeatureStyle(links['features'][i]['properties']['id'],style_update);
}
setTimeout( update_the_map, 10000);
console.log("updated");
},
error:function(){}
});
}

Related

Clear GeoJSON layer every time function is called

The function getCountryBorders() updates the map by drawing the desired country border every time the function is run. However, it just adds each country border to the current layer, rather than replacing the old border.
How can I clear the current layer each time the function is called?
const getCountryBorders = function() {
$.ajax({
url: "libs/php/getCountryBorders.php",
type: 'POST',
dataType: 'json',
success: function(result) {
const countries = result["data"]["features"];
function countryFilter(feature) {
if (feature.properties.iso_a2 === countryCode) return true
}
const borderStyle = {
"color": "red"
}
borderLayer = L.geoJson(countries, {
filter: countryFilter,
style: borderStyle
}).addTo(map);
},
error: function(jqXHR, textStatus, errorThrown) {
}
})
}
Since your borderLayer is in global scope, a very easy solution is to remove it from the map just before reassigning it:
if (borderLayer) {
borderLayer.remove();
}
borderLayer = L.geoJson(countries).addTo(map);

Function to refactor AJAX post: Get field ID that changed and post it's value with AJAX

I'm a new developer asking my first SO question :). Working on a form that has some calculated fields based off corresponding text inputs in ASP.NET MVC. Essentially, takes value from text box, AJAX post that value to controller, perform calc, returns that data to read-only calculated field.
I have the following code for this working:
$("#volume").focusout(function () {
volume = $(this).val()
$.ajax({
type: "POST",
url: '/StaffingPlan/CalculatorAction',
data: { volume: volume },
dataType: "json",
success: function (data) {
console.log(data);
$("#selectorsNeeded").val(data);
}
});
});
$("#drops").focusout(function () {
drops = $(this).val()
$.ajax({
type: "POST",
url: '/StaffingPlan/CalculatorAction',
data: { drops: drops },
dataType: "json",
success: function (data) {
console.log(data);
$("#liftsNeeded").val(data);
}
});
});
and in the controller:
public ActionResult CalculatorAction(string volume, string drops)
{
int data = 0;
//one calculation performed for volume, but will be others to calculate
if (volume != null && volume != "")
{
data = Int32.Parse(volume) / 150 / 9;
}
//example of another calc
if (drops != null && drops != "")
{
data = Int32.Parse(drops) / 25 / 6;
}
return Json(data, JsonRequestBehavior.AllowGet);
}
This works, however, the form has several other inputs and calculated fields. Obviously there's better/dryer way to write this instead of duplicating the .focusout function. Would be nice to just get the field ID that changes and assign value to appropriate variable. Hope this makes sense! Any direction would be appreciated very much.
Change your code to this:
$("#volume").focusout(function () {
var data= { volume: $(this).val()},
var resultField= $("#selectorsNeeded");
calculateResult(data, resultField);
});
$("#drops").focusout(function () {
var data= { drops: $(this).val() },
var resultField= $("#liftsNeeded");
calculateResult(data, resultField);
});
function calculateResult (data, resultField) {
$.ajax({
type: "POST",
url: '/StaffingPlan/CalculatorAction',
data: data,
dataType: "json",
success: function (result) {
console.log(result);
resultField.val(result);
}
});
};

Zing feed plotting multiple series in 1 chart

I am trying to plot 2 line series data in ZingChart feed.
Below is my script code.
<script>
var chartData = {
"type":"line",
"refresh": {
"type": "feed",
"transport": "js",
"url": "feed()",
"interval": 1000
},
"series":[
{
"values":[]
},
{
"values":[]
}
]
};
window.onload = function() {
zingchart.render({
id: "chartDiv",
data: chartData,
height: 600,
width: "100%"
});
};
window.feed = function(callback) {
$.ajax({
type: "GET",
dataType: "json",
headers: {
Accept: "application/json",
"Access-Control-Allow-Origin": "*"
},
url: "/PerformanceMonitor/showProcessUsage/${processName}",
success: function (data) {
var mem = data.mem.size/100000;
var tick = {
plot0: parseInt(mem)
};
callback(JSON.stringify(tick));
var tick2 = {
plot1:parseInt(mem/1000)
};
callback(JSON.stringify(tick2));
}
});
};
It gets displayed , but looses the line nature of the graph.Is this the right way ?Is there a better method?. Later I am planning to let user decide how many plots to be allowed in chart at runtime.Is there something in ZingChart that I can make use of ?
Thanks in advance.
The tick object contains the data for each series of a plot. That means you can add multiple plots to that object.
You can replace everything in your success callback with the following code...
var mem = data.mem.size/100000;
var tick = {
plot0: parseInt(mem),
plot1: parseInt(mem/1000)
};
callback(JSON.stringify(tick));
If you wanted to add a third plot to the series, you'd just add a plot2 attribute (since ZingChart's series have a 0-based index).
I'm on the ZingChart team. Let me know if you have other questions.

query clearInterval when variable is "x"

I have made a function that is controlling a row in a my database for a certain number with AJAX.
Im calling the function with a click function and putting the function in a setInterval function to make the check 10 times a second.
In the beginning it will return 0, but at some point (usually within 5 seconds) it will return something els than 0, when it does i want to clearInterval.
But im not sure how to this?
This is my function:
function get_buzzer() {
$.ajax({
url: 'ajax_buzzer.php',
dataType: 'json',
async: false,
type: 'post',
data: {
job: 'get'
},
success:function(s) {
if(s['number'] == 0) {
var player = false;
} else {
var player = true;
}
}, error:function(e) {
}
});
}
$(document).ready(function() {
$('#test').click(function() {
var buzzer = setInterval("get_buzzer()",100);
});
});
You can do something like
$(document).ready(function () {
//make buzzer a share variable
var buzzer;
$('#test').click(function () {
buzzer = setInterval(get_buzzer, 100);
});
function get_buzzer() {
$.ajax({
url: 'ajax_buzzer.php',
dataType: 'json',
async: false,
type: 'post',
data: {
job: 'get'
},
success: function (s) {
if (s['number'] != 0) {
//if number is not 0 then clear the interval
clearInterval(buzzer)
}
},
error: function (e) {}
});
}
});
Try this : declare global variable to store interval and call window.clearInterval in success call of ajax
var buzzer;
function get_buzzer() {
$.ajax({
url: 'ajax_buzzer.php',
dataType: 'json',
async: false,
type: 'post',
data: {
job: 'get'
},
success:function(s) {
if(s['number'] == 0) {
var player = false;
} else {
var player = true;
//clear interval
window.clearInterval(buzzer);
}
}, error:function(e) {
}
});
}
$(document).ready(function() {
$('#test').click(function() {
buzzer = setInterval("get_buzzer()",100);
});
});
Use:
inside success use: And make var buzzer Gloval var.
clearInterval(buzzer);
Refence
You just need to clear the interval in the success handler of ajax call over a condition.
success: function (s) {
if (s['number'] != 0) {
//if number is not 0 then clear the interval
clearInterval(buzzer)
}
},
error: function (e) {}

$.done() code gets executed before $.when()

In my project I m using 2 versions of JQuery.js, so I resolved the conflict using $.noConflict() for my latest version of JQuery to variable named jq172. Now I have used jq172.when().done()construct to show loading status image until all ajax request are processed completely. The code is as follows.
jq172.when(
DisplayPOXOrderStatistics(fromDate, toDate),
DisplayPOXCompletedOrdersData(fromDate, toDate),
DisplayPOXCompletedOrderPieChart(fromDate, toDate),
DisplayCurrentYearlyTrends())
.done(function (a1,a2,a3,a4)
{
$("#loading").hide();
});
where functions in the jq172.when() are coded as follows,
function DisplayPOXOrderStatistics(fromDate, toDate) {
return $.ajax({
type: "POST",
url: '#Url.Action("DisplayPOXOrderStatistics", "Home")',
dataType: "json",
data: { FromDate: fromDate, ToDate: toDate },
success: function (data) {application code.....}
});
}
function DisplayPOXCompletedOrdersData(fromDate, toDate) {
return $.ajax({
type: "POST",
url: '#Url.Action("DisplayPOXCompletedOrders", "Home")',
data: { FromDate: fromDate, ToDate: toDate },
dataType: "json",
success: function (data) { some code....}
});
}
& rest 2 functions are coded in the same way as above
Now my code in .done() to hide loading image dive should be executed after all 4 ajax call is finished, but currently it gets executed immediately after function call is dispatched. Can anybody figure out the problem in my code.
Thanks in Advance...
Here is the definition of rest 2 functions..
function DisplayPOXCompletedOrderPieChart(fromDate, toDate) {
return $.ajax({
type: "POST",
url: '#Url.Action("POXCompletedOrderPieChart", "Home")',
data: { FromDate: fromDate, ToDate: toDate },
dataType: "json",
success: function (data) {
$('#POXCompletedOrdersPie').empty();
var dataSet = [];
var isDataAvailable = false;
for (var i = 0; i < data.length ; i++) {
var newElement = { label: data[i].Name, data: parseFloat(data[i].ColumnValue), color: Color[i] };
dataSet.push(newElement);
if (newElement.data > 0)
isDataAvailable = true;
}
if (dataSet.length != 0 && isDataAvailable) {
$.plot($("#POXCompletedOrdersPie"), dataSet, {
series: {
pie: {
show: true
}
},
legend: {
show: false
}
});
}
else {
$("#POXCompletedOrdersPie").empty();
$("#POXCompletedOrdersPie").append("<html><p> <b>" + "#Html.Raw(VirtuOxAdvDME.Dashboard_PieChart_POXCompletedOrder_NoData)" + "</b> </p><html>");
}
}
});
}
function DisplayCurrentYearlyTrends() {
$("#DisplayCurrentYear").html($('#selectCurrentYear option:selected').text());
return $.ajax({
url: '#Url.Action("DisplayCurrentYearlyTrends", "Home")',
data: { selectedCurrentYear: $('#selectCurrentYear option:selected').text() },
type: 'POST',
dataType: 'json',
success: function (data) {
var DataValues = [], TickData = [];
var i = undefined;
$.each(data, function (index, item) {
i = (index + 1) * 2;
DataValues.push({ data: [i, item.Value], color: Color[i] });
DataValues.push([i, item.Value]);
TickData.push([i, item.MonthName]);
});
$.plot($("#CurrentYearlyTrendsBar"), [{ data: DataValues, color: "#3D69AA" }],
{
series: { bars: { show: true } },
bars: {
barWidth: 1.5,
align: "center"
},
xaxis: {
ticks: TickData,
axisLabelUseCanvas: true,
labelAngle: -90,
},
yaxis: { axisLabelUseCanvas: true },
grid: { hoverable: true }
});
$("#CurrentYearlyTrendsBar").UseTooltip();
}
});
}
Probably your $.ajax calls (from the old jQuery version) do not return jqXHR objects which implement the Promise interface, a feature that was introduced with v1.5. when would see the objects as plain values then and resolve immediately.
To fix this, use jq172.ajax() instead, or use a (single) up-to-date jQuery and update your legacy code.
this is from the jquery site
in the multiple-Deferreds case where one of the Deferreds is rejected, jQuery.when immediately fires the failCallbacks for its master Deferred. Note that some of the Deferreds may still be unresolved at that point. If you need to perform additional processing for this case, such as canceling any unfinished ajax requests, you can keep references to the underlying jqXHR objects in a closure and inspect/cancel them in the failCallback.
check your ajax calls and make sure no one is getting rejected. You can do this in the
developers console->network tab
generally becomes accessible after pressing F12.

Categories