Adding JSON results to a drop down list with JQUERY - asp.net

I'm making a call to a page method via AJAX in my ASP.NET application via JQUERY's AJAX method e.g.
$.ajax({
type: "POST",
url: "page.aspx/GetDropDowns",
data: "{'aId':'1'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function() {
alert('Error getting page');
}
I'll be returning the results in JSON format, whereby I will be populating a drop down. I could do this part myself but I want to know if there is any built in magic in JQuery for processing JSON results or if there are any good utility scripts for this sort of thing.

There is little jQuery itself can help you with populating dropdown. You just need to create HTML and append it to your dropdown.
I'm not sure what is the format of your data so I'm assuming it's an object where keys should be dropdown's keys and values should be dropdown's values.
I also prefer using $.post then $.ajax as it has a clearer structure for me.
$.post('page.aspx/GetDropDowns', {'aId': '1'}, function (data, status) {
if (status === 'success') {
var options = [];
for (var key in data) {
options.push('<option value="' + key + '">' + data[key] + '</option>');
}
$('#yourId').append(options.join(''));
} else {
alert('error');
}
}, 'json');

In the past I have used a plugin when working with dropdowns.
http://www.texotela.co.uk/code/jquery/select
Request the JSON data:
//Get the JSON Data
$.getJSON(url, function(json) {
PopulateDropDownFromJson(json, "#element");
});
and then just pass the JSON into a function that uses the plugin above
function PopulateDropDownFromJson(json, element){
$.each(json, function() {
$(element).addOption(this[valueText], this[displayText], false);
});
}

Related

How can I print the values from a list of JSON objects to a div after being returned via Ajax?

I can successfully return the the list of objects via an Ajax call, and I can see them in my console:
How can I iterate over each object (in the above example there are 1) and then print one of the values, i.e. notificationText below, to a series of divs?
JQuery/Ajax:
<script>
function LoadReplies(convoMessageId) {
$('#test123').html('<i class="fas fa-circle-notch fa-spin"></i>');
console.log("Message ID: " + convoMessageId);
$.ajax({
type: "POST",
url: "Index?handler=Replies",
headers: {
"XSRF-TOKEN": $('input:hidden[name="__RequestVerificationToken"]').val()
},
contentType: "application/json; charset=utf-8",
data: convoMessageId,
success: function (response) {
console.log(JSON.stringify(response));
$('#convo' + convoMessageId).modal('show');
$.each(response, function (idx, obj) {
console.log(obj[0].value);
$("#test123").html(obj[0].value);
});
},
failure: function (response) {
// console.log(response);
}
});
}
</script>
JSON List:
I can retrieve the value I want now but it doesn't render to the div:
$("#test123").html(obj[0].value);
Keeping in mind that the Div will show the HTML only, you have to generate the HTML string out of the JSON or the data. For example in your success callback function, I would do the simplest as below:
var generatedHtml = ['<dl>'];
$.each(response, function (idx, obj) {
generatedHtml.push(`<dt>label1:</dt> <dd>${obj[idx].prop1}</dd> <dt>label2:</dt>${obj[idx].prop2}</dd>`);
});
generatedHtml.push('</dl>');
$("#test123").html(generatedHtml.join(''));
I didn't test it myself, but it should work...

Asynchronous ajax call causing issue in KnockOutjs

I have a button on click of that i am calling something like :
ViewModel:
self.MyArray = ko.observableArray();
self.remove = function(c) {
ko.utils.arrayForEach(c.sData(), function(ser) {
if (ser.Check() == true) {
self.MyArray.push(service);
count++;
}
});
if (count) {
$.ajax({
url: "/api/LoadCustomer/?reason=" + reason,
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(self.MyArray),
success: function(data) {
ko.utils.arrayForEach(self.MyArray(), function(removedata) {
c.sData.remove(removedata);
});
}
});
self.MyArray([]);
}
};
If i include async:false in my ajax call i get everything fine but if i didn't include async (its default property is true) i dont know somehow in my success function of ajax call self.MyArray() remains Empty but its not the case if i keep it false (Awkward).
Sometimes i fear like if i have series of ajax calls with async:true while loading into a observable array(OnLoad) there may be a slight chance of misplacement of data .
Help me understand .
The reason your observable array MyArray is empty sometimes is because this line of code self.MyArray([]); executing before the ajax call is done. How about this instead -
if (count) {
$.ajax({
url: "/api/LoadCustomer/?reason=" + reason,
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(self.MyArray),
success: function (data) {
ko.utils.arrayForEach(self.MyArray(), function (removedata) {
c.sData.remove(removedata);
});
},
complete: function() { // complete fires after success and error callbacks
self.MyArray([]); // empty the array no matter what happens (error or success)
}
});
}

Check UserName availability by using AJAX in asp.net

I'm creating a SignUp form,i want to add a feature to the form in which whenever a new user types an username in the text box, it should automatically check if the username is already taken or not(should compare it with usernames exist in SQL server database). I want to implement this feature using AJAX.
Use the following jquery code, don't forget include jquery libraries
$("#<%=txtJournalIdToMove.ClientID %>").blur(function () {
var journalTextBoxId = '<%= this.txtJournalIdToMove.ClientID %>';
var journalId = $("#" + journalTextBoxId).val();
var params = '{"JournalId":"' + journalId + '"}';
$.ajax({
type: "POST",
url: "Default.aspx/PopulateVolumeNo",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// Replace the div's content with the page method's return.
var returnValue = data.d;
if (returnValue == null) {
alert("The given journal id does not exist or is in active in db.");
}
else {
//If success do your functionality
});
}
}
});
});
Try this onchange or on blur event of a textbox. Here I used user-name-box as text box id
$.post('/Server/CheckAvailablity/',
{name:function(){return $('#user-name-box').val()},
function(response){
if(response.status="Y"){
alert('available');
}
else{
alert('not available');
}
}
);
In server side CheckAvailablity method prepare a JSON object like {"status":"Y"} and return

parsing json response to C# object using jquery

I have following JSON returned from my WCF service:
`{"DoWorkResult":[{"AAID":0,"AreaID":1,"AreaName":"Basement","AssemblyAssessmentID":1,"AssemblyID":493,"AssemblyName":"Handrail (Steel)","AssessmentID":1,"AssessmentName":"University Of WA","AttributesCount":1,"CapitalReplacementUnitCost":623,"CategoryID":7,"CategoryName":"Furniture and Fixtures","CountedUnits":7,"CreatedBy":"Admin","ElementID":37,"ElementName":"Handrails and Balustrades","FacilityID":1,"FacilityName":"Central Chilled Water Plant","FacilityPercentage":"0","IsCompleted":1,"IsHeritage":false,"IsSafetyRisk":false,"Level1Units":0,"Level2Units":0,"Level3Units":0,"Level4Units":0,"Level5Units":7,"MesurementUnit":"Items","PhotosCount":1,"RepairCost":0,"RepairNotes":"","RequiresSpecialist":false,"SiteName":"CRAWLEY","SpaceID":1,"SpaceName":"B01","TasksCount":0}]}
My service method is like this
[System.ServiceModel.OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
public List<BLL.BLL_AssemblyAssessment> DoWork(string id) {
return BLL.BLL_AssemblyAssessment.GetAssessemblyAssessmentByAssemblyAssessmentID(1, 1);
}
and I need data parsed in jquery ajax success. how can i parse it to object of my class:
$.ajax({
type: "POST",
url: "MyTestService.svc/DoWork",
data: '{"id":"3"}',
processData: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
},
error: function (msg) {
// $("#errorDiv").text(msg);
alert(msg);
}
});
}
Use
alert(JSON.parse(jsonString));
In your javascript code, calling the $.ajax function with the dataType: "json" option lets jQuery take care of the parsing.
The data variable in the success callback is already a javascript object.
You can access its properties :
success: function(data) {
var html = "",
rows = data.DoWorkResult,
lgth = rows.length,
i, row;
for ( i=0; i<lgth; i++ ){
row = rows[i];
html += "<tr><td>"+row.AAID+"</td><td>"+row.AreaName+"</td></tr>";
// or whatever
}
$("#myTable").html( html );
}
From what I understand, the class BLL.BLL_AssemblyAssessment is a C# class, to be used on the server side, not a javascript class on the client side. In javascript, objects don't need a class definition to hold data.
You can output an object to the console to check its structure :
success: function(data) {
console.log(data);
console.log(data.DoWorkResult);
console.log(data.DoWorkResult[0]);
}
I don't really see the problem.
Since you have specified JSON as the datatype, the JSON is parsed in to a javascript object in the success handler. Just iterate over it using $.each:
//data.DoWorkResult is an array with one element
$.each(data.DoWorkResult, function(k, v){
alert(v.AAID); //will alert 0 one time since there is only one object in the
//array and the value is 0 on the AAID property
});
Fiddle
Note that I need to parse the JSON in my example, since it isnt automatically done by any ajax method there.

How can I return a value from a function that uses a jQuery ajax call?

I have the following Javascript function that makes a call to an Asp.Net WebMethod that returns true if a username already exists and false if it does not.
The following will give me the correct answer in an alert box but if I change the
alert(result.d) to return result.d
the result of the function is always undefined.
How can I get the function that the Ajax call is contained in to return a value based on the response from the WebMethod?
function doesEnteredUserExist() {
var valFromUsernameBox = $("#txtUserName").val();
var jsonObj = '{username: "' + valFromUsernameBox + '"}';
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: jsonObj,
dataType: 'json',
async: false,
url: 'AddNewUser.aspx/IsUserNameValid',
success: function (result) {
alert(result.d);
},
error: function (err) {
alert(err);
}
});
}
The thing to note is that the ajax function is non blocking. You specify two callback functions, one for success and one for error, one of these functions will get executed when the underlying request is finished.
Your doesEnteredUserExist does not wait for the ajax call to complete, and thus, the return value of the function is undefined.
The proper way to continue execution based on the result of your call is to break your functionality out into a separate function, and call that from your success function.
Ajax is asynchronous so once the function "doesEnteredUserExist" returns, the ajax call is not yet finished. Then later in the success callback you have the value. From there you should continue with your code and display the info to the user.
Store the value of result.d in a variable, then use it for whatever you would like.
Change this:
success: function (result) {
alert(result.d);
},
to this:
success: function (result) {
var resultString = result.d;
},
Now whenever you need result.d, just use the variable resultString. Basically, the ajax call is the only thing that can call the function that you wanted to return the value for, so you need to store that value when the function is called.
Maybe give this a bash
function onSucess (data) {
alert(data.d);
}
function doesEnteredUserExist() {
var valFromUsernameBox = $("#txtUserName").val();
var jsonObj = '{username: "' + valFromUsernameBox + '"}';
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: jsonObj,
dataType: 'json',
async: false,
url: 'AddNewUser.aspx/IsUserNameValid',
success: onSucess,
error: function (err) {
alert(err);
}
});
}
I am guessing that you are trying to set result.d which is out of scope from the call which is why the alert (result.d) works as its in scope.
I may be getting the wrong end of the stick, you could use a global variable (not recommended), set that in the ajax return which you could then read from your function.
May need a bit more info or clarity on what your trying to achieve, as I read the question a couple of ways.
I normally do this (havent tested this):
function ajaxLoad(callback)
$.ajax({
type: 'POST',
async: true,
url: 'url.aspx',
data: d,
cache: false,
contentType: 'application/json',
dataType: 'json',
error: function (xmlHttpRequest, textStatus, errorThrown) {
//error stuff
},
success: function (data) {
if (typeof callback == 'function') { [callback(data)]; }
}
});
}
function callback(data)
{
alert(data);
}
call the function using
ajaxLoad('callback');
something like that!
Inside your success callback function if you return some value it doesn't set the return value for it's parent function. In this case the parent function is $.ajax and it always returns a jqXHR deferred object.
If you are using jQuery 1.5 or later the you can use deferreds. The idea is to save the jqXHR object returned from the AJAX request and wait for it to complete before returning it's value:
var jqXHR = $.ajax({...});
$.when(jqXHR).then(function (result) {
return result.d
});
Docs for $.when(): http://api.jquery.com/deferred.when
An example of doing this would be to return the jqXHR object from your function and then wait for the AJAX request to resolve outside the function:
function doesEnteredUserExist() {
return $.ajax({...});
}
$.when(doesEnteredUserExist).then(function (result) {
//you can access result.d here
});
As #timing has mentioned, by the time the value is returned from thefunction, the ajax call is not complete so everytime you get the undefined.
This is not a solution to the problem, but an alternative method you can try for displaying it would be instead of returning the value, just update the innerHTML of some element like div with the returned text.Below is what I mean:
function doesEnteredUserExist() {
var valFromUsernameBox = $("#txtUserName").val();
var jsonObj = '{username: "' + valFromUsernameBox + '"}';
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: jsonObj,
dataType: 'json',
async: false,
url: 'AddNewUser.aspx/IsUserNameValid',
success: function (result) {
//alert(result.d);
if(result.d==true){ //Just a check for the value whether true or 1 etc..
$("#notifications").html('Username Already Exists'); // Have a div where you can display the message (named it notifications here) , update the notifications div text to notify the user
}else{
$("#notifications").html('Username is Available');
}
},
error: function (err) {
alert(err);
}
});
}
This seems a good example of $.Deferred object usage
the idea is quite simple (really, I promise, :) see steps on the code)
Create a new deferred object
Make your ajax call. If result is false you will reject the deferred otherwise you will resolve it (you could reject it also on error ajax callback)
return the promise
Use .when() helper to check the status of the promise.
I create a fiddle which return randomically true or false in the response
function checkUserExist() {
var dfd = $.Deferred(); /* step 1 */
$.ajax({
url: "/echo/json/",
data: {
"json": JSON.stringify({d: (Math.random() < 0.5) })
},
type: "POST",
success: function (data) {
console.log("result (inside ajax callback) ", data.d);
if (!data.d) { dfd.reject() } else { dfd.resolve(); } /* step 2 */
},
error : ...
});
/* step 3 */
return dfd.promise();
}
$.when(checkUserExist()) /* step 4 */
.fail(function() { console.log("user don't exist (inside fail)"); })
.done(function() { console.log("user already exist (inside done)"); })
fiddle url : http://jsfiddle.net/Gh9cN/
(note: I've changed some internal details so to make it work on jsfiddle)

Resources