using the result from jQuery into C# - javascript

I have this function in jquery which has the result array and how can I get this result array to C# code. Can anyone help me regarding this.
function generateData() {
var result = $('#accordion').sortable('toArray');
}

You could do this asynchronously through a web method call from script, such that you define a web method appropriately, then call and handle the data and potential return value, as desired. For example:
Defining a web method:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string HandleData(object[] data)
{
//handle data
return string.Empty;
}
Defining a reusable jQuery script method to handle web method calls:
function ExecutePageMethod(page, fn, paramArray, successFn, errorFn) {
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
$.ajax({
type: "POST",
url: page + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
dataType: "json",
success: successFn,
error: errorFn
});
}
And, of course, the call itself:
ExecutePageMethod("Default.aspx", "HandleData",
["data", result], successCallback, failureCallback);
Naturally we now need to make sure our callback methods exist:
function successCallback(result) {
var parsedResult = jQuery.parseJSON(result.d);
}
function failureCallback(result) {
}

Use a hiddenfield to store the result..
<asp:HiddenField id="hfResult" runat="server" />
JQuery
$('hfResult').val(result);
C#
String result = hfResult.Value;
Note that a hiddenField only holds a string, so you might need to use some kind of seperator to seperate your array objects..

Related

"Error : Cannot use 'in' operator to search for 'length' in [{"ID":"2","Name":"EAA2"}]" when performing $.each

What ever I do, I keep getting the same error. The only thing I have found that might of helped is the JSON.parse, but I still get the same problem. console log gives data as [{"ID":"2","Name":"EAA2"}]
I split it into two functions as I didn't want to keep going back to the api everytime a user selects/de-selects an option.
I have also tried the following:
Changing vars to lets
Passing data.d from the update to the populate
function populateAvailableAuthorities() {
var list = $('#availableAA');
var data = JSON.parse($('#AAJSON').val());
var auths = $('#tbSelectedAA').val();
list.empty();
$.each(data, function (key, entry) {
if (!~auths.indexOf(entry.ID + ';')) {
list.append($('<option></option>').attr('value', entry.ID).text(entry.Name));
}
});
}
function updateListboxes() {
var teams = '';
let aa = $('#AAJSON');
aa.empty();
$('#cblTeams input:checked').each(function () {
teams += $(this).attr('value') + ',';
});
if (teams.length > 1) {
teams = teams.substr(0, teams.length - 1);
$.ajax({
type: "POST",
url: '<%# ResolveUrl("~/api/Authorities.asmx/FetchByTeam") %>',
data: '{teams: "' + teams + '"}',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
aa.val(JSON.stringify(data.d));
populateAvailableAuthorities();
}
});
}
}
It would seem that "over-stringifying" is an issue with JSON. If I doubled the JSON.parse or removed the JSON.stringify it all works correctly.
Annoying!!

Ajax Call to Service with Multiple Return Values

I am building a WCF service in C# in which I would like to be able to return multiple values from some of my functions. The code below appears to do this:
[WebMethod]
public void ReturnMultipleValues(int startingValue)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
var jsonData = new { FirstValue = startingValue, SecondValue = startingValue * 2 };
Context.Response.Write(ser.Serialize(jsonData));
}
I am trying to access this function through an ajax call in JavaScript code:
function runTestService() {
$.ajax({
type: "POST",
url: "http://localhost:12345/WebServices/MyService.asmx/ReturnMultipleValues",
contentType: "application/json;charset=utf-8",
data: "{ 'startingValue' : 6 }",
dataType: "json",
done: function(data) {
var firstValue = data.FirstValue;
var secondValue = data.SecondValue;
alert("First: " + firstValue + ", Second: " + secondValue);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
}
When I execute the above JavaScript code, the function in the .done portion never executes. When I check Fiddler, however, I see that the function in my service did execute properly and returned the correct values in the JSON.
Is there another way I should code either the service or the ajax call to it?
You are not supposed to write to Context.Response by yourself. Just return an object from method and let the framework do it for you
[WebMethod]
public object ReturnMultipleValues(int startingValue)
{
var jsonData = new { FirstValue = startingValue, SecondValue = startingValue * 2 };
return jsonData;
}
And you have to consider the fact web service wraps json repsonse in object with d property
{
"d": {
"FirstValue": 6,
"SecondValue": 12
}
}
So update js as well
done(function (data) {
data = data.d;
var firstValue = data.FirstValue;
var secondValue = data.SecondValue;
alert("First: " + firstValue + ", Second: " + secondValue);
});

Pass list of values from Code-Behind to Javascript

I currently have a list of dates in my code-behind, I'd like to pass the list to a variable in javascript without the use of hiddenfield
For instance,
Aspx.cs:
List < DateTime > blockedDate = new List < DateTime > ();
foreach(DataRow blockedRow in phBLL.getAllPH(DateTime.Now.Year).Tables[0].Rows)
{
blockedDate.Add(Convert.ToDateTime(blockedRow["date1"]));
}
Aspx:
$(document).ready(function () {
var arrayOfDates = ""
});
What I've tried
Aspx.cs:
public static List < DateTime > blockedDate = new List < DateTime > ();
[WebMethod]
public static List < DateTime > blockDates()
{
foreach(DataRow blockedRow in phBLL.getAllPH(DateTime.Now.Year).Tables[0].Rows) {
blockedDate.Add(Convert.ToDateTime(blockedRow["date1"]));
}
return blockedDate;
}
Javascript:
$.ajax({
type: "POST",
url: "CreateClass.aspx/blockDates",
data: null,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function(result) {
for (var i = 0; i < result.d.length; i++) {
var dates = [new Date(parseInt(result.d[i].substr(6)))];
console.log(dates);
}
}
});
I am trying to get the result and place into an Array. So it'd end up something like this
an array of dates
var array = ["2016/11/14", "2016/11/15", "2016/11/16"];
As per comments, Create a [WebMethod] which contain your code behind logic and call it using ajax.
Now, you will get data on ajax success, and just push your data to array arrayOfDates using JavaScript Array push() Method
Hope this helps!

Function as parameter in Jquery Ajax

Is it possible to put a function into a parameter for Jquery Ajax like below. dataType and data are given as functions. dataType returns a value of JSON if the returntype is JSON and text if isJson is false.
dataVal and dataVar are arrays containing the parameter names and values used to construct the data paramater. The result of the data: function would be a string as:
{dataVar[0]:dataVal[0],dataVar[1]:dataVal[1],.....,}
I'm getting an error when I try this, so, just wanted to know if this method was possible.
function getAjaxResponse(page, isJson, dataVar, dataVal, dfd) {
$.ajax(page, {
type: 'POST',
dataType: function () {
if (isJson == true) {
return "JSON";
} else {
return "text";
}
},
data: function () {
var dataString = '{';
for (var i = 0; i < dataVar.length; i++) {
dataString = dataString + dataVar[i] + ':' + dataVal[i] + ',';
}
console.log(dataString);
return dataString + '}';
},
success: function (res) {
dfd.resolve(res);
}
});
}
Edit
As per answers and comments, made the changes. The updated function is as below. This works:
function getAjaxResponse(page, isJson, dataVar, dataVal, dfd) {
$.ajax(page, {
type: 'POST',
dataType: isJson ? "JSON" : "text",
data: function () {
var dataString ="";
for (var i = 0; i < dataVar.length; i++) {
if (i == dataVar.length - 1) {
dataString = dataString + dataVar[i] + '=' + dataVal[i];
} else {
dataString = dataString + dataVar[i] + '=' + dataVal[i] + ',';
}
}
return dataString;
}(),
success: function (res) {
dfd.resolve(res);
}
});
}
And my original question is answered. But apparently, data is not getting accepted.
The return value of the data function is just treated as the parameter name and jquery just adds a : to the end of the request like so:
{dataVar[0]:dataVal[0]}:
So, my server is unable to pick up on the proper paramater name.
From the manual:
data
Type: PlainObject or String
So no.
Call the function. Use the return value.
data: function () { ... }();
// ^^ call the function
Not that way. But it will work with a little change:
(function () {
if (isJson == true) {
return "JSON";
} else {
return "text";
}
})()
That should work. You just call the function immidiately after you created it. This way, dataType is a String and the script will work.
Same with data. Also use the (function(){})()-notation here
jquery just adds a : to the end of the request like so:
{dataVar[0]:dataVal[0]}:
No, your devtools display does. However, as you're data string does not contain a = sign, and you send the content as application/x-www-form-urlencoded, the whole body is interpreted as if it was a parameter name.
For sending JSON, you should:
use contentType: "application/json"
use data: JSON.stringify(_.object(dataVar, dataVal))1
to ensure valid JSON is sent with the correct header (and correctly recognised as such at the server).
1: _.object is the object function from Underscore.js which does exactly what you want, but you can use an IEFE as well:
JSON.stringify(function(p,v){var d={};for(var i=0;i<p.length;i++)d[p[i]]=v[i];return d;}(dataVar, dataVal))
You need to call the function with parenthesis like below:
function func1(){
//func1 code in here
}
function func2(func1){
//func2 code in here
//call func1 like this:
func1();
}
So, you can use like this:
data: function () {
//your stuff her
}(); // which mean you are having data()

How to decode a JSON string?

On the server side do I have 2 hashes I encode into JSON strings like so
my $j = JSON->new;
$j = $j->utf8;
my $data;
$data->{users} = $j->encode(\%user_result);
$data->{owners} = $j->encode(\%owner_result);
$json_string = to_json($data);
print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;
On the client side I have
$(document).ready(function(){
$('form').live('submit', function(){
$.ajax({
type: "GET",
url: "/cgi-bin/ajax_confirm.pl",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: $(this).serialize(),
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#create_result').text("responseText: " + XMLHttpRequest.responseText +
", textStatus: " + textStatus +
", errorThrown: " + errorThrown);
$('div#create_result').addClass("error");
},
success: function(result){
if (result.error) {
$('div#create_result').text("result.error: " + result.error);
$('div#create_result').addClass("error");
} else { // perl script says everything is okay
var users = result.users;
var owners = result.owners;
...
users contains
{"ss":"Sandra Schlichting","fn":"Full name"}
but it is not an array. When I use $.each() it takes on character at a time.
Problem
How do I turn it into an array, so I can use
function makeTable(users) {
var result = '<table>\n<tr><td>Initials</td><td>Full Name</td></tr>\n';
$.each(users, function(index, value) {
result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
});
result += '</table>';
return (result);
}
which should produce
Initials Full Name
ss Sandra Schlichting
fn Full name
You should use jQuery.getJSON() as mentioned at http://api.jquery.com/jQuery.getJSON/.
There is also $.parseJSON() method to parse string to json if you want to go that way.
You don't need to turn it into an array. According to the jQuery.each() documentation it takes both arrays or objects and JSON is a subset of the object literal notation of JavaScript.
Edit: Here's an example: http://jsfiddle.net/pedrocorreia/s5UrZ/2/
You can use the JSON parser created by douglas crockford:
https://github.com/douglascrockford/JSON-js
include the json2.js in your page, the you can do:
var object = JSON.parse(string);
Then you can use it as an array.
you can use for in statement
var index = 0;
for(user in users){
result += '<tr><td>' + index + '</td><td>' + user['fn'] + '</td></tr>\n';
index++;
}

Categories

Resources