I am trying to use JQPlot within a VB.NET application under .NET 3.5. On a button click, using jquery, I am trying to populate the JQPlot Chart with JSON derived data using a ASP.NET Webservices Source file (which is part of the solution).
The JSON data is sent by the web service but when it is presented to JQPlot I get the javascript error 'No Data Specified' which is generated by JQPlot code.
My code listing is as follows:
Code to listen for the button to be clicked:
$(document).ready(function () {
$('#<%=btnASMX1.ClientID%>').click(function () {
getElectricDataJSON();
return false;
});
});
Javascript code outside the 'document.ready' function:
function ajaxDataRenderer() {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
//url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "AccountsService.asmx/GetJSONData",
data: "{AccountID: " + $('#<%= hiddenAccountID.ClientID%>').val() + " }",
dataType: "json",
success: function (response) {
var ret = response.d;
// The following two lines just display the JSON data for testing purposes
$('#<%=outputASMX.ClientID%>').empty();
$('#<%=outputASMX.ClientID%>').html("<div>" + ret + "</div>");
return ret;
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
var jsonurl = "./jsondata.txt";
function getElectricDataJSON() {
var ret = ajaxDataRenderer();
var plot1 = $.jqplot('chart2', jsonurl, {
title: "AJAX JSON Data Renderer",
dataRenderer: ret, //$.jqplot.ciParser
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
}
The JSON data format is as follows:
[ { "todate": "2013-09-23T00:00:00", "Bill": 7095.65 }, { "todate": "2013-08-22T00:00:00", "Bill": 1137.96 }, { "todate": "2013-07-24T00:00:00", "Bill": 220429.41 }, ... ]
Any help or advice will be appreciated.
Thanks to #Fresh for their quick response. Here is the complete solution to my problem:
Code to listen for the button to be clicked:
$(document).ready(function () {
$('#<%=btnASMX1.ClientID%>').click(function () {
getElectricDataJSON();
return false;
});
});
JS function to get the data from a web service:
function ajaxDataRenderer() {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "AccountsService.asmx/GetJSONData",
data: "{AccountID: " + $('#<%= hiddenAccountID.ClientID%>').val() + " }",
dataType: "json",
success: function (response) {
ret = response.d; // return response string object
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
Data structure outputted by the web service is:
[ { "todate": "2013-09-23T00:00:00", "Bill": 7,095.65 }, { "todate": "2013-08-22T00:00:00", "Bill": 1,137.96 }, { "todate": "2013-07-24T00:00:00", "Bill": 220,429.41 }, ... ]
Data structure that is expected by JQPlot:
[ [ "2013-09-23T00:00:00", 7095.65 ] , [ "2013-08-22T00:00:00", 1137.96 ], [ "2013-07-24T00:00:00", 220429.41 ], ... ]
Note the removal of the comma's in the 'expected data' Bill field.
And finally, the function getElectricDataJSON() that is being called by btnASMX1 where 'chart2' is the ID of the div tags where the chart will be drawn.
function getElectricDataJSON() {
// Get JSON 'string' object
var ret = ajaxDataRenderer();
// If JSON string object is null, stop processing with friendly message
if (ret == null) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>CHARTS ARE NOT AVAILABLE AT THIS TIME</div>");
return false;
}
// Now push required data into a JSON array object
var sampleData = [], item;
$.each(ret, function (key, value) {
sampleData.push([value.todate, parseFloat(value.Bill.replace(/,/g, ""))]);
});
var plot = $.jqplot('chart2', [sampleData], {
title: 'AJAX JSON Data Renderer',
dataRenderer: sampleData,
...
});
}
The method signature for your datarender (i.e. ajaxDataRender) is wrong. The signature should look like this:
function(userData, plotObject, options) { ... return data; }
(See the documentation here)
In your example you are passing the datarenderer "ret" which is not a function with the correct datarender signature. Also the jsonurl you are passing to getElectricDataJSON() is redundant as at no point in your code is the data from "AccountsService.asmx/GetJSONData" persisted to "./jsondata.txt".
Hence you should change your code to this:
$(document).ready(function(){
function ajaxDataRenderer(url, plot, options) {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
url: url,
dataType: "json",
success: function (response) {
var ret = response;
// The following two lines just display the JSON data for testing purposes
$('#<%=outputASMX.ClientID%>').empty();
$('#<%=outputASMX.ClientID%>').html("<div>" + ret + "</div>");
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
var url = "AccountsService.asmx/GetJSONData";
function getElectricDataJSON() {
var plot1 = $.jqplot('chart2', url, {
title: "AJAX JSON Data Renderer",
dataRenderer: ajaxDataRenderer,
});
}
Related
This is the code for fetching the data from database using Json and displaying it in handsontable. I checked in console and it shows the data I am getting from database but somehow that data is not being displayed in handsontable.
```
<div id="example"></div>
<script type="text/javascript">
const container = document.getElementById('example');
var hot = new Handsontable(container, {
// data: getData(),
rowHeaders: true,
colHeaders: true,
licenseKey: 'non-commercial-and-evaluation',
colHeaders: true
});
$(document).ready(function () {
var result = null;
$.ajax({
url: 'someurl',
type: 'post',
dataType: 'json',
async: false,
success: function (res) {
result = res;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
console.log(result);
var resultdata = JSON.parse(JSON.stringify(result));
hot.loadData(resultdata);
});
</script>
This is the Code from controller that is fetching the data from the database and returning it. I don't know if I am returning right type of data or if the data returned needs to be serialized. Can anyone help me with this? I will really appreciate any help from anyone
public class SupplierTypeController : BaseController
{
[HttpGet]
public JsonResult Index()
{
IEnumerable<SupplierTypeDto> supplierType = new List<SupplierTypeDto>();
var apiResponse = Post<List<SupplierTypeDto>>("api/SupplierType/SuppliersType", null);
if (apiResponse != null)
{
if (apiResponse.Success)
{
supplierType = apiResponse.Data;
}
}
else
{
ShowErrorMesage(ResponseMessages.API_NoResponse);
}
return Json(supplierType,JsonRequestBehavior.AllowGet);
}
}
I have some code on a file that makes Ajax calls. This file is being called as a function by multiple other files that creates a new instance each time.
This is the JS code that is being called:
define(["underscore", "homeop", "domReady!"],
function (_, homeop, domready) {
var timeout = 500;
return function (opUrl, opList, onCallback) {
// IRRELEVANT CODE
var getFetch = function (optionName) {
$.ajax({
url: optionsUrl,
data: { optionNames: [optionName] },
type: "POST",
dataType: "json",
async: false,
traditional: true,
success: function (data) {
_.each(data, function (optionData, optionName) {
if (homeop.globalCache[optionName] === null) {
homeop.globalCache[optionName] = optionData;
}
});
},
error: function (message) {
console.error(message.responseText);
}
});
};
self.getInfo = function (optionName) {
if (homeop.globalCache[optionName] === undefined) {
if (!_.contains(homeop.getOption(), optionName)) {
getFetch(optionName);
}
// MORE IRRELEVANT CODE GOES HERE
In other JS files, I call the get function; for example
var these = new getOptions(optionsUrl, optionsList, onLoadCallback);
var getOpt = these.get(OptionsUrl);
The problem is I am making multiple calls to the get information from the database causing multiple call to my JS file. Each new instance of the JS file will create a ajax call.
Is there a way to wait for all the calls to be done and then get data from the database? In other words how can I somehow combine all the call to my 'getOption.js'?
Thanks
Try this.. You can also implement queue in place of stack
var optionStack = [];
var isAvailable = true;
var getFetch = function (optionName) {
if(isAvailable){
isAvilable = false; // function not available now
}
else {
optionStack.push(optionName)
return;
}
$.ajax({
url: optionsUrl,
data: { optionNames: [optionName] },
type: "POST",
dataType: "json",
async: false,
traditional: true,
success: function (data) {
_.each(data, function (optionData, optionName) {
if (homeop.globalCache[optionName] === null) {
homeop.globalCache[optionName] = optionData;
}
});
},
error: function (message) {
console.error(message.responseText);
},
done: function (){
isAvailable = true;
if(optionStack.length > 0){
getFetch(optionStack.pop());
}
}
});
};
Here is the web method, which I use before for another thing, and it works:
[WebMethod]
public static string GetTests()
{
return GetData().GetXml();
}
public static DataSet GetData()
{
DataSet ds = new DataSet();
BusinessLayer.StudentsController oStudent = new BusinessLayer.StudentsController();
oStudent.Action = "page";
oStudent.PageIndex = 0;
oStudent.PageSize = int.Parse(System.Configuration.ConfigurationManager.AppSettings["PageSize"].ToString());
DataTable dt1 = oStudent.Select();
DataTable dt2 = dt1.Copy();
dt2.TableName = "Students";
ds.Tables.Add(dt2);
DataTable dt = new DataTable("PageCount");
dt.Columns.Add("PageCount");
dt.Rows.Add();
dt.Rows[0][0] = oStudent.PageCount;
ds.Tables.Add(dt);
return ds;
}
JavaScript:
$('#selectDynamic1').select2({
placeholder: "Search for a movie",
minimumInputLength: 1,
multiple: true,
ajax: {
url: "Default.aspx/GetTests",
type: 'POST',
params: {
contentType: 'application/json; charset=utf-8'
},
dataType: 'json',
data: function (term, page) {
return JSON.stringify({ q: term, page_limit: 10 });
},
results: function (data) {
return {results: data};
},
},
formatResult: formatResult,
formatSelection: formatSelection,
/*initSelection: function(element, callback) {
var data = [];
$(element.val().split(",")).each(function(i) {
var item = this.split(':');
data.push({
id: item[0],
title: item[1]
});
});
//$(element).val('');
callback(data);
}*/
});
function formatResult(node) {
alert('');
return '<div>' + node.id + '</div>';
};
function formatSelection(node) {
alert('');
return node.id;
};
Please help, GetTests is not even firing, I want to bring the student through SQL then fill the select2.
First, you shoul ry to change the HTTP verb to GET, as you are not posting data to the server, you want to get data from it:
ajax: {
...
type: 'GET',
...
}
Secondly, you are expecting JSON from the server, but in the GetData method, you are creating an XML document - at least the code conveys this. This may be one cause, why your code does not work.
I have these ajax calls that need to get called when the previous one is success, meaning once the first ajax is OK, call the 2nd ajax, once the 2nd ajax is OK call the 3rd one, etc so on. I started with a few ajax calls so it was fine to chain them up like this below but now I have about 20 of them and it'd be a mess to chain them up like this.
$.ajax({
url: 'urlThatWorks1',
success: function (data) {
//call someMethod1 with data;
$.ajax({
url: 'urlThatWorks2',
success: function (data) {
//call method2 with data;
//another ajax call ... so on
}
}.... 19 level deep
So I need to make it bit easier to read and maintain so I'm thinking something like
var ajaxArray = [];
var function1 = $.ajax('urlThatWorks1', data I get back from the 'urlThatWorks1' call);
myArray.push(function1);
var function2 = $.ajax('urlThatWorks2', data I get back from the 'urlThatWorks2' call);
myArray.push(function2);
//etc 19 others
myArray.each(index, func){
//Something like $.when(myArray[index].call()).done(... now what?
}
Hope this makes sense, I'm looking for a way of ajax call array from which I can call an ajax call on whose success I call the next ajax in the array. Thanks.
Create a recursive function to be called in sequence as the ajax requests return data.
var urls = [ "url.1", "url.2", ... ];
var funcs = [];
function BeginAjaxCalls()
{
RecursiveAjaxCall(0, {});
}
function RecursiveAjaxCall(url_index)
{
if (url_index >= urls.length)
return;
$.ajax(
{
url: urls[url_index],
success: function(data)
{
funcs[url_index](data);
// or funcs[urls[url_index]](data);
RecursiveAjaxCall(url_index + 1);
}
});
}
funcs[0] = function(data)
// or funcs["url.1"] = function(data)
{
// Do something with data
}
funcs[1] = function(data)
// or funcs["url.2"] = function(data)
{
// Do something else with data
}
Try
$(function () {
// requests settings , `url` , `data` (if any)
var _requests = [{
"url": "/echo/json/",
"data": JSON.stringify([1])
}, {
"url": "/echo/json/",
"data": JSON.stringify([2])
}, {
"url": "/echo/json/",
"data": JSON.stringify([3])
}];
// collect responses
var responses = [];
// requests object ,
// `deferred` object , `queue` object
var requests = new $.Deferred() || $(requests);
// do stuff when all requests "done" , completed
requests.done(function (data) {
console.log(data);
alert(data.length + " requests completed");
$.each(data, function (k, v) {
$("#results").append(v + "\n")
})
});
// make request
var request = function (url, data) {
return $.post(url, {
json: data
}, "json")
};
// handle responses
var response = function (data, textStatus, jqxhr) {
// if request `textStatus` === `success` ,
// do stuff
if (textStatus === "success") {
// do stuff
// at each completed request , response
console.log(data, textStatus);
responses.push([textStatus, data, $.now()]);
// if more requests in queue , dequeue requests
if ($.queue(requests, "ajax").length) {
$.dequeue(requests, "ajax")
} else {
// if no requests in queue , resolve responses array
requests.resolve(responses)
}
};
};
// create queue of request functions
$.each(_requests, function (k, v) {
$.queue(requests, "ajax", function () {
return request(v.url, v.data)
.then(response /* , error */ )
})
})
$.dequeue(requests, "ajax")
});
jsfiddle http://jsfiddle.net/guest271314/6knraLyn/
See jQuery.queue() , jQuery.dequeue()
How about using the Deferred approach. Something like:
var arrayOfAjaxCalls = [ { url: 'https://api.github.com/', success: function() { $("#results").append("<p>1 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>2 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>3 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>4 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>5 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>6 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>7 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>8 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>9 done</p>"); } }
];
loopThrough = $.Deferred().resolve();
$.each(arrayOfAjaxCalls, function(i, ajaxParameters) {
loopThrough = loopThrough.then(function() {
return $.ajax(ajaxParameters);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="results"></div>
You could use the async library, which has a bunch of functions like waterfall or series which could solve your problem.
https://github.com/caolan/async#series
https://github.com/caolan/async#waterfall
As the title suggests I would like to load remote data once only.
I thought about loading a data with independent ajax call and set it "locally" at the control but wonder if there is more "built in" way to do so...
a solution can be found here:
https://github.com/ivaynberg/select2/issues/110
$("#selIUT").select2({
cacheDataSource: [],
placeholder: "Please enter the name",
query: function(query) {
self = this;
var key = query.term;
var cachedData = self.cacheDataSource[key];
if(cachedData) {
query.callback({results: cachedData.result});
return;
} else {
$.ajax({
url: '/ajax/suggest/',
data: { q : query.term },
dataType: 'json',
type: 'GET',
success: function(data) {
self.cacheDataSource[key] = data;
query.callback({results: data.result});
}
})
}
},
width: '250px',
formatResult: formatResult,
formatSelection: formatSelection,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
});
Edit:
I might have misinterpreted your question. if you wish to load all data once, then use that is Select2, there is no built in functionality to do that.
Your suggestion to do a single query, and then use that stored data in Select2 would be the way to go.
This is for Select2 v4.0.3:
I had this same question and got around it by triggering an AJAX call and using the data returned as the initialized data array.
// I used an onClick event to fire the AJAX, but this can be attached to any event.
// Ensure ajax call is done *ONCE* with the "one" method.
$('#mySelect').one('click', function(e) {
// Text to let user know data is being loaded for long requests.
$('#mySelect option:eq(0)').text('Data is being loaded...');
$.ajax({
type: 'POST',
url: '/RetrieveDropdownOptions',
data: {}, // Any data that is needed to pass to the controller
dataType: 'json',
success: function(returnedData) {
// Clear the notification text of the option.
$('#mySelect option:eq(0)').text('');
// Initialize the Select2 with the data returned from the AJAX.
$('#mySelect').select2({ data: returnedData });
// Open the Select2.
$('#mySelect').select2('open');
}
});
// Blur the select to register the text change of the option.
$(this).blur();
});
This worked well for what I had in mind. Hope this helps people searching with the same question.
To load data once:
Assumptions:
You have a REST API endpoint at /services that serves a JSON array of objects
The array contains objects which have at least a "name" and "id" attribute. Example:
[{"id": 0, "name": "Foo"}, {"id": 1, "name": "Bar"}]
You want to store that array as the global 'services_raw'
First, our function to load the data and create the global 'services_raw' (AKA 'window.services_raw'):
fetchFromAPI = function() {
console.log("fetchFromAPI called");
var jqxhr = $.ajax(
{
dataType:'json',
type: 'GET',
url: "/services",
success: function(data, textStatus, jqXHR) {
services_raw = data;
console.log("rosetta.fn.fetchServicesFromAPI SUCCESS");
rosetta.fn.refreshServicesSelect();
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error inside rosetta.fn.fetchServicesFromAPI", errorThrown, textStatus, jqXHR);
setTimeout(rosetta.fn.fetchServicesFromAPI(), 3000); // retry in 3 seconds
}
}
)
.done(function () {
console.log("success");
console.log(jqxhr);
})
.fail(function () {
console.log("error");
})
.always(function () {
console.log("complete");
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function () {
console.log("second complete");
});
};
Second, our Select2 instantiation code which transforms our data into a format that Select2 can work with:
refreshServicesSelect = function () {
// ref: http://jsfiddle.net/RVnfn/2/
// ref2: http://jsfiddle.net/RVnfn/101/ # mine
// ref3: http://jsfiddle.net/RVnfn/102/ # also mine
console.log('refreshServicesSelect called');
$("#add-service-select-service").select2({
// allowClear: true
data: function() {
var arr = []; // container for the results we're returning to Select2 for display
for (var idx in services_raw) {
var item = services_raw[idx];
arr.push({
id: item.id,
text: item.name,
_raw: item // for convenience
});
}
return {results: arr};
}
});
};
Here's what the Select2 element in HTML should look like before your call the above functions:
<input id="add-service-select-service" type="hidden" style="width:100%">
To use all of this, call (in JS):
window.fetchFromAPI();
window.refreshServicesSelect();
Lastly, here's a JSFiddle where you can play with a similar thing: http://jsfiddle.net/RVnfn/102/
Basically, in my example above, we're just using ajax to populate the equivalent of window.pills in the Fiddle.
Hope this helps :)
Please reply if you know how to do this via the Select2 .ajax function, as that would be a bit shorter.
In my condition, it is working perfectly with the given code
$('#itemid').select2({
cacheDataSource: [],
closeOnSelect: true,
minimumInputLength: 3,
placeholder: "Search Barcode / Name",
query: function(query) {
// console.log(query);
self = this;
var key = query.term;
var cachedData = self.cacheDataSource[key];
if(cachedData) {
query.callback({results: cachedData});
return;
} else {
$.ajax({
url: "./includes/getItemSelect2.php",
data: { value : query.term },
dataType: 'json',
type: 'POST',
success: function(data) {
self.cacheDataSource[key] = data;
query.callback({results: data});
}
});
}
},
});
And my data return from the ajax is in this form
<?php
$arr = [
["id" => 1, "text" => "Testing"],
["id" => 2, "text" => "test2"],
["id" => 3, "text" => "test3"],
["id" => 4, "text" => "test4"],
["id" => 5, "text" => "test5"]
];
echo json_encode($arr);
exit();
?>