Chart js line with asp.net - javascript

i'm trying to do a line chart with chart js in ASP.NET but this don't work, before I tried with a pie chart and this working fine, but with line chart doesn't work, I think the response is incorrect because in the console displays "uncaught SyntaxError: unexpected token : ".
This is the code c# :
[WebMethod]
public static string GetChart(string country)
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
sb.Append("labels:[\"January\",\"February\",\"March\",\"April\",\"May\",\"June\"],");
sb.Append("datasets:[");
System.Threading.Thread.Sleep(50);
string color = "rgba(220,220,220,0.2)";
//
sb.Append("{");
sb.Append(string.Format("fillColor:\"{0}\", strokeColor:\"{1}\", pointColor:\"{2}\", pointStrokeColor:\"{3}\", data:{4}", color, "#ACC26D", "#fff", "#9DB86D", "[203,156,99,251,305,247]"));
//
sb.Append("}");
sb.Append("]");
sb.Append("};");
return sb.ToString();
}
And this is the Javascript:
<script type="text/javascript">
function LoadChart() {
var chartType = parseInt($("[id*=rblChartType] input:checked").val());
$.ajax({
type: "POST",
url: "inicioCliente.aspx/GetChart",
data: "{country: '" + $("[id*=ddlCountries]").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
$("#dvChart").html("");
$("#dvLegend").html("");
var data = eval((r.d));
var el = document.createElement('canvas');
$("#dvChart")[0].appendChild(el);
var ctx = el.getContext('2d');
var userStrengthsChart;
switch (chartType) {
case 1:
userStrengthsChart = new Chart(ctx).Line(data);
break;
case 2:
userStrengthsChart = new Chart(ctx).Doughnut(data);
break;
}
for (var i = 0; i < data.length; i++) {
var div = $("<div />");
div.css("margin-bottom", "10px");
div.html("<span style = 'display:inline-block;height:10px;width:10px;background-color:" + data[i].color + "'></span> " + data[i].text);
$("#dvLegend").append(div);
}
},
failure: function (response) {
alert('There was an error.');
}
});
}
$(function () {
LoadChart();
$("[id*=ddlCountries]").bind("change", function () {
LoadChart();
});
$("[id*=rblChartType] input").bind("click", function () {
LoadChart();
});
});
</script>

after some time I found the solution, the problem was in the eval method, I need add "()"
var data = (eval("(" + r.d + ")"));
Thanks

Related

How to get data from a JavaScript to controller and store it in the database

I want to get the location from this JavaScript to the controller and store it in the database:
var currPosition;
navigator.geolocation.getCurrentPosition(function(position) {
updatePosition(position);
setInterval(function() {
var lat = currPosition.coords.latitude;
var lng = currPosition.coords.longitude;
jQuery.ajax({
type: "POST",
url: "myURL/location.php",
data: 'x=' + lat + '&y=' + lng,
cache: false
});
}, 1000);
}, errorCallback);
var watchID = navigator.geolocation.watchPosition(function(position) {
updatePosition(position);
});
function updatePosition(position) {
currPosition = position;
}
function errorCallback(error) {
var msg = "Can't get your location. Error = ";
if (error.code == 1)
msg += "PERMISSION_DENIED";
else if (error.code == 2)
msg += "POSITION_UNAVAILABLE";
else if (error.code == 3)
msg += "TIMEOUT";
msg += ", msg = " + error.message;
alert(msg);
}
To send post with .ajax():
// ....
let formData = new FormData();
const lat = currPosition.coords.latitude;
const lng = currPosition.coords.longitude;
formData.append("x", lat);
formData.append("y", y lng;
$.ajax({
url: "myURL/location.php", // update this with you url
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'POST',
success: function(data){
const response = jQuery.parseJSON(data);
}
});
//....
To receive post data in codeigniter :
$x = $this->input->post('x');
$y = $this->input->post('y');
you just need to change uri parameter to codeginter route that you have
setInterval(function(){
....
url: "change this to codeigniter route url",
....
}, 1000);
then in the controller you just need to save those parameter,
class X extends CI_Controller{
function update_position(){
$x = $this->input->post('x');
$y = $this->input->post('y');
// then save it using model or query.
$this->model_name->insert([...])
}
}

request.getParameter("pgIndex") always returns null in the servlet

I am trying to paginate rows of a table inside my servlet using hibernate.But once I click on the desire index of the page it always gives me only the first set of row of the table.So I put System.out.print() at every major sections and finally found out that the request.getParameter("pgIndex") is always returns null.
My servlet code:
int pageIndex = 0;
int totalNumberOfRecords = 0;
int numberOfRecordsPerPage = 5;
String sPageIndex = request.getParameter("pgIndex");
//whether pgIndex=1 or pgIndex=2 in the url, always returns null as the output.
System.out.println("pg - " + sPageIndex);
pageIndex = sPageIndex == null ? 1 : Integer.parseInt(sPageIndex);
int s = (pageIndex * numberOfRecordsPerPage) - numberOfRecordsPerPage;
List<ProductHasSize> phs = ses.createCriteria(ProductHasSize.class)
.setFirstResult(s)
.setMaxResults(numberOfRecordsPerPage)
.list();
for (ProductHasSize pro : phs) {... some html content here...}
Criteria criteriaCount = ses.createCriteria(ProductHasSize.class);
criteriaCount.setProjection(Projections.rowCount());
totalNumberOfRecords = (int) (long) (Long) criteriaCount.uniqueResult();
int noOfPages = totalNumberOfRecords / numberOfRecordsPerPage;
if (totalNumberOfRecords > (noOfPages * numberOfRecordsPerPage)) {
noOfPages = noOfPages + 1;
}
for (int j = 1; j <= noOfPages; j++) {
String myurl = "products.jsp?pgIndex=" + j;
String active = j == pageIndex ? "active" : "";
s2 = s2 + "<li class='" + active + "'>" + j + "</li>";
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("[{\"d1\":\"" + s1 + "\",\"d2\":\"" + s2 + "\"}]");
products.jsp
<div class="row">
<div class="col-md-12">
<ul class="pagination" id="pagId"></ul>
</div>
</div>
JavaScript
$(document).ready(function () {
$.ajax({
url: 'AdimnProductFilterAction',
dataType: 'json',
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
});
UPDATE :
$(document).on("click", "#pagId a", function (event) {
//tried with adding another function . But still returns null.
event.preventDefault();
var para = $(this).attr('href').match(/\d+/);
$.ajax({
url: 'AdimnProductFilterAction',
dataType: 'json',
data: {pgIndex: para},
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
});
Thanks in advance.
In sending JSON data, you will not simply receive it as request parameter. Instead, just add "normal" parameter:
Sending as HTTP POST
$.ajax({
url: 'AdimnProductFilterAction',
type: 'POST',
data: {
'pgIndex': para
},
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
Or as HTTP GET
$.ajax({
url: 'AdimnProductFilterAction?pgIndex='+para,
cache: false,
success: function (data) {
$.each(data, function (key, value) {
$('#proFilterTab').html(value.d1);
$('#pagId').html(value.d2);
});
},
error: function () {
alert('error');
}
});
To add parameter into your servlet call.

After submit a reply by Ajax Its display a blank data space

After submit a reply without 1st post Its display a blank data space and after refresh page its show reply.
What is problem here please.
..............................................................................
This is my script
var inputAuthor = $("#author");
var inputComment = $("#comment");
var inputReplycom = $(".replycom");
var inputImg = $("#img");
var inputUrl = $("#url");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var replyList = $("#replynext");
function updateReplybox() {
var tutid = inputTutid.attr("value");
$.ajax({
type: "POST",
url: "reply.php",
data: "action=update&tutid=" + tutid,
complete: function (data) {
replyList.append(data.responseText);
replyList.fadeIn(2000);
}
});
}
$(".repfrm").click(function () {
error.fadeOut();
if (checkForm()) {
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var img = inputImg.attr("value");
var replycom = inputReplycom.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
$('.reply_here').hide();
$("#loader").fadeIn(400).html('<br><img src="loaders.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
//send the post to submit.php
$.ajax({
type: "POST",
url: "reply.php",
data: "action=insert&author=" + author + "&replycom=" + replycom + "&url=" + url + "&img=" + img + "&parent_id=" + parent_id + "&tutid=" + tutid,
complete: function (data) {
error.fadeOut();
$("#loader").hide();
replyList.append(data.responseText);
updateReplybox();
$("#repfrm").each(function () {
this.reset();
});
}
});
} else //alert("Please fill all fields!");
error_message();
});
Probably all this code should be inside a $(document).ready({ ... });
To debug: Open chrome inspector and put a brakepoint at this line: var tutid = inputTutid.attr("value"); and check for what is inside inputTutid variable.
Also you can try
inputTutid.val();
instead of
inputTutid.attr("value");

Ajax send image to server

I am working phonegap application. I want to send data image to server but i can not sent it.
function addSiteToServer() {
var cId = localStorage.getItem("cId");
var sname = $('#sitename').val();
var slat = $('#lat').val();
var slng = $('#lng').val();
var storedFieldId = JSON.parse(localStorage["field_id_arr"]);
var p = {};
for (var i = 0; i < storedFieldId.length; i++) {
var each_field = storedFieldId[i];
var val_each_field = $('#' + each_field).val();
p[each_field] = val_each_field;
console.log("p" + p);
}
var online = navigator.onLine;
if (online) {
var data = {
site: {
collection_id: cId,
name: sname,
lat: slat,
lng: slng,
properties: p
}
};
//function sending to server
$.ajax({
url: App.URL_SITE + cId + "/sites?auth_token=" + storeToken(),
type: "POST",
data: data,
enctype: 'multipart/form-data',
crossDomain: true,
datatype: 'json',
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log("data: " + data);
alert("successfully.");
},
}
Looks like you are using the normal method to send data/image to server which is not recommended by Phonegap/Cordova Framework.
I request you to replace your code with the following method which works as you expected,I also used local storage functionality to send values to server,
function sendDataToServer(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = {};
params.some_text = localStorage.getItem("some_text");
params.some_id = localStorage.getItem("some_id");
params.someother_id = localStorage.getItem("someother_id");
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://example.co.uk/phonegap/receiveData.php"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode+"Response = " + r.response+"Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
function saveData(){
sendDataToServer(globalvariable.imageURI);
alert("Data Saved Successfully");
}
Hope this helps.

Help passing variables between functions in ajax callbacks

OK I am building something that makes an ajax request to one server where it determines the url it needs to then make a new ajax request to another place. Everything is progressing thanks to all the help at SO =) .. however I am stuck again. I am struggling with getting the variables to return to the different functions as I need. The second (jsonp) request returns a json function which looks like :
jsonResponse(
{"it.exists":"1"},"");
and my code...
var img = "null";
var z = "null";
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "connect.php",
dataType: "xml",
success: function parseXml(data)
{
$(data).find("ITEM").each(function()
{
query = $("SKU", this).text();
query = 'http://domain.com/' + query + '?req=exists,json';
img = $("SKU", this).text();
img = '<img src="http://domain.com/' + img + '">';
var date =$("LAST_SCAN" , this).text();
$.ajax({
url: query,
dataType: 'jsonp'
});
$("table").append('<tr>'+'<td>' + (date) + '</td>' + '<td>' + (z) + '</td>');
});
}
});
});
// function required to interpret jsonp
function jsonResponse(response){
var x = response["it.exists"];
// console.log(x);
if (x == 0) {
console.log("NO");
var z = "NO IMG";
}
if (x == 1) {
console.log(img);
//this only returns the first image path from the loop of the parseXml function over and over
var z = (img);
}
return z;
}
So I guess my problem is a two parter.. one how do I get the img variable to loop into that if statement and then once that works how can I return that z variable to be used in the first xml parser?
Try this synchronous approach:
var itemQueue = [];
$(document).ready(function ()
{
$.ajax({
type: "GET",
url: "connect.php",
dataType: "xml",
success: function parseXml(data)
{
itemQueue= $(data).find("ITEM").map(function ()
{
return {
sku: $("SKU", this).text(),
date: $("LAST_SCAN", this).text()
};
}).get();
getNextItem();
}
});
});
function getNextItem()
{
var item = itemQueue[0];
var query = "http://domain.com/" + item.sku + "?req=exists,json";
$.ajax({
url: query,
dataType: 'jsonp'
});
}
function jsonResponse(response)
{
var item = itemQueue.shift();
if (itemQueue.length)
{
getNextItem();
}
var x = response["it.exists"];
var z = x == "0" ? "NO IMG" : "<img src=\"http://domain.com/" + item.sku + "\">";
$("table").append("<tr><td>" + item.date + "</td><td>" + z + "</td>");
}
Store 'date' in a global variable, and move the logic to append HTML elements into the jsonResponse function. You cannot return control flow from jsonResponse because it's called asynchronously, but you can continue doing anything you'd like from that function.

Categories

Resources