How to make YUI datasource parse Null values in the dataset? - javascript

I am using YUI datatable and datasource to render data in one of my projects. The data returned happens to be NULL and YUI datasource is unable to parse it.
Below is the declaration code of datasource and datatable. For readability sake, I am seperating each of the declarations.
Column Descriptions declaration
var columnDescription =
[
{key:'Requirements'},
{key:'abc'},
{key:'xyz'}
];
This columnDescription is set in the function below.
DataSource Declaration
var dataSrcSample = new YAHOO.util.FunctionDataSource(getDataGrid);
myDataSource.connMethodPost = true;
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
myDataSource.responseSchema = {
fields:['Requirements',
{key:'abc',parser:YAHOO.util.DataSource.parseString},
{key:'xyz',parser:YAHOO.util.DataSource.parseString}]
};
getDataGrid function makes the call to server side to get the data from the server.
Below is the table definition itself.
YAHOO.example.sampleTable = function()
{
var columnDesc=columnDescription;
var myDataSource = dataSrcSample;
var oConfigs =
{
width:'100%'
};
var myDataTable = new YAHOO.widget.DataTable("tableContainerDiv", columnDesc, myDataSource, oConfigs);
}();
tableContainerDiv is declared in the html page. This is the container div.
The function that gets the JSON data from server.
function getDataGrid()
{
//calls backend and gets the data
}
The function is returning json string that has some null values. Datasource constructor is complaining following problems.
ERROR_DATAINVALID
ERROR_DATANULL
I checked the yui documentation and found that the string parser does not parse null values. I am wondering if there is any way to parse this data. Do I have to handleResponse parse the raw data? Any suggestions appreciated.

You need to create your own parser perhaps?
function parseNull(value) {
// This exact logic may be incorrect, depends on what you get for value in the null case
if (value=='null') {
return null;
}
YAHOO.util.DataSource.parseString(value);
}
Then you can specify:
{key:'abc',parser:parseNull}
To use your new parser

Related

pass collection of objects through http post in angular js

I have pass a collection of objects through http post in angular js.
The code is as follows:
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data.ContentId, { Selected: true }); // I could able to get all the selected objects here, No problem with it
var jsonData = angular.toJson(contents); //It is not able to convert to Json if there are more than 5 records
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent?jsonData=' + jsonData, {});
promise.success(function () {
window.location.reload();
});
[ReferrerFilterAttribute]
[HttpPost]
[System.Web.Http.ActionName("CmsPublishApprovedContent")]
public void CmsPublishApprovedContent(string jsonData)
{
var contents = JsonConvert.DeserializeObject<List<ContentNodeInWorkFlow>>(jsonData);
foreach (var content in contents)
{
_contentService.PublishContent(content.ContentId, userId);
}
}
}
The above code works fine if there are 5 records or less. If there are more records, I could able to get all the selected record
objects in the variable 'contents'. But the problem is occuring when converting to Json for all those objects. I
have about 500 records to pass through. How can do I it?
There is no specific reason to convert to JSON data. I just need to extract the ids of all the selected items. I have modified the above code as below:
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data, { Selected: true });
var abc = [];
angular.forEach(contents, function(content)
{
abc.push(content.ContentId); // got all the ids in the array now
});
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,{contents : abc});
promise.success(function () {
window.location.reload();
});
}
I have just took an array and pushed all the content ids into it. I could able to see all the ids in the array now. I tried to pass the array as above.
How to retrieve those array in the code behind.
[ReferrerFilterAttribute]
[HttpPost]
[System.Web.Http.ActionName("CmsPublishApprovedContent")]
public void CmsPublishApprovedContent(int[] abc)
{}
I do not see any values obtained under int[] abc. What will be the datatype for the parameter in the method call above.
You need second argument of $http.post method. You have to send such data by POST requests, not in query of url. You can put some data into body of the post request.
You need this:
var postBodyWithHugeAmountOFData = {data: [1,2,3,4,5...500]};
$http.post(url, postBodyWithHugeAmountOFData).success(function () {});
Also, you must be ready to handle this request in your backend.
is there any specific reason u want to pass this data as a JSON?.
if u r using Web API in that case u can pass the object as it is but only make sure that collection in web API method contains all the property in javascript collection
Thank you for all your posts. It's working fine without converting to Json. The code is as below.
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data, { Selected: true });
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,contents);
promise.success(function () {
window.location.reload();
});
}
and the signature would be
public void CmsPublishApprovedContent(List<ContentNodeInWorkFlow> abc)
{
}

ASP Web Pages Razor using AJAX to return array from Database

I'm working with ASP for my coursework and I am using Razor Web Pages to do an application. Now, I would like some help with retrieving information from the SQL database.
As it stands I make an ajax call like this:
$.ajax({
type: "POST",
url: "/timetabler/Includes/ajaxModulesByUserId",
data: { id: UserId },
success: function (data) {
alert(data);
if (data == "ERROR") {
alert("We are unable to store the theme you have selected, therefore the change will not be permanent.");
}
}
});
This quite simply calls ajaxModulesByUserId.cshtml passing a userID of like 1. Now this calls the file fantastically.
Now what I'm trying to do in my CSHTML is take the requested ID, then use my C# function:
public IEnumerable<dynamic> getAllQuery(string query)
{
return _db.Query(query);
}
To execute my query.
Now I call it in my Razor code like this:
string input = "";
input = Request["id"];
var arr = new List<string>();
if (!string.IsNullOrEmpty(input))
{
// Add new sheet to database
using (var repo = new initDatabase("SQLServerConnectionString"))
{
foreach (var row in repo.getAllQuery("SELECT * FROM Module WHERE userID = " + input))
{
arr.Add(""+row.moduleCode+","+row.moduleTitle+"");
}
#session.Serialize(arr);
}
}
So I return the rows from the database and put them into an array, now my problem is, getting those values to the javascript.
As it stands I'm using a trick I read from here Stackoverflow, by using a function like this:
public static string Serialize(object o)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(o);
}
This will actually let me see the values in Javascript, but I'm getting stuck as I end up with values like this:
How can I receive a clean array? and possibly even return ALL the rows from the database as I've had to do a messy way of passing the code and title in 1 array field but separated by a comma.
Would really appreciate it if you could help me get my output correct.
Thanks
The Web Pages framework includes a Json helper which can take your data and return it as JSON.
if (!Request["id"].IsEmpty())
{
using (var repo = new initDatabase("SQLServerConnectionString"))
{
var data = repo.getAllQuery("SELECT * FROM Module WHERE userID = #0", Request["id"])
Json.Write(data, Response.Output);
}
}

Flot.js & JQuery.Ajax: Create graph from key-value-pair

I'm trying to create a graph in mvc using flot.js. The graph will be a line graph with 3 lines on it. I have created a set of 3 list keyvaluepair with date/value to be plotted on the graph as shown in the code below. Currently i get : JavaScript runtime error: 'listvoltage' is undefined
Here's what I tried already:
Index.cshtml:
#if (Model != null)
{
foreach (var item in Model.BatteryInfo)
{
var listvoltage = new List<KeyValuePair<double, int>>();
var listtemperature = new List<KeyValuePair<double, int>>();
var listlevel = new List<KeyValuePair<double, int>>();
listvoltage.Add(new KeyValuePair<double, int>(
TMTMonitorAndCompare_Helpers.DateTimeHelpers.DateTimeToUnixTimestamp(item.TEST_DATE), Convert.ToInt32(item.battery_voltage)));
listtemperature.Add(new KeyValuePair<double, int>(
TMTMonitorAndCompare_Helpers.DateTimeHelpers.DateTimeToUnixTimestamp(item.TEST_DATE), Convert.ToInt32(item.battery_temperature)));
listlevel.Add(new KeyValuePair<double, int>(
TMTMonitorAndCompare_Helpers.DateTimeHelpers.DateTimeToUnixTimestamp(item.TEST_DATE), Convert.ToInt32(item.battery_level)));
CustomGraphinScript.js
$(document).ready(function () {
$.plot($("#placeholder"), listvoltage, { yaxis: { max: 1000 } });
});
Could anyone tell me what I need to do to the above to display this data on graph? is ajax required?
Razor file is executing on the server side. flot.js is executing on client/browser and they dont share the same type system. Thats why 'listvoltage' is undefined.
Put this in your razorfile. Lookout for Date conversion between .NET and Javascript. flot.js need Javascript timestamp.
#using System.Web.Script.Serialization
<script>
#{
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(listvoltage);
}
var timeserie = #Html.Raw(json);
</script>
Consider a Web API solution with JSON result and Ajax call.

google maps store locator modify hardcoded initialization to dynamic

I'm trying to modify this example
http://storelocator.googlecode.com/git/examples/panel.html
the javascript code is here:
https://gist.github.com/2725336
the aspect I'm having difficulties with is changing this:
MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet(
new storeLocator.Feature('Wheelchair-YES', 'Wheelchair access'),
new storeLocator.Feature('Audio-YES', 'Audio')
);
to create the FeatureSet from a function, so for example I have this function which parses a JSON object
WPmmDataSource.prototype.setFeatures_ = function(json) {
var features = [];
// convert features JSON to js object
var rows = jQuery.parseJSON(json);
// iterate through features collection
jQuery.each(rows, function(i, row){
var feature = new storeLocator.Feature(row.slug + '-YES', row.name)
features.push(feature);
});
return new storeLocator.FeatureSet(features);
};
so then change the first code snippet to something like
WPmmDataSource.prototype.FEATURES_ = this.setFeatures_(wpmm_features);
which returns an error:
Uncaught TypeError: Object [object Window] has no method 'setFeatures_'
I think you just have to make some changes to the WPmmDataSource.prototype and your setFeatures_ method:
WPmmDataSource.prototype = {
FEATURES_ : null,
setFeatures_ : function( json ) {
//Set up an empty FEATURES_ FeatureSet
this.FEATURES_ = new storeLocator.FeatureSet();
//avoid the use of "this" within the jQuery loop by creating a local var
var featureSet = this.FEATURES_;
// convert features JSON to js object
var rows = jQuery.parseJSON( json );
// iterate through features collection
jQuery.each( rows, function( i, row ) {
featureSet.add(
new storeLocator.Feature( row.slug + '-YES', row.name ) );
});
}
}
And with this, you don't have to do the assignment by returning a value from setFeatures_; it has direct access to the FEATURES_ member. So the line:
WPmmDataSource.prototype.FEATURES_ = this.setFeatures_(wpmm_features);
is no longer necessary. This also means that later, when you have created an instance of WPmmDataSource, your code can work like this:
var wpmd = new WPmmDataSource( /* whatever options, etc. you want */ );
wpmd.setFeatures_( json );
// Thereafter, wpmd will have its FEATURES_ set
I'm not exactly sure what you are trying to achieve, but I believe this will get you over the hurdle of your current stall. I hope this gets you moving forward -

Javascript array into jQuery .post AJAX call

I have a JAVASCRIPT array that looks like this:
postarray['min_price'] = 120000;
postarray['max_price'] = 150000;
I'm trying to pass this to an AJAX call via jQuery .post function so that the .PHP file gets it in this format:
$_REQUEST['query']['min_price'] = 120000;
$_REQUEST['query']['max_price'] = 150000;
So far I've tried:
$.post("ajax_findproperties.php", {query: postarray},
function(data){
// processing function with JSON result
}
,'json');
But I've had no luck. I even tried changing the var postarray to query and then tried query.serialize() in place of the bracketed variable block, but with no luck either.
When I check my status on Firebug, the AJAX call has absolutely no POST vars set whatsoever - complete blank.
The javascript array is not an array, it's an object. Define it before:
var postarray = {};
postarray['min_price'] = 120000;
postarray['max_price'] = 150000;
or replace with:
var postarray = {
min_price: 120000,
max_price: 150000
};
Now the JSON.stringify works:
alert(JSON.stringify(postarray));
Also see this example.
But this object should also be send without JSON.stringify():
$.post("ajax_findproperties.php", {query: postarray}, ... );
Have you tried converting it with JSON.stringify(); and then doing a json_decode(...); in the PHP script?
Try this solution : add [] to your query key
$.post("ajax_findproperties.php", { 'query[]': postarray },
function(data) { },
'json');
Source : http://api.jquery.com/jQuery.post/#example-2

Categories

Resources