jqGrid Initialize DropDownList Items - javascript

I have a jqGrid control which includes a dropdownlist field. The items in the list come from a method on the server side using ajax, but I'm not sure how to structure the returned json to make it compatible with the grid. I looked at this question and according to the answers, it seems like the grid expects the following format for dropdowns:
[value] : [display text]
I'm relatively new to JavaScript and am not sure what type of data this is (I'm assuming it's a key-value pair?) so I don't know how create an array of this type from my json object. This is what I tried:
function populateTable(){
$.ajax({
type: "POST",
url: "MyHttpHandler.ashx",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var jsonObject = jQuery.parseJSON(result.d);
var dropdpwnvalues = new[];
for(var i = 0; i< jsonObject.length; i++){
dropdpwnvalues.push({ jsonObject[i].id : jsonObject[i].name });
}
// The rest of the function
);
}
dropdpwnvalues variable is the one that gets bound to the grid. Note that jsonObject does have an id and name on it, but this syntax
dropdpwnvalues.push({ jsonObject[i].id : jsonObject[i].name });
is obviously incorrect. Any ideas how I can make the list from this json object?

I figured the easiest way to do this is by creating a string instead of an object array:
var sessionStream = ""
for (var i = 0; i < sessions.length; i++) {
sessionStream += sessions[i].id + ":" + sessions[i].name + ";";
}
// Remove the trailing ';' in the stream
sessionStream = sessionStream.substring(0, sessionStream.length - 1);
I originally thought the grid was expecing a list. It can bind to a string just fine.

You need to return JSON value of the Select list in following format :
{1:'One',2:'Two'}
And , i believe you are using this in loadcomplete event of jqGrid. So, to set the JSON value simply use it as ,
loadcomplete : function(){
$.ajax({
type: "POST",
url: "MyHttpHandler.ashx",
dataType: "json",
success : function ( result) {
$("#gridId").setColProp('columnName', { editoptions: { value: result}});
}
});
}

Related

Parsing Json data from asp.net webservice and populating it in asp.net dropdownlist

i am trying to populate an asp.net dropdownlist returned as JSON from my webservice.
WebService
[WebMethod(EnableSession = true)]
public string GetActiveDepositAccountsForLoanAlert(string customerId)
{
var data = BusinessLayer.SMS.SmsSetup.GetActiveDepositAccountsForLoanAlert(customerId.ToLong());
var json = new JavaScriptSerializer().Serialize(data);
return json;
}
The webservice returns
[{"AccountNumber":"NS-0000092"},{"AccountNumber":"6MR-0000002"},{"AccountNumber":"1YFD-0000007"}]
I am calling the data from ajax call and populating it to my dropdownlist.
Ajax call
function GetActiveDepositAccounts(customerrId) {
var customerId = $('#CustomerIdHiddenField').val();
var data = { customerId: $('#CustomerIdHiddenField').val() };
var json_data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "/WebMethods/Misc.asmx/GetActiveDepositAccountsForLoanAlert",
data: json_data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(r) {
var depositRadioList = $("[id*=DepositAccountDropDownList]");
depositRadioList.empty().append('<option selected="selected" value="0">Please select</option>');
for (var i = 0; i < r.d.length; i++) {
depositRadioList.append('<option>' + r.d[i] + '</option>');
}
}
The data gets populated in json.In my dropdown i only want the accountnumber as
NS-0000092.I am getting the whole json in my dropdown.i have searched and seen lots of question with this Json parse thing in here.But couldnt get hold of this.It isnt that i didnt tried,I am newbie,so before marking this as duplicate,please for once have a look at the code.Thank you.
I can't shake the feeling that because your GetActiveDepositAccountsForLoanAlert is returning a string and not an object, r.d is being seen as a string. Try one of 2 things. Either:
Change your method signature to return data type and don't use the JavaScriptSerializer. or,
In your OnSuccess function, add var data = JSON.parse(r.d) and use that variable in your for loop.
Single Object Returned
If by "whole json", you mean you are getting a single {"AccountNumber":"6MR-0000002"} per option -- try outputting the value of the target AccountNumber object (e.g. r.d[i].AccountNumber or r.d[i]["AccountNumber"]).
Modified Function
var depositRadioList = $("[id*=DepositAccountDropDownList]");
depositRadioList.empty().append('<option selected="selected" value="0">Please select</option>');
for (var i = 0; i < r.d.length; i++) {
depositRadioList.append('<option>' + r.d[i].AccountNumber + '</option>');
}
Array of Objects Returned
If the result per option is an entire AccountNumber array of objects, you'll need to loop through your r object until you get to the list of Account Number objects.
Take a look at my Example JS Fiddle. There is probably a cleaner way to do this, but to present the principle, I've laid out nested loops to get you into the list of object values that you need for your <select></select>.
I'm using the JQuery $.each() method, but you can use the for loop. I recommend just using one or the other for consistency. If the data set is really large, for loops have better performance.

Sending Json Array in POST request for JavaScript

I am having trouble in sending a JSON array in an AJAX call. Following is my Code
var company_name = $('input#company_name').val();
var company_localname = $('input#company_localname').val();
var companytype = $('#companytype').val();
if (companytype == 'retailer') {
var bank_name = $('input#bank_name').val();
var account_title = $('input#account_title').val();
var business_nature = $('input#business_nature').val();
var gross_sales = $('input#gross_sales').val();
}
After getting all the values I am storing the data in Json like the following
var jsonArray = [];
jsonArray["company_name"] = company_name;
jsonArray["company_localname "] = company_localname;
if (companytype == 'retailer') {
jsonArray["bank_name"] = bank_name;
jsonArray["account_title"] = account_title;
jsonArray["business_nature"] = business_nature;
jsonArray["gross_sales"] = gross_sales;
}
Now for sending the jsonArray in Ajax call
$.ajax({
url : url,
type : "POST",
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
data : JSON.stringify(jsonArray),
success : function(response) {
//Some Code here
}
});
Please help me sending data. Or tell me if I am making any mistake here. Thank you
In JavaScript / JSON arrays are 0 based indexed data structures. What you are using here is more like a Map:
var jsonArray = [];
jsonArray["company_name"]=company_name ;
In JavaScript you cannot use arrays like this (well you can, but it is probably not what you want). For a data structure like a map that maps strings to objects rather then an index to objects, just use an object.
Or in short: Use var jsonArray = {}; rather than var jsonArray = []; The {} will create an object that you can assign properties to like you did. And JSON.stringify will correctly translate this into a JSON string like this:
{ "property": value, "otherProperty", otherValue }
Do something like this.
$.ajax({
url: url,
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.parse(JSON.stringify(jsonArray)),
success: function(response) {
//Some Code here
}
});
The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing. Read more about JSON.parse() method
The JSON.stringify() method converts a JavaScript value to a JSON string. Read more about JSON.stringify() method
Here simply you can send an array and Parse it in server side.
$.ajax({
url : url,
type : "POST",
dataType : 'json',
data : jsonArray,
success : function(response) {
//Some Code here
}
});

How to send array in AJAX using JSON

I am fairly new to JS and AJAX, and for some reason I can not send my dynamically generated and read data via AJAX. How do I properly send an array via AJAX to PHP script?
I have tried following the instructions but I can not get the AJAX to send the data. The first try was a complete bust, the second gets error:
Uncaught TypeError: Illegal invocation
but it seems to originate from the JS-library instead of my code (though the code is most probably the reason for it!) and I do not know what to do with it.
//first thing I tried
var i = 1, j = 0, cu = [], cu2 = [];
while (i <= tilit ) {
cu[j] = document.getElementById("til_nro_"+i);
console.log(cu[j].value);
i++;
}
var dynamic_account_value = JSON.stringify(cu);
jQuery.ajax({
type: "POST",
url: 'http:mysite.php',
dataType: 'json',
data: { dynamic_account_count:tilit, db:cu , id:id, result:dynamic_account_value
}
});
//2nd thing I tried
var i = 1, j = 0, cu = [], cu2 = [];
while (i <= tilit ) {
cu[j] = document.getElementById("til_nro_"+i);
cu2.push(JSON.parse(cu[j].value));
i++;
}
var tilinrot_lisa = JSON.stringify(cu2);
jQuery.ajax({
type: "POST",
url: 'http:mysite.php',
dataType: 'json',
data: { dynamic_account_count:tilit, db:cu , id:id, result:tilinrot_lisa
}
});
First, give them something that makes selection easier, like a common class. Second, use jquery serialize
$.ajax({
url : "foo",
data : $(".bar").serialize(),
success : function(response) {}
})
Try this code snippet, Try to send just one variable then go for another & use content type.
u can use //console.log(JSON.stringify(cu)); to view what's inside.
jQuery.ajax({
type: 'post',
dataType: 'json',
data: {your_var:JSON.stringify(cu)},
contentType: "application/json"
});

How to navigate JSON Object in jQuery?

I made this webservice that handles my database functions, and this is an AJAX call to one of the methods.
$.ajax({
type: "POST",
url: "Service/dataBaseService.asmx/getRMAData",
data: '{"RMAId": 1 }',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (data) {
console.log(data);
alert(data.RMA_ID);
}
});
this is what is logged:
({d:"[{\"RMA_ID\":1,\"RequestDate\":\"2013-02-28T00:00:00\",\"Company\":1,\"Status\":\"Accepted \",\"Serial\":201764,\"LastChangeDate\":\"2013-02-28T00:00:00\",\"LastChangeBy\":\"Foreign \",\"Price\":null}]"})
However alert(data.RMA_ID) returns undefined aswell as data.d.RMA_ID?
How can I get hold of the values?
The value of data that you've logged is an object with a property named d, that contains a string value. You could probably make adjustments at your server side to make the value of d an object rather than a string, but the way it is currently constructed, you would be able to parse it into an object using JSON.parse.
Once you've done that, the resulting object should be an array, containing one single object. Thus, your access to RMA_ID would be as follows:
var data = JSON.parse(data.d);
alert(data[0].RMA_ID);
Using simple javascript you need to parse JSON response
var resp = eval('(' + data + ')');
or thru jQuery
var resp = jQuery.parseJSON(data);
now you can access the data using '.' and key name
console.log(resp.d[0].RMA_ID)

howto "submit" a part of a form using jQuery

I'm got a form laid out like a spreadsheet. When the user leaves a row, I want to submit fields from that row to the server using jQuery Ajax. The page is one large form, so this isn't really a javascript clicking the submit button scenario - the form is huge and I only want to send a small portion of the content for reasons of speed.
I've got the code written that identifies the row and iterates through the fields in the row. My issue is how to build the dat object in order to submit something comprehensible I can disassemble and store at the server end.
At the moment my code looks like this
var dat=[];
$("#" + finalrow).find("input").each(function () {
var o = $(this).attr("name");
var v = $(this).val();
dat.push({ o: v });
});
$.ajax({
url: 'UpdateRowAjax',
dataType: 'json',
type: 'POST',
data: dat ,
success: function (data) {
renderAjaxResponse(data);
}
});
The assembling of dat doesn't work at all. So how should I build that dat object in order for it to "look" as much like a form submission as possible.
You can add the elements that contain the data you want to send to a jQuery collection, and then call the serialize method on that object. It will return a parameter string that you can send off to the server.
var params = $("#" + finalrow).find("input").serialize();
$.ajax({
url: 'UpdateRowAjax',
type: 'POST',
data: params ,
success: function (data) {
renderAjaxResponse(data);
}
});
You can use $.param() to serialize a list of elements. For example, in your code:
var dat= $.param($("input", "#finalrow"));
$.ajax({
url: 'UpdateRowAjax',
dataType: 'json',
type: 'POST',
data: dat ,
success: function (data) {
renderAjaxResponse(data);
}
});
Example of $.param(): http://jsfiddle.net/2nsTr/
serialize() maps to this function, so calling it this way should be slightly more efficient.
$.ajax 'data' parameter expects a map of key/value pairs (or a string), rather than an array of objects. Try this:
var dat = {};
$("#" + finalrow).find("input").each(function () {
dat[$(this).attr('name')] = $(this).val();
});

Categories