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.
Related
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
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
I have a web page which is redirected from a another page and have a querystring in it. now this page is calling a Jquery AJAX call to do some other task.
Page URL is like : http://localhost:1041/Inventory/Inventorydetail.aspx?invoiceid=3
now this page is calling a AJAX post to delete a record from the grid.
$(".DeleteInvoiceLine").click(function() {
//Get the Id of the record
var record_id = $(this).attr("id");
var loc = window.location;
// Ask user's confirmation
if (confirm("Do you want to delete this record?")) {
$.ajax({
type: "POST",
url: loc + "/DeleteInvoiceLineEntry",
//Pass the selected record id
data: "{'args': '" + record_id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msgstr) {
var msg = $("#ctl00_ContentPlaceHolder1_success");
msg.html(msgstr.d);
msg.show();
}
});
}
return false;
});
so when I call the AJAX call the page_Load event is called instead of the webmethod "DeleteInvoiceLineEntry".
if I have my page without the querystring passed it works fine.
could you please suggest me how I can call a AJAX call on the page which has a querystring data init.
I tried it both way passing the static URL
Not working
url: "Inventorydetail.aspx?invoiceid=3/DeleteInvoiceLineEntry"
Working (if there is no querystring data in the page)
url: "Inventorydetail.aspx/DeleteInvoiceLineEntry"
Thanks for your quick help.
Don't attach query string when you call ajax. It will confuse the communication as ajax actually use query string to pass json data. If you want to pass invoiceid to the ajax, include it in json data.
Change
var loc = window.location;
To
var loc = window.location.href.replace(window.location.search, '');
as Taesung Shin mentioned. The query string in the URL is confusing your application.
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);
In my web application I have a textbox called "Address" which is multiline and have 3 rows and 250 characters.
I am calling a javascript function in which i am calling AJAX to send the data to a webservice for some processing but AJAX is unable to process variable which contains multiline text.
I am reading multiline textbox value like this in javascript function.
var puid = document.getElementById('<%=userid.ClientID%>').value;
var paddress = document.getElementById('<%=xaddress.ClientID%>').value;
and passing like this.
$.ajax({
type: "POST",
url : "DataService.asmx/UpdateProfile",
data: "{'puserid': ' " + puid + 'padd': ' " + paddress + " '}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError
});
If I comment paddress parameters in ajax "data:" it works fine other wise ajax goes on "OnError" ...Oh i just figured out that my address has 'B' Area (apostrophe) in it thats why it its giving this problem. So how to parse apostrophe as textbox value and read in javascript variable and write back in database similary.
I'd use the jQuery Post function instead. Your GET request URIs shouldn't have new line chars in them.
var puid = document.getElementById('<%=userid.ClientID%>').value;
var paddress = document.getElementById('<%=xaddress.ClientID%>').value;
puid => string value
paddress => string value
$.ajax({
type: "POST",
url : "DataService.asmx/UpdateProfile",
data: {'puserid': puid , 'padd': paddress }, need = >","
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError
});