Generic Handler Data to Ajax Json - asp.net

I have a Handler which has some data inside as shown below:
{"city1": { "name": "Adana","slug": "north-east", "url": "#", "path": "M 156.53125,407.40625 L 156.71875,408.5625 L 157.1875,407.8125 L 156.53125,407.40625 z"}}
P.S: The path is coming from SVG image. it draws a city border and there are many cities.
I try to get the data from this handler to variable to use it later...
CODE:
<script type="text/javascript">
var paths;
$.ajax({
url: '/paths.ashx',
dataType: 'json',
contentType: 'application/json',
responseType: "json",
success: function (data) {
paths = data;
alert(paths);
},
error: function (data, status, jqXHR) {
alert(status);
}
});
jQuery(function ($) {
var c = Raphael('map', "100%", "100%");
c.safari();
var label = c.popup(0, 0, "").hide();
attr = { fill: '#898989', stroke: '#FFFFFF', 'stroke-width': 2, 'stroke-linejoin': 'round' }
arr = new Array();
for (var item in paths) {
var p = c.path(paths[item].path);
arr[p.id] = item;
p.attr(attr);
p.hover(function () {
this.animate({
fill: '#8fbf27'
}, 200);
bbox = this.getBBox();
label.attr({ text: paths[arr[this.id]].name }).update(bbox.x, bbox.y + bbox.height / 2, bbox.width).toFront().show();
}, function () {
this.animate({
fill: attr.fill
}, 200);
label.hide();
})
.click(function () {
location.href = paths[arr[this.id]].url;
})
}
});
</script>
The problem comes right here...paths or data is undefined, it's always empty. But paths.ashx is not empty at all...
I couldnt find the solution...could you take a look pls...

Put your jQuery .ajax() function inside of the jQuery DOM ready function and the drawing logic inside the success handler of the AJAX call, like this:
<script type="text/javascript">
var paths;
jQuery(function ($) {
$.ajax({
url: '/paths.ashx',
dataType: 'json',
contentType: 'application/json',
responseType: "json",
success: function (data) {
paths = data;
alert(paths);
var c = Raphael('map', "100%", "100%");
c.safari();
var label = c.popup(0, 0, "").hide();
attr = { fill: '#898989', stroke: '#FFFFFF', 'stroke-width': 2, 'stroke-linejoin': 'round' }
arr = new Array();
for (var item in paths) {
var p = c.path(paths[item].path);
arr[p.id] = item;
p.attr(attr);
p.hover(function () {
this.animate({
fill: '#8fbf27'
}, 200);
bbox = this.getBBox();
label.attr({ text: paths[arr[this.id]].name }).update(bbox.x, bbox.y + bbox.height / 2, bbox.width).toFront().show();
}, function () {
this.animate({
fill: attr.fill
}, 200);
label.hide();
})
.click(function () {
location.href = paths[arr[this.id]].url;
})
}
},
error: function (data, status, jqXHR) {
alert(status);
}
});
});

You're trying to draw before the ajax promise is full filled, try this
function drawMap (paths) {
var c = Raphael('map', "100%", "100%");
c.safari();
var label = c.popup(0, 0, "").hide();
attr = { fill: '#898989', stroke: '#FFFFFF', 'stroke-width': 2, 'stroke-linejoin': 'round' }
arr = new Array();
for (var item in paths) {
var p = c.path(paths[item].path);
arr[p.id] = item;
p.attr(attr);
p.hover(function () {
this.animate({
fill: '#8fbf27'
}, 200);
bbox = this.getBBox();
label.attr({ text: paths[arr[this.id]].name }).update(bbox.x, bbox.y + bbox.height / 2, bbox.width).toFront().show();
}, function () {
this.animate({
fill: attr.fill
}, 200);
label.hide();
})
.click(function () {
location.href = paths[arr[this.id]].url;
})
}
}
and from your ajax request
$.ajax({
url: '/paths.ashx',
dataType: 'json',
contentType: 'application/json',
responseType: "json",
success: function (data) {
paths = data;
drawMap(paths); //notice this
},
error: function (data, status, jqXHR) {
alert(status);
}
});

Related

Show values on google piechart legends

I have this google piechart, which is working fine, except on the legend text along with it, I wanna show the percentage and numbers. The below would be the code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var options = {
title: 'Registration',
legend: { position: 'right', textStyle: { color: 'blue', fontSize: 16 } }
};
$.ajax({
type: "POST",
url: "adminrep.aspx/GetChartData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r.d);
var chart = new google.visualization.PieChart($("#chart")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
<div id="chart" style="width: 900px; height: 500px; margin-top:60px;"></div>
How do I get this done? Thanks in advance.
Try using .setFormattedValue to format the the labels in the DataTable.
This still requires you do a little bit of manual calculation for the getting the total sum of values, but it should work:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var options = {
title: 'Registration',
legend: {
position: 'right',
textStyle: { color: 'blue', fontSize: 16 }
}
};
$.ajax({
type: "POST",
url: "/echo/json/",
data: {
json: JSON.stringify({
d: [
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]})
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r.d);
var count = data.getNumberOfRows();
var values = Array(count).fill().map(function(v, i) {
return data.getValue(i, 1);
});
var total = google.visualization.data.sum(values);
values.forEach(function(v, i) {
var key = data.getValue(i, 0);
var val = data.getValue(i, 1);
data.setFormattedValue(i, 0, key + ' (' + (val/total * 100).toFixed(1) + '%)');
});
var chart = new google.visualization.PieChart($("#chart")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
<div id="chart" style="width: 900px; height: 500px; margin-top:60px;"></div>
Example: https://jsfiddle.net/cn74tvmL/show
You need to use number format:
var formatter = new google.visualization.NumberFormat({pattern: '#,### MW'});
formatter.format(data, 1);
or:
chart1.options = {
.
.
.
pieSliceText: 'value',
legend: {
position: 'labeled',
labeledValueText: 'both',
textStyle: {
color: 'blue',
fontSize: 14
}
}
};

Script not works (ASP.NET MVC)

I have script for recording video
Here is code of it
var fileName;
stop.onclick = function () {
record.disabled = false;
stop.disabled = true;
window.onbeforeunload = null; //Solve trouble with deleting video
preview.src = '';
fileName = Math.round(Math.random() * 99999999) + 99999999;
console.log(fileName);
var full_url = document.URL; // Get current url
var url_array = full_url.split('/') // Split the string into an array with / as separator
var id = url_array[url_array.length - 1]; // Get the last part of the array (-1)
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
I try to get url with this row var id = url_array[url_array.length - 1]; // Get the last part of the array (-1)
and with this code write to table filename
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
but it not works.
There is my Action method for it
[HttpPost]
public ActionResult LinkWriter(string link, int id) {
Link link_ = new Link
{
Link1 = link,
Interwier_Id = id,
};
db.Link.Add(link_);
db.SaveChanges();
return View();
}
But it not works. Where is my mistake?
UPDATE
As I understood not works this
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}

Mapbox fitBounds, function bounds map but does not render tiles

Here, my javascript code to render markers in map and after that fitBounds of that map.
Map bounds are get fit according to geojson, but problem is that when there is any marker
on map and I try to fit bound, map tiles images are not get render.
In map it display only markers, no tile images.
var latLongCollection = [];
var map;
$(document).ready(function() {
map();
});
function map() {
map = L.mapbox.map('DivId', 'ProjectId');
GetData();
}
function GetData() {
$.ajax({
type: "GET",
url: someUrl,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: AjaxSuccess,
error: function () {
}
});
}
function AjaxSuccess(data) {
if (data == null || data.length == 0) {
return;
}
var geoJson = {
"type": "FeatureCollection",
"features": []
};
$.each(data, function (index, value) {
var latitude = parseFloat(value.Latitude),
longitude = parseFloat(value.Longitude);
if (latitude && longitude) {
var dataJson = {
type: "Feature",
geometry: { type: "Point", coordinates: [longitude, latitude] },
properties: {
someProp: value.SomeProperty,
}
};
geoJson.features.push(vehicleJson);
}
});
var markerLayer = L.mapbox.featureLayer(geoJson).addTo(map);
markerLayer.eachLayer(function (marker) {
var feature = marker.feature;
var featureProperty = feature.properties;
if (featureProperty.someProp) {
marker.setIcon(L.divIcon({
html: 'htmlstring',
iconSize: [35, 75]
}));
}
else {
marker.setIcon(L.divIcon({
html: 'anotherhtmlstring',
iconSize: [35, 75]
}));
}
latLongCollection.push(marker._latlng);
});
markerLayer.on('click', function (e) {
map.panTo(e.layer.getLatLng());
});
if (latLongCollection.length > 0) {
map.fitBounds(latLongCollection);
}
}
If anyone is still struggling with this, it appears to be a bug in Leaflet: https://github.com/Leaflet/Leaflet/issues/2021
It has been fixed in the latest version, but if you can't update you can work around the race condition by setting a timeout:
setTimeout(function () {
map.fitBounds(latLongCollection);
}, 0);
How did you try debug the problem? What's your network and js console saying?
Try to zoom out, maybe fitBounds zooms your map too much. I had this problem. The solution was using maxSize option in fitBounds, see leaflet docs.

jqgrid edit call ajax every time

I'm trying to use jqgrid edit form, but I can't understand why jqgrid do not call asmx web method every time I select a row and I click on edit icon (jqgrid call ajax just the first time)
This is the code:
function Grid() {
var ret = Array();
var grid = jQuery("#grid");
var hideLoading = function () {
$("#lui_" + grid).hide();
$("#load_" + grid).hide();
}
var strSearch = "";
var strField = "";
var strOper = "";
//
// handler: si occupa di creare il contenuto del menu a tendina (form jqGrid)
//
var buildOptions = function (dataList) {
var response = dataList;
var option = "";
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
if (response[i]["selectedvalue"] == "on")
option += '<option role="option" selected="selected" value="' + response[i]["Codice"] + '">' + response[i]["Descrizione"] + '</option>';
else
option += '<option role="option" value="' + response[i]["Codice"] + '">' + response[i]["Descrizione"] + '</option>';
}
}
return option;
};
grid.jqGrid({
// setup custom parameter names to pass to server
prmNames: {
search: "isSearch",
nd: null,
rows: "numRows",
page: "page",
sort: "sortField",
order: "sortOrder"
},
// add by default to avoid webmethod parameter conflicts
postData: {
searchString: '',
searchField: '',
searchOper: ''
},
// setup ajax call to webmethod
datatype: function (postdata) {
$.ajax({
url: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/GetRoomRateDiscount") %>',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postdata),
dataType: "json",
success: function (data, st) {
if (data.d == "KO") {
grid.GridUnload();
jAlert("La ricerca non ha restituito alcun risultato", "Book2Guest");
return false;
}
if (st == "success") {
var grid = $("#grid")[0];
grid.addJSONData(JSON.parse(data.d));
ret = JSON.parse(data.d);
}
},
error: function (xhr, textStatus, errorThrown) {
jAlert("Si รจ verificato un errore: " + textStatus + " " + errorThrown + " -- " + $.parseJSON(xhr.statusText), "Book2Guest");
}
});
},
// this is what jqGrid is looking for in json callback
jsonReader: {
root: "rows",
page: "page",
total: "totalpages",
records: "totalrecords",
cell: "cell",
id: "id",
userdata: "userdata",
repeatitems: true
},
ajaxSelectOptions: {
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
data: {
rowId: function () {
if (JSON.stringify(grid.jqGrid('getRowData', grid.jqGrid('getGridParam', 'selrow'))['Codice']) == undefined)
return "";
return JSON.stringify(grid.jqGrid('getRowData', grid.jqGrid('getGridParam', 'selrow'))['Codice']);
}
}
},
colNames: ['ID', 'Rate'],
colModel: [
{ name: 'ID', index: 'ID', width: 10, align: "center", search: false, sorttype: 'int', searchoptions: { sopt: ['eq', 'ne', 'cn']} },
{
name: 'TariffaCodiceOfferta',
index: 'TariffaCodiceOfferta',
width: 50,
hidden: true,
formatter: 'select',
editable: true,
edittype: 'select',
editrules: { edithidden: true }, //, required: true },
editoptions: {
multiselect: true,
dataUrl: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/GetRoomRateListByRowId") %>',
buildSelect: function (data) {
var response = $.parseJSON(data.d);
var option = buildOptions(response);
var s = '<select>';
s += option;
return s + "</select>";
},
dataInit: function (elem) {
setTimeout(function () {
$(elem).multiselect({ selectedList: 10 });
}, 50);
},
multiple: true
}
},
],
rowNum: 10,
rowList: [10, 20, 30],
height: 'auto',
pager: '#gridpager',
viewrecords: true,
shrinkToFit: false,
loadComplete: function () {
hideLoading();
},
loadError: function () {
hideLoading();
},
editurl: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/SaveRoomDiscount") %>',
sortname: "ID",
sortorder: "asc",
caption: "Rate list",
onSelectRow: function (id, status) {},
ondblClickRow: function (rowid) {
grid.jqGrid('editGridRow', rowid,
{
width: 450,
height: 450,
closeOnEscape: true,
addCaption: "Add Rate",
editCaption: "Edit Rate",
bSubmit: "Salva",
bCancel: "Annulla",
bClose: "Chiudi",
bYes: "Si",
bNo: "No",
bExit: "Annulla",
editData: {
"codice": function () {
var selectedRow = grid.getGridParam("selrow");
var rowData = grid.getRowData(selectedRow);
return rowData["Codice"];
}
},
viewPagerButtons: false,
closeAfterEdit: true,
reloadAfterSubmit: true,
beforeShowForm: function (form) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
// Grabbed jQuery for grabbing offsets from here:
//http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
},
onClose: function (response, postdata) {
}
});
return;
},
gridComplete: function () {
if (grid.getGridParam('records') == 0) // are there any records?
DisplayEmptyText(true);
else
DisplayEmptyText(false);
},
emptyDataText: 'There are no records. '
})
grid.setGridWidth(900, true);
grid.jqGrid('navGrid', '#gridpager',
{
edit: true,
view: false,
add: false,
del: true,
search: false
},
//prmEdit
{
width: 450,
height: 300,
closeOnEscape: true,
addCaption: "Aggiungi Offerta",
editCaption: "Modifica Offerta",
bSubmit: "Salva",
bCancel: "Annulla",
bClose: "Chiudi",
saveData: "Sono state apportate delle modifiche, sei sicuro di voler continuare?",
bYes: "Si",
bNo: "No",
bExit: "Annulla",
editData: {
"Codice": function () {
var selectedRow = grid.getGridParam("selrow");
var rowData = grid.getRowData(selectedRow);
return rowData["Codice"];
}
},
viewPagerButtons: false,
closeAfterEdit: true,
reloadAfterSubmit: true,
beforeShowForm: function (form) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
// Grabbed jQuery for grabbing offsets from here:
//http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
},
onClose: function (response, postdata) {}
}
//prmSearch,
//prmView
);
return ret;
}
UPDATE: to solve this issue, you guys have to insert 'recreateForm: true' in the edit section of jqGrid
You current code don't have 'Codice' column in colModel, but you try to get the data from the column. Even if the original server response has the Codice property, the property will be saved only if you add additional hidden column with the same name.
Sorry, but to tell the trust I would recommend you to rewrite the whole code which you use. The usage of datatype as function is not good. Instead of that you can use jsonReader. The call JSON.parse(data.d) inside of $.ajax having dataType: "json" shows that you did one more important error in the webmethod on the server side. It shows that you make manual conversion of returned object to String instead of returning object from the web method. WebService convert the object to JSON automatically. Because of manual convention to JSON the returned data will be twice converted to JSON. Only because of the error in the server code you have to use JSON.parse(data.d) and can't just use jsonReader like described here for example.

Jquery AutoComplete Load Problem

Not Work
Jquery Code:
$('[id$=Name]').autocomplete('CallBack.aspx',{formatItem: function(item){return item.Name;}}).result(function(event, item) {
location.href = item.AGE;
});
Json:
var data = [{NAME:"John",AGE:"57"}];
Work
Jquery Code:
var data = [{NAME:"John",AGE:"57"}];
$('[id$=Name]').autocomplete(data,{formatItem: function(item){return item.Name;}}).result(function(event, item) {
location.href = item.AGE;
});
alt text http://img11.imageshack.us/img11/119/38235621.jpg
Help me pls how its make ? callback.aspx return json not work
Try changing your data to this:
var data = [{id:"John",value:"57"}];
EDIT
Here's a sample of what I think you're trying to do:
var data = [{NAME:"John",AGE:"57"}];
$('[id$=Name]').autocomplete('CallBack.aspx', {
formatItem: function(item) {
return item.NAME;
}}).result(function(event, item) {
location.href = 'somepage.aspx?age=' + item.AGE;
});
Basically you needed to capitalise return item.Name to return item.NAME.
Try This
<script type="text/javascript">
$(document).ready(function () {
$("#TextboxId").autocomplete({
source: function (request, response) {
$.ajax({
url: "URL",
type: "POST",
dataType: "json",
data: { ids: idstopass },
success: function (retrieveddata) {
alert(retrieveddata);
var dData = JSON.parse(retrieveddata);
alert(dData.Name);
},
error: function (request, status, error) {
console.log("Error! " + request.responseText);
}
})
},
});
})
</script>

Resources