I have a textbox (txtDescription) where the user can type a description when an event is canceled.
The problem is when the there is an apostrophe ' with in that textbox AJAX throws an error. Without the apostrophe it works and saves fine.
I have tried using JSON.stringify but this did not work.
This is my code:
$("#btnCancelEvent").click(function () {
var CencelDesc = $("#txtDescription").val();
var user = $("#lblFullName").html();
if (CencelDesc === "") {
alert("Please provide a reason why this schedule event is being canceled.");
return false;
} else {
$.ajax({
type: "POST",
url: "ScheduleOverview.aspx/CancelEvent",
data: "{'ScheduleID': '" + ScheduleID +
"','CentreID': '" + CentreID +
"','CencelDesc': '" + CencelDesc + //this is where the problem occurs
"','user': '" + user + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
swal("Information", "Schedule Event Cancelled.", "success");
$('#CancelSchedule').modal('hide');
}
});
return false;
}
return false;
});
Please assist how I can fix this issue.
Two issues:
JSON uses double quotes, not single quotes.
Never buld JSON strings by hand. Instead, build an object and let JSON.stringify handle the escaping, etc., for you.
So:
$.ajax({
type: "POST",
url: "ScheduleOverview.aspx/CancelEvent",
data: JSON.stringify({ScheduleID: ScheduleID
,CentreID: CentreID
,CencelDesc: CencelDesc
,user: user }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
swal("Information", "Schedule Event Cancelled.", "success");
$('#CancelSchedule').modal('hide');
}
});
Side note: There's no need for dataType: "json" in that code. You're not doing anything with the response. In fact, in general, using dataType is an anti-pattern. Instead, ensure that the server sends back the correct Content-Type header.
Related
Well I am developing a web application in Asp.Net and in the code behind I am using C#. I've successfully written code to pass a class object to code behind method but I am wondering how to pass an array as an argument via ajax and jQuery.
I've tried something but it didn't work. Here is my code what I am trying to run
function Test(){
var argu = [1, 2];
$.ajax({
type: 'POST',
url: 'MyPage.aspx/Foo',
data: '{args: ' + argu + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// Success
},
error: function (response) {
// Failed
}
});
}
And this is my code behind method which is written in C#.
[WebMethod]
[ScriptMethod]
public static bool Foo(int[] args)
{
return true;
}
Application built successfully. I have put break points but my code behind method doesn't fire. I am wondering Where is the problem? What else I am missing here?
Well all code seems good enough to make a call but I think the problem is in passing the data in your code.
It should be like.
data: '{args: ' + JSON.Stringify(argu) + '}'
And finally your code should be like
function Test(){
var argu = [1, 2];
$.ajax({
type: 'POST',
url: 'MyPage.aspx/Foo',
data: '{args: ' + JSON.Stringify(argu) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// Success
},
error: function (response) {
// Failed
}
});
}
Hope that helps.
Where is the problem?
What you are sending is not valid JSON and that's what you are telling $ajax to send when you set contentType: "application/json; charset=utf-8"
JSON requires double quotes for keys and for string values
Don't try creating JSON manually ... use language built in serializers
Try changing:
data: '{args: ' + argu + '}',
To
data: JSON.stringify({args: argu }),
Note: Seems you are expecting int in server code. Looks suspicious when you are sending an object structure
Why no simply set the array value to data and do the post ?
function Test(){
var argu = [1, 2];
$.ajax({
type: 'POST',
url: 'MyPage.aspx/Foo',
data: argu,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// Success
},
error: function (response) {
// Failed
}
});
}
You can use JSON.stringify([1,2]) to send the entire data as a string to the backend, get the data as a string (rather than int[]) and deserialize of parse it back to int[]
I have a problem with this.
below are my jquery code and aspx.cs code.
I should send $('#UserID').val() to WebMethod as a parameter.
but in WebMethod it is always null.
if I change $('#UserID').val() to any string, it works well.
#UserID is correct. because I made a alert window with this value.
and.. I already changed data: '{userId: "' + $('#UserID').val() + '"}',
to data: JSON.stringify({ userId: $('#UserID').val() }).
but nothing works.
$.ajax({
url: "register.aspx/IsIdAvailable",
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{userId: "' + $('#UserID').val() + '"}',
dataFilter: function (data) {
var msg = JSON.parse(data);
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
}
})
[WebMethod]
public static bool test(string userId)
{
System.Diagnostics.Trace.WriteLine("userId: " + userId +"!");
...
}
output is always userId: !
Try changing your data attribute to something like:
data: {'userId': $("#UserID").val()}
when i add alert(file) line after ajax block code work but when i remove alert(file) code not work .
this is work fine :
function Delete(file) {
$.ajax({
type: "POST",
url: "Image.aspx/Delete",
data: '{file: "' + file + '" }',
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
$("#statusBox").text("ok"); //alert(response.d);
},
error: function (response) {
$("#statusBox").text("error"+response.text);
// alert(response.status + ' ' + response.statusText);
},
complete: function () {
// $("#statusBox").text("completed");
}
});
alert(file);
}
if i remove alert(file) line code web method not work.
this my c# asp.net code web method :
[WebMethod]
public static string Delete(string file)
{
try
{
// int lastSlash=file.ind
// Lesson learnt - always check for a valid URI
if (Uri.IsWellFormedUriString(file, UriKind.Absolute))
{
Uri uri = new Uri(file);
file = (uri.LocalPath);
}
//file= file.Remove(0)
//File.Delete(file);
File.Delete(HttpContext.Current.Server.MapPath(#"~\" + file.Replace("/", #"\")));
}
catch (Exception ex)
{
return ex.Message;
}
return "ok";
}
You're sending the request asynchronously,try to make false asynchronous.
for more information take a look at this
I see three (3) errors in your code:
data: '{file: "' + file + '" }',
datatype: "jsondata",
async: "true",
You are not sending a js object to the server.
jsondata is not a valid datatype.
async is a boolean and you are instead assigning a string value.
So the solution from here is:
data: {file: file }, // send a object
datatype: "text", // change to text because you are returning "ok" string
async: true, // remove the quotes
Another suggestion is try with default headers:
contentType: "application/json; charset=utf-8",
Try removing this line and see.
I am trying to use AJAX with ASP.NET for the first time - by trying to pass the following data to a WebMethod in my corresponding aspx page:
$.ajax({
type: "POST",
url: "myurl.aspx/SaveScreen",
data: "{'data': " + JSON.stringify(arrayRows.data) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
Here is my WebMethod in the aspx page. I have tried passing a simple data object which just contained one key and value, which worked successfully. When attempting to pass this object, I get an error stating that there is an internal server error with code 500.
What could I be doing wrong?
Try this:
data: {"data": JSON.stringify(arrayRows.data)}
Try this :
data: "{data: '" + JSON.stringify(arrayRows.data) + "'}"
You could wrap the data string in quotations:
$.ajax({
type: "POST",
url: "SpecifyPositioning.aspx/SaveScreen",
data: "{'data': '" + JSON.stringify(arrayRows.data) + "'}", //Added ' around JSON.stringify to pass string instead of object
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
This however would be a cleaner solution:
data: {"data": JSON.stringify(arrayRows.data)},
I have the following jQuery AJAX request:
function sendUpdate(urlToSend) {
var code = AccessCode;
var url = urlToSend;
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "webmethods.aspx/UpdatePage",
data: "{ accessCode: " + code + ", newURL: '" + url + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(response) { var results = response.d; } };
$.ajax(options);
}
And the corresponding ASP.NET WebMethod:
[WebMethod]
public static bool UpdatePage(string accessCode, string newURL)
{
bool result = true;
try
{
HttpContext.Current.Cache[accessCode + "l"] = newURL;
}
catch
{
result = false;
}
return result;
}
That all used to work correctly with "async:false", however I have to get rid of it as it freezes the browser until the response is received. Now the AJAX request above returns "undefined".
Could anybody tell me why it happens and where the problem is?
Thanks.
You should really make sure to properly encode this JSON. JSON.stringify is the most reliable method:
data: JSON.stringify({ accessCode: code, newURL: url })
This ensures that even if the code and url variables contain some dangerous characters that will break your string concatenations in the resulting JSON at the end everything will be properly encoded. The JSON.stringify method is natievly built into modern browsers but if you need to support legacy you could include json2.js.
Also because you code is no longer blocking you should make sure that if you call this sendUpdate from some button click or form submit you cancel the default action by returning false.
My way works correctly:
[System.Web.Services.WebMethod()]
public static string getHello(string str)
{
//do some things with str
return str;
}
In file .js, I define this function to call webmethod in file .cs:
function CallServerFunction(StrPriUrl, ObjPriData, CallBackFunction) {
$.ajax({
type: "post",
url: StrPriUrl,
contentType: "application/json; charset=utf-8",
data: ObjPriData,
dataType: "json",
success: function (result) {
if (CallBackFunction != null && typeof CallBackFunction != 'undefined') {
CallBackFunction(result);
}
},
error: function (result) {
alert('error occured');
alert(result.responseText);
window.location.href = "FrmError.aspx?Exception=" + result.responseText;
},
async: true
});
}
Then, call to use (call in file.js):
var text = $("#textbox_send").val();
var myresult;
CallServerFunction("Default.aspx/getHello", JSON.stringify({ str: text }), function (myresult) {
if (text != "")
$('#' + id).append('<p>' + $("#account_user").text() + ': ' + myresult.d + '</p>');
});
The "undefined" could be the result of a server error.If you use Firebug,Firefox(or any good client debugging tool), you can find the error returned by the server. Paste the error,if any.
Nevertheless, I also noted the the "data" for "accessCode" is not properly enclosed within quotes ‘ ’
The corrected data option would be :
data: "{ accessCode: '" + code + "', newURL: '" + url + "' }",
PS:
Since 'options' have a different meaning in Jquery, I would recommend changing the variable name as 'setting' . Change 'var options ' to 'var settings'. :)