pass multiple arguments __doPostBack - javascript

Is it possible to pass multiple arguments in the __doPostBack call?
I Know how I use one arrgument
__doPostBack('Service', $("input[name=celservice]:checked").val());
and in code behind vb.net
If eventTarget = "Service" Then
'Something
EndIf
but how when I use two arguments

We have created our own library to pass data from web page to ASP.NET. Without getting too much into details, the javascript code wraps info into an XML stream (you can use JSON just as well) that is then parsed on the server.
At its core, our javascript object looks something like this:
function MyArgs() {
var args = '';
this.add = function (id, value) {
args += ('<param id="' + encodeURI(id) + '" value="' + encodeURI(value) + '" />');
};
this.output = function () {
return '<request>' + args + '</request>';
};
}
And we use it like this:
var args = new MyArgs();
args.add("param1", "value A");
args.add("param2", "Value B");
__doPostBack("YOUR_SERVICE", args.output());
We like it because we are quite comfortable with XML data, but you may as well use JSON or URL encoding. The logic is the same: you create a stream that you can parse on the server.
This technique is also useful the other way around, server to client, especially as a response to AJAX requests.
I hope this may be of help to you :)

You can wrap your multiple results in an object, like so:
var result = {
celservice: $("input[name=celservice]:checked").val(),
somethingElse: true
}
then
__doPostBack('Service', result);

Related

Javascript custom library issue [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have looked and looked and I am still scratching my head. If I have missed something obvious, I apologise. I have tried to create a custom library of functions that I have written myself (thanks stackoverflow for helping me work that one out....). I then have a javascript file that loads when the web page is called, which in turn calls said functions in my custom library.
I have a function called getConfig() that does the obvious. It gets a JSON file with the configuration details for my server that hosts all of my RESTful web services. When I step through the code, the configuration details are returning as I would expect, however, when I load the web page at full speed, the configuration object comes back as undefined. I thought it might be a timing thing, so I wrapped everything in a $(document).ready(function()) block, but no go. I even tried a window.onload = function(){} block to make sure everything is loaded before the custom libraries are called. No luck! Its doing my head in as I cannot for the life of me work out what is going on.
My custom library file looks like this with filename xtendLibs.js
var xtendLibs = {
getConfig : function(){
var CONFIG;
$.getJSON("/js/config.json", function(json){
CONFIG = json;
});
return CONFIG;
},
getObjects : function(config, medicareno, medicarelineno, objectType){
var object;
var urlString = config.scheme + config.muleHost + config.mulePort + ":/patients/";
switch(objectType){
case ("details") :
urlString = urlString + "details/" + medicareno + "/" + medicarelineno ;
break;
case ("appointments") :
urlString = urlString + "appointments/" + medicareno +"/" + medicarelineno;
break;
}
$.ajax({
type : 'GET',
url : urlString,
success : function(data){
object = data;
},
failure : function(){
alert("Failure");
}
});
return object;
},
getUrlParameters : function(){
var paramsArray = window.location.search.substring(1).split("&");
var obj = [];
var tempArray;
var paramName,paramValue;
for(var i = 0; i < paramsArray.length; i++){
tempArray = paramsArray[i].split("=");
paramName = tempArray[0];
paramValue = tempArray[1];
obj[paramName] = paramValue;
}
return obj;
}
};
The javascript file that calls the various functions in the above file looks like this appts.js
window.onload = function(){
var config, params, appointments;
params = xtendLibs.getUrlParameters(); // This line works - and params is returned
config = xtendLibs.getConfig(); // This line fails but will work if I step through the code
appointments = xtendLibs.getObjects( config,
params["medicareno"],
params["medicarelineno"],
"appointments");
console.log(params);
}
I am truly stumped. Any help would be greatly appreciated.
Ajax is async process, so when getJson is called it does not stop the execution of next statement.
getConfig : function(){
var CONFIG;
$.getJSON("/js/config.json", function(json){
CONFIG = json;
});
return CONFIG;
}
When getJson is called it switches to a new thread, and the next statement which is in this case is "return CONFIG;" is executed. However, CONFIG has not been defined yet, so it is returning as undefined.
How Could you solve this problem?
You could not solve this problem. Not using this code design. You could non async the ajax, but it will make your page freeze.
You could set a global variable "config" when "getConfig" is called and check whether the config variable is defined when executing any function concerning it, but the best approach would be to pass a function, containing all the statements to be executed when config has finished loading, in getConfig function and call it when "/js/config.json" has loaded.

Using third party js libraries with Jint

I'm working on a feature where user defined, anonymous, javascript functions retrieved from a database need to be executed server side in the context of ASP.Net application.
I'm evaluating Jint for this purpose (Latest version from NuGet). I have been able to run functions that do basic operations and return values without an issue as below.
public void Do()
{
var jint = new Engine();
var add = jint.Execute(#"var f = " + GetJsFunction()).GetValue("f");
var value = add.Invoke(5, 4);
Console.Write("Result: " + value);
}
private string GetJsFunction()
{
return "function (x,y) {" +
" return x+y;" +
"}";
}
My question is whether Jint facilitates the execution of javascript functions which uses third party libraries like lodash? If so, how would I go about making the Jint engine aware of it (i.e third party library)?
An example would be the execution of following function.
private string GetFunction()
{
return "function (valueJson) { " +
" var value = JSON.parse(valueJson);" +
" var poi = _.find(value,{'Name' : 'Mike'});" +
" return poi; " +
"}";
}
Thanks a lot in advance.
I think I have figured this out. It's no different to executing a custom function. You just read the third party library from a file (project resource) and invoke execute on Jint engine. See below;
private void ImportLibrary(Engine jint, string file)
{
const string prefix = "JintApp.Lib."; //Project location where libraries like lodash are located
var assembly = Assembly.GetExecutingAssembly();
var scriptPath = prefix + file; //file is the name of the library file
using (var stream = assembly.GetManifestResourceStream(scriptPath))
{
if (stream != null)
{
using (var sr = new StreamReader(stream))
{
var source = sr.ReadToEnd();
jint.Execute(source);
}
}
}
}
We can call this function for all the third party libraries that needs to be added.

How do I pass a variable to request's callback?

I'm using express and request to turn a site's html into json, then returning it. For example:
app.get('/live', function(req,_res){
res = _res;
options.url = 'http://targetsite.com';
request(options,parseLive);
});
function parseLive(err, resp, html) {
var ret = {status:'ok'};
-- error checking and parsing of html --
res.send(ret);
}
Currently I'm using a global var res to keep track of the return call, but this fails when multiple requests are made at the same time. So, I need some way of matching return calls from express to their callbacks in request.
How might I do this?
Use a closure.
Pass the variable to a function. Return the function you want to pass to request from that function.
app.get('/live', function(req,_res){
options.url = 'http://targetsite.com';
request(options,parseLiveFactory(res));
});
function parseLiveFactory(res) {
function parseLive(err, resp, html) {
var ret = {status:'ok'};
-- error checking and parsing of html --
res.send(ret);
}
return parseLive;
}

Passing parameter to json_callback function

I am using an inverse geolocation method from mapquest that looks something like this
function fieldVia_changed(a)
{
if (document.getElementsByName("via"+a)[0].value.trim().length!=0)
{
var via = document.getElementsByName("via"+a)[0].value ;
var strV = via.replace(/ |,/g, "+");
var s = document.createElement('script');
s.src = 'http://open.mapquestapi.com/nominatim/v1/search?q='+strV+'&json_callback=cbv&format=json&polygon=1&addressdetails=1';
document.getElementsByTagName('head')[0].appendChild(s);
}
}
The results of the request are processed in the function cbv which accepts a parameter
function cbv(json)
{
v_lat[0] = json[0].lat;
v_lng[0] = json[0].lon;
}
However i need to be able to pass another parameter to the cbv function from fieldVia_changed function so that i can process the information properly. The cbv function definition would look like this function cbv(json,a). I looked all over but i can not find a solution. Is it possible ?
The server side won't usually have the option of passing additional arguments in a JSONP system. A possible solution is to use the value of a in the callback function name, and dynamically create the function as a kind of man in the middle between the cbv() function, allowing you to pass a as a second argument.
function fieldVia_changed(a) {
if (document.getElementsByName("via" + a)[0].value.trim().length != 0) {
// dynamically create the function
window['cbv_' + a] = function (json) {
cbv(json, a);
};
var via = document.getElementsByName("via" + a)[0].value;
var strV = via.replace(/ |,/g, "+");
var s = document.createElement('script');
// call the function cbv_x
s.src = 'http://open.mapquestapi.com/nominatim/v1/search?q=' + strV + '&json_callback=cbv_' + a + '&format=json&polygon=1&addressdetails=1';
document.getElementsByTagName('head')[0].appendChild(s);
}
}
function cbv(json, a) {
v_lat[0] = json[0].lat;
v_lng[0] = json[0].lon;
console.log(a);
}
This is OK if a is some sort of short identifier, if it's from user input then it's not really suitable for use in the function name. You're using in the name attributes so I'm assume this is fine.

Setting object properties using AJAX

I am newbie in OOP and I try to build an object using ajax request. What I need is to get 'responseArray' in JSON format and than work on it.
function adres(adres) {
this.adres_string = adres;
var self = this
$.ajax({
type: 'POST',
url: "http://nominatim.openstreetmap.org/search?q="+adres+"&format=json&polygon=0&addressdetails=0",
success: function(data) {
self.responseArray = eval('(' + data + ')')
}
})
//Method returning point coordinates in EPSG:4326 system
this.getLonLat = function() {
var lonlat = new OpenLayers.LonLat(this.responseArray.lon, this.responseArray.lat);
return lonlat;
}
}
The problem starts when in appilcation code I write:
var adr = new adres('Zimna 3, Warszawa');
adr.getLonLat();
This returns nothing as there is no time get the response from the server.
How to write it properly in the best way? I've read about when().then() method in jQuery. This may be OK for me. I just want to get know best practise
This is how AJAX works (notice the A-synchronous part). You are right, the moment you call adr.getLonLat() response did not yet came back. This is the design I would suggest: just pass callback function reference to adres constructor:
function adres(adres, callbackFun) {
//...
success: function(data) {
var responseArray = eval('(' + data + ')')
var lonlat = new OpenLayers.LonLat(responseArray[i].lon, responseArray[i].lat);
callbackFun(lonlat)
}
and call it like this:
adres('Zimna 3, Warszawa', function(lonlat) {
//...
})
Few remarks:
adres is now basically a function, you don't need an object here.
do not use eval to parse JSON, use JSON object.
Are you sure you can POST to http://nominatim.openstreetmap.org? You might hit the same origin policy problem
where is the i variable coming from in responseArray[i]?

Categories

Resources