Jquery ajax wrapper with optional parameters - asp.net

I hope someone can help me with the following scenario because I'm breaking my small head over this! I have made a wrapper so I can easily call webservices/pagemethod using jquery. Now in the success function of the ajax call I want to be able to call a function (with optional parameters) I have done the following but I'm not sure if I'm the right direction:
function AjaxMethod(path, fn, paramArray, returnParamArray, 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 + '}';
if (returnParamArray.length > 0) {
$.ajax({
type: "POST",
url: path + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
dataType: "json",
success: function () {
var strFun = successFn;
var strParam = returnParamArray;
var funcCall = strFun + "('" + strParam + "');";
//Call custom function with parameter array
var ret = eval(funcCall);
},
error: errorFn
})
}
else {
$.ajax({
type: "POST",
url: path + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
dataType: "json",
success: successFn,
error: errorFn
})
}
;}
I am able to call the function but I cant seem to pass the parameters. Am I going in the right direction or is this complete off the path ? Is it even possible to pass parameters/values as an array. Or is there an easier way to accomplish this.
By the way I need this function to make up the following (Schematic) actions:
1) User deletetes a row from a table with data - DeleteRow(rowindex)
2) DeleteRow calls the AjaxMethod to delete the row from database
3) On success event I want the specific row to be deleted visually, so I need the selected rowindex available in the successfunction. There are a couple of other scenarios too so it needs to be really dynamic.
I can also store this information in global vars like CurrentDeletedIndex but I hope it's possible in the way I was thinking.
I hope I made myself a little bit clear if not feel free to ask.
Thank you for your time.
Kind regards,
Mark

This won't work
This is bad; eval is evil
The proper way to do this is fairly simple. First, we need to make the object paramList, not its string representation. We can do it like this:
var paramList = {};
for(var i=0; i<paramArray.length; i+=2) {
paramList[paramArray[i]] = paramArray[i+1];
} // note: make sure the array size is even.
Now for the success function:
var ret = successFn(paramList);
NOTE: if successFn is passed as a string, use window[successFn] for the global scope, or window.some.scope[successFn] for a specific scope, and I wholeheartedly suggest you to take the actual function as a parameter, not some string. This is useful for anonymous functions and functions from unreachable scopes. Oh and it's also the proper way of doing things

You need to use the apply method
So instead of using eval, and trying to create a String representation of parameters use this
window[successFn].apply(null, paramArray);

Related

file upload controlasp.net and ajax

hey i am have made a form for product detail insertion . I am using ajax in asp.net in order to insert data in database. Now in my form of the controls is fileupload control. Problem is i dont know how to select the file and pass it to the static method for operations like hasfile, etc. so is it possible that i pass the file using ajax technique and can store it's detail in database.
<asp:FileUpload ID="file_image" runat="server" />
$(document).ready(function () {
$("#submit").click(function () {
var cat = document.getElementById('DropDownList1').value;
var nm = document.getElementById('name').value;
var code = document.getElementById('code').value;
var dt = document.getElementById('dt').value;
var price = document.getElementById('price').value;
alert("you clicked " + cat + " - " + nm + "-" + code + "-" + dt + "-" + price + "-");
var fl = document.getElementById('file_image').value;
//this line is the problem as i can't get file
$.ajax({
method: "POST",
contentType: "application/json",
url: "~/home.aspx/insert",
dataType: "json",
// data: "{'Name':'" + document.getElementById('name').value + "'}",
data:"{}",
//async: false,
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
})
});
There are some issues with uploading files via ajax.
Ref. jQuery Ajax File Upload
You can do it as shown in the following link; however, it won't work in IE <= 9. http://blog.teamtreehouse.com/uploading-files-ajax
My recommendation if you want to upload multiple files would be to use something like http://www.uploadify.com/ with automatic fallback support. That way, you don't have to spend time programming that stuff yourself.

update session variable on textbox_change without postback

is there any way to save textbox text to a session variable without having to postback on text change?
You will need to do this in 4 stages.
1) Add an onkeydown="textChanged(this.ID);" to your textbox
2) Use some Javascript to capture the text
3) Fire an Ajax call to a web method
4) use the web method to store the session variable.
So something like this:
On your textbox, set Autopostback=false so you don't post back on typing.
Create yourself a small Javascript function that will be fired when the user types.
this function will first clear any timer attached to the textbox. then it will create another one that will fire another function after 1 second. This will ensure you're not trying to fire the end function too often.
function textChanged(id) {
var txtBox = document.getElementById(id);
clearTimeout(txtBox.timer);
txtBox.timer = setTimeout('SaveVariable()', 1000);
};
After 1 second, your method will call something like this:
function SaveVariable(){
// Do an ajax call in here and send your textbox value to a web method
var t = // GetYourTextboxTextHere
if (t != "") {
$.ajax({
type: "POST",
url: "yourPage.aspx/SaveMyTextVar",
data: "{'textToSave ': '" + escape(t) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (!msg.d) {
// it didn't save
} else {
// it saved just fine and dandy
};
}
});
};
}
Finally, a small web method on your code behind to capture the text
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> <Services.WebMethod()> _
Public Shared Function SaveMyTextVar(ByVal textToSave As String) As Boolean
'' Save your variable to session here.
'' return true or false
'' you can capture the returning result in the AJAX that calls this method
End Function

How do i bind the json data to a asp.net dropdownlist using jquery?

I am trying to design a cascading dropdown. i am using 3 asp.net dropdowns. THe first one on page load loads the countries. Then when a country is selected i do a ajax call to a webmethod. I fetch the data for the teams belonging to that country. The data is in a dataset which i convert into JSON and then return it. On success what code do i need to add to bind the json data to the dropdown list.
below is the code.
$(document).ready(function() {
$('#ddlcountries').change(function() {
debugger;
var countryID = $('#ddlcountries').val();
$.ajax({
type: "POST",
url: "Default.aspx/FillTeamsWM",
data: '{"CountryID":' + countryID + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(jsonObj) {
/* WHAT CODE DO I ADD HERE TO BIND THE JSON DATA
TO ASP.NET DROP DOWN LIST. I DID SOME GOOGLING
BUT COULD NOT GET PROPER ANSWER */
},
error: function() {
alert('error');
}
});
});
});
Depending on what you're passing back to the client, I am going to assume it's a List<string>. You can adjust the code accordingly depending on what you're passing back to the client, since you're not telling us what is being passed back.
So if that is the case do something like this:
// first remove the current options if any
$('#ddlTeams').find('option').remove();
// next iterate thru your object adding each option to the drop down\
$(jsonObj).each(function(index, item){
$('#ddlTeams').append($('<option></option>').val(item).html(item));
});
Assuming again, if your List has an object containing teamid and `teamname11
// first remove the current options if any
$('#ddlTeams').find('option').remove();
// next iterate thru your object adding each option to the drop down\
$(jsonObj).each(function(index, item){
$('#ddlTeams').append($('<option></option>').val(item.teamid).html(item.teamname));
});
It is dependent on the data you are getting back from the server but this is what I came up with presuming it was a simple json structure, I was also wondering whether it may be better to send the data on the first request, and forget about the ajax.
$('#continent').change(function() {
// success function
$('#country').children().remove();
for (var country in json.continents[$(this).val()]) {
var $elm = $('<option>').attr('value', country)
.html(country);
$('#country').append($elm);
}
})
Here is a demo;
Edit: Given your data structure have update so something like this
var teams = json['TeamList'];
$('#teamid').change(function() {
// success function
var $t = $(this);
var $select = $('#teamname');
var i = (function() {
for (var i=0; i<teams.length; i++) {
if (teams[i]['teamid'] == $t.val()) {
return i;
}
}
})()
var name = teams[i]['teamname'];
var $elm = $('<option>').val(name).html(name);
$select.children().remove();
$select.append($elm);
})
see here for demo, please note this may requiring some changing to fit your specific use case, but it demonstrates simple iteration over arrays and objects

asp.net mvc outputting json with backslashes ( escape) despite many attemps to filter

i have an asp.net controller that output Json as the results
a section of it is here
returnString += string.Format(#"{{""filename"":""{0}"",""line"":[", file.Filename);
what i get returned is this:
"{\"DPI\":\"66.8213457076566\",\"width\":\"563.341067\",\"editable\":\"True\",\"pricecat\":\"6\",\"numpages\":\"2\",\"height\":\"400\",\"page\":[{\"filename\":\"999_9_1.jpg\",\"line\":[]},{\"filename\":\"999_9_2.jpg\",\"line\":[]}]]"
i have tried to return with the following methods:
return Json(returnString);
return Json(returnString.Replace("\\","");
return Json will serialize my string to a jSon string, this i know but it likes to escape
for some reason, how can i get rid of it ????
for info this is how i call it with jQuery:
$.ajax({
url:"/Products/LoadArtworkToJSon",
type:"POST",
dataType: "json",
async: false,
data:{prodid: prodid },
success: function(data){
sessvars.myData = data;
measurements = sessvars.myData;
$("#loading").remove();
//empty the canvas and create a new one with correct data, always start on page 0;
$("#movements").remove();
$("#canvas").append("<div id=\"movements\" style=\"width:" + measurements.width + "px; height:"
+ Math.round(measurements.height)
+ "px; display:block; border:1px solid black; background:url(/Content/products/"
+ measurements.page[0].filename + ") no-repeat;\"></div>");
your help is much appreciated
thanks
Are you looking at it in the debugger in VS or in the browser? The debugger will include the extra slashes when it displays it, while the actual output will not consist of those values.
Edit: Try passing an object to Json instead of a custom string. Your string is already in Json format (ish), so passing it to Json is re-ecoding it.
return Json(new { filename = "yourfilename" } );
or
return "yourfilename";
...etc, adding in whatever properties you need.

Submission with single quotes using jQuery, Ajax and JSON

I've looked around, and I'm trying to find an elegant solution to this, and I'm yet to find one. I have an ASMX web service in .NET that I'm trying to call that requires parameters.
I'm using jQuery on the client side to call the service and my jQuery code looks something like this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "/Reviews/HotelReview.asmx/SubmitReview",
data: "{'name': '" + name + "', " +
"'info': '" info + "'}",
processData: true,
beforeSend: function() { startSubmit(); },
complete: function() { submitComplete(); },
error: function(xhr) { submitError(xhr); },
success: function(msg) { submitSuccess(msg.d); }
});
It works very well, except when either name or info contain the ' character, a single quote. Simple enough, because my JSON defines the end of the value of the field and is a single quote. When either of these fields contains a single quote, all I get is an "Internal Server Error", but further inspection using Fiddler showed me the results (I won't bother to post them) indicating the single quote issue.
I've put something in place temporarily to remove the single quotes on the client side and put them back in on the server side, but this is far from elegant. Is there a more elegant way to escape these single quotes so that my code can work?
The specifications say that in JSON you can only use double-quotes around keys and values so try it with double quotes. I am pretty sure your error will be solved.
You may want to use json.js to encode / escape special characters in the actual values so you don't run into problems with values containing " for instance, or the stringify method from http://www.json.org/js.html.

Resources