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
});
Related
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.
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've got some Ajax code with calls a WebMethod from within my back-end code and now want to be able to databind the information it receives to a repeater.
Here's my Ajax
$.ajax({
type: "POST",
url: "default.aspx/Call_Car",
data: '{ Ref: "MD12355"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var cars = msg.d;
$.each(cars, function(index, car) {
$('.test').text(car.PICKUP);
$('.test2').text(car.SUPPLIER);
});
}
});
At the moment it is writing the fields PICKUP and SUPPLIER to my labels but ideally i want it to be able to databind my repeater with all the data.
Here's the response I get back from this call
{"d":[{"SUPPLIER":"Magos Car Hire","PICKUP":"Funchal Airport"}]}
Is it possible to do this?
Thanks
You cannot, a repeater binds on the server side, and you are returning client side data.
You can use one of the jQuery grids or a variety of other grids (kendoui im particularly fond of from telerik)
Or you could request the page from the server that contains the data and grid and load that via ajax.
This is addressed in a bit more detail here:
Bind Data to Repeater using Ajax
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'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.