Passing C# function return value to Javascript - javascript

what i'm doing is, i'm calling a C# function so it returns the data i will use in Javascript,
However when i read the data from javascript it's always undefined, I debugged the C# function and found out that it actually returns the correct data, so i'm thinking i'm only having trouble receiving it from Javascript.
Here is the c# function i'm calling
[WebMethod]
public static string CommonBus(int StopNo1, int StopNo2)
{
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
LinkedList<int> StopBusNo1 = new LinkedList<int>();
LinkedList<int> StopBusNo2 = new LinkedList<int>();
StopBusNo1 = LookForBuses(StopNo1); //Returns the buses that stop at StopNo1
StopBusNo2 = LookForBuses(StopNo2);
LinkedList<int> CommonBusNos = LookForCommonBuses(StopBusNo1.First, StopBusNo2.First);// Get common buses that stop at both stops
LinkedListNode<int> commonNo = CommonBusNos.First;
LinkedList<Bus> availableBus = new LinkedList<Bus>();
while (commonNo != null)
{
availableBus.AddLast(GetCommonBusIntel(commonNo.Value, StopNo1, StopNo2));
commonNo = commonNo.Next;
}
return oSerializer.Serialize(availableBus);
}
And here is the Javascipt side
function FindTransportation(startStops, endStops) {
for (var i = 0; i < startStops.length; i++) {
for (var x = 0; x < endStops.length; x++) {
availabeTransports.push(PageMethods.CommonBus(startStops[i].StopNo, endStops[x].StopNo)); // Trying to push the returned data into an array
}
}
}

Alright found the answer thank you for your comments.
i edited the FindTransportation function
function FindTransportation(length1, length2) {
for (var i = 0; i < length1; i++) {
for (var x = 0; x < length2; x++) {
GetCommonBuses(i, x);
}
}
}
and i also created the GetCommonBuses function for ajax calls
function GetCommonBuses(index1,index2) {
$.ajax({
type: "POST",
url: "/HomePage.aspx/CommonBus",
data: JSON.stringify({ StopNo1: startWalkableStops[index1].StopNo, StopNo2: endWalkableStops[index2].StopNo }),
contentType: "application/json; charset:utf-8",
dataType: "json",
})
.done(function (res) {
availabeTransports.push(res);
});
}

Related

Getting type error while using Ajax call in JavaScript/jQuery [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I am getting the following error while extracting some value inside loop using jQuery. I am showing my error below.
Uncaught TypeError: Cannot read property 'no_of_optional' of undefined
I am providing my code below.
var data = $.param({
'op': 'setPollField',
'sid': id
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var qdata = JSON.parse(msg);
var get = $("#ques").val();
var cntr = 0;
for (var i = 1; i < get; i++) {
if (i != 0) {
$("#questions0").val(qdata[0].questions);
$('#noofoption0').val(qdata[0].no_of_optional);
var data = $.param({
'op': 'getOptional',
'id': qdata[0]['_id']['$id']
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var optdata = JSON.parse(msg);
var cnt = 0;
for (var j = 0; j < qdata[0].no_of_optional; j++) {
}
}
cnt++;
}
})
}
if (i == 1) {
$('#questions' + i).val(qdata[i].questions);
$('#noofoption' + i).val(qdata[i].no_of_optional);
var data = $.param({
'op': 'getOptional',
'id': qdata[i]['_id']['$id']
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var optdata = JSON.parse(msg);
var cnt = 0;
console.log('first question', qdata[i].no_of_optional);
for (var j = 0; j < qdata[i].no_of_optional; j++) {
}
})
}
}
})
I am getting error at this console.log('first question',qdata[i].no_of_optional); .Actually qdata is containing the two set of data(qdata[0],qdata[1]) but inside the second ajax call i is becoming 2.
Here I am expecting qdata[1].no_of_optiona inside second ajax call.
use a closure, by the time the done callback is called the for loop has finished and incremented i:-
var data = $.param({
'op': 'setPollField',
'sid': id
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var qdata = JSON.parse(msg);
var get = $("#ques").val();
var cntr = 0;
for (var i = 1; i < get; i++) {
if (i == 1) {
(function(i) {
$('#questions' + i).val(qdata[i].questions);
$('#noofoption' + i).val(qdata[i].no_of_optional);
var data = $.param({
'op': 'getOptional',
'id': qdata[i]['_id']['$id']
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var optdata = JSON.parse(msg);
var cnt = 0;
console.log('first question', qdata[i].no_of_optional);
for (var j = 0; j < qdata[i].no_of_optional; j++) {
}
})
})(i);
}
}
})

How to pass the select box value as an array using AJAX from one page to another in PHP?

var message = $("#send_message").val();
var Teaminput = $("#sms_reminder_team").val();
for (var i = 0; i <Teaminput.length; i++)
{
var team=Teaminput[i];
}
var Memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <Memberinput.length; i++)
{
var members=Memberinput[i];
}
Get 2 varaibles as array members and team
var parameter = "message="+message+"&team="+team+"&members="+members;
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: parameter,
success: function(data)
{
document.getElementById('check').innerHTML = data;
}
});
How to send both array variables using AJAX from current page to "dir_sendmessage".
Change the below line
var parameter = "message="+message+"&team="+team+"&members="+members;
to
var parameter = "message="+message+"&team="+JSON.stringify(team)+"&members="+JSON.stringify(members);
Edit: Modify like this too
var team = [];
var members = [];
for (var i = 0; i <Teaminput.length; i++)
{
team=Teaminput[i];
}
var Memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <Memberinput.length; i++)
{
members=Memberinput[i];
}
Note: When you add var in each line in the loop, it will declare a new variable. You have to edit like the above code
After update the code with the JSON.stringify() function, you will be able to get the value as an array in you PHP code
Ajax will not directly pass Jquery array to PHP
First of all ideally you should send in JSON format or use array.tostring() ( can avoid this )
But if you have to send it as array you can try following:
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: {team:team, members: members},
success: function(data) {
document.getElementById('check').innerHTML = data; } });
var message = $("#send_message").val();
var teaminputt = $("#sms_reminder_team").val();
team = new Array();
members = new Array();
for (var i = 0; i <teaminputt.length; i++)
{
var team=teaminputt[i];
}
var memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <memberinput.length; i++)
{
var members=memberinput[i];
}
var parameter = "message="+message+"&team="+team+"&members="+members;
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: parameter,
success: function(data)
{
document.getElementById('check').innerHTML = data;
}
});
$("#msg-send-btn").click(function() {
var message = $("#send_message").val();
var optionsmembers = $('#sms_reminder_members option:selected');
var members = $.map(optionsmembers ,function(option) {
return option.value;
});
//---- Using $.map get all selcted data as a an Array.
var postData = {
message,
members
}
//---- For Avoid Json-Stringfy.
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage.php',
type: 'POST',
data:{myData:postData},
//----- And It's Work Perfectly.

How to get JSON result from an API call using jQuery(or Javascript) in a non-Ajax way?

I am new to JS an jQuery. And I am trying to build a key-value map from an API call which returns an array of key-value pairs.
[{"key":"191","value":244}, ... , {"key":"920","value":130}]
I came up with this ajax code. But following code will need the map constructed from loadMap. How to change it to non-ajax way that the "followingFunction" runs after loadMap finishes>
var mp = {};
(function loadMap() {
$.ajax({
type: 'GET',
url:'http://localhost:8080/xxx/api?start_date=2014-10-01&end_date=2014-11-01',
dataType: "json",
success: function(arr){
var out = "";
for(i = 0; i<arr.length; i++) {
mp[arr[i].key] = arr[i].value;
}
}
});
}());
//followingFunction which needs the information from mp
You can solve this in two different ways.
1) ExecutefollowingFunctionat the end of your success callback:
var mp = {};
function loadMap() {
$.ajax({
type: 'GET',
url:'http://localhost:8080/xxx/api?start_date=2014-10-01&end_date=2014-11-01',
dataType: "json",
success: function(arr){
var out = "";
for(i = 0; i<arr.length; i++) {
mp[arr[i].key] = arr[i].value;
}
followingFunction();
}
});
};
loadMap();
2) Set the async flag to false (by default this flag is true). This will result in blocking call with synchronous execution:
var mp = {};
function loadMap() {
$.ajax({
type: 'GET',
url:'http://localhost:8080/xxx/api?start_date=2014-10-01&end_date=2014-11-01',
dataType: "json",
async: false,
success: function(arr){
var out = "";
for(i = 0; i<arr.length; i++) {
mp[arr[i].key] = arr[i].value;
}
}
});
};
loadMap();
followingFunction();

javascript wait for several callback finished

I have a following javascript program:
function jQueryFunction(url, callback)
{
$.ajax
({
type: "GET",
async: true,
url: url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler",
success: function(json)
{
return callback(json);
}
});
}
var jsonArray = new Array();
for(var i = 0; i < 10; i++)
{
jQueryFunction(url[i], function(json){
jsonArray[i] = json;
});
}
//process jsonArray
However, when I check jsonArray after the for loop, it is null. So my question is that how to store the return value from jQueryFunction to jsonArray in for loop and then process it?
I have tried $.when.apply($,jsonArray).done(function) but still the same, it is null.
A simple way:
function doTheAjax(url, callback) {
return $.ajax({
type: "GET",
async: true,
url: url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler"
});
};
var reqs = [];
for(var i = 0; i < 10; i++) {
reqs.push(doTheAjax(url[i]));
}
// send the array of requests to when, which will fire `done`
// when it's, well, done
$.when.apply($.when, reqs).done(function() {
$.each(arguments, function(data) {
// process the data
});
});
alternatively, make a bunch of requests and put them into jsonArray, but keep
track of how many you're making. When they all complete, you have the array. Create your
own deferred, resolve it yourself when the counter is up, and return the promise.
var getJSON = function(url) {
var dfd = $.Deferred();
var count = 0;
var total = 10;
var jsonArray = [];
for(var i = 0; i < total; i++) {
doTheAjax(url[i]).done(function(json) {
jsonArray.push(json);
count++;
if ( count >= total ) {
dfd.resolve(jsonArray);
}
});
}
return dfd.promise();
};
getJSON().done(function(theCreatedJsonArray) {
// do stuff
});
I'm not sure why the answer to your previous question (using deferreds) didn't work. But the cause of your problem is that you are checking the array before any of the ajax responses arrived. You also have a problem with i referencing the same value on all callbacks.
One simple workaround, if you know how many responses you're expecting:
var arr = [];
for(var i = 0; i < 10; i++){
jQueryFunction(url[i], function(json){
arr.push(json);
if(arr.length == 10) {
// All 10 responses arrived!
// DO STUFF FROM HERE
// e.g., call another function
console.log(arr);
}
});
}

Javascript Function Returns Undefined JSON Object (But It's Not Undefined!)

I am trying to return a JSON object from a function using the JSON jQuery plugin (http://code.google.com/p/jquery-json/) but after returning the object from the function, it becomes undefined.
$(document).ready(function() {
var $calendar = $('#calendar');
$calendar.weekCalendar({
...
data : function(start, end, callback) {
var datas = getEventData();
alert(datas); // Undefined???
}
});
If I inspect the object before returning it, it is defined.
function getEventData() {
var dataString = "minDate="+ minDate/1000 + "&maxDate=" + maxDate/1000;
//alert(dataString);return false;
$.ajax({
type: "POST",
url: "busker_ops.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data != null) {
var jsonArray = new Array();
var jsonObj = {};
for(var i = data.length - 1; i >= 0; --i) {
var o = data[i];
var set_id = o.set_id;
var start = o.startOrig;
var end = o.endOrig;
var title = o.title;
var deets = o.deets;
jsonObj =
{
"id":parseInt(set_id),
"start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
"end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
"title":title,
"body":deets
};
jsonArray[i] = jsonObj;
}
alert($.toJSON(jsonArray)); // Defined!
return ($.toJSON(jsonArray));
} else {
}
}
});
}
Any idea what I'm missing here?
function getEventData() {
function local() {
console.log(42);
return 42;
}
local();
}
Your missing the fact that the outer function returns undefined. And that's why your answer is undefined.
Your also doing asynchronous programming wrong. You want to use callbacks. There are probably 100s of duplicate questions about this exact problem.
Your getEventData() function returns nothing.
You are returning the JSON object from a callback function that's called asynchronously. Your call to $.ajax doesn't return anything, it just begins a background XMLHttpRequest and then immediately returns. When the request completes, it will call the success function if the HTTP request was successful. The success function returns to code internal in $.ajax, not to your function which originally called $.ajax.
I resolved this by using callbacks since AJAX is, after all. Once the data is retrieved it is assigned to a global variable in the callback and the calendar is refreshed using the global variable (datas).
$(document).ready(function() {
// Declare variables
var $calendar = $('#calendar');
datas = "";
set = 0;
// Retrieves event data
var events = {
getEvents : function(callback) {
var dataString = "minDate="+ minDate/1000 + "&maxDate=" + maxDate/1000;
$.ajax({
type: "POST",
url: "busker_ops.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data != null) {
var jsonArray = new Array();
var jsonObj = {};
for(var i = data.length - 1; i >= 0; --i) {
var o = data[i];
var set_id = o.set_id;
var start = o.startOrig;
var end = o.endOrig;
var title = o.title;
var deets = o.deets;
jsonObj =
{
"id":parseInt(set_id),
"start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
"end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
"title":title,
"body":deets
};
jsonArray[i] = jsonObj;
}
//alert($.toJSON(jsonArray));
callback.call(this,jsonArray);
} else {
}
}
});
}
}
$calendar.weekCalendar({
data : function(start, end, callback) {
if(set == 1) {
callback(datas);
//alert(datas.events);
}
}
});
// Go get the event data
events.getEvents(function(evented) {
displayMessage("Retrieving the Lineup.");
datas = {
options : {},
events : evented
};
set = 1;
$calendar.weekCalendar("refresh");
});
});

Categories

Resources