Escape character and error 500 - asp.net

I have a problem with some basic ajax and asp.net web service. In my website page i have a text box that is reach text editor, when i put text and try to submit it, ajax supposed to take the text and pass it to asp.net web service. When the sentence contains no escape characters it goes well, however when it does contains escape character the asp.net web service gives me error 500. On debug it doesn't even enters into web service.
So the question is: How can i fix it ?
Here is the code that i have.
Javascript:
//posting the user comment
function postComment() {
var comment_body = $("textarea[id*='txt_editor']").val();
$.ajax({
type: "POST",
url: "Article.asmx/postComment",
data: "{'article_id': '" + article_id + "', 'comment_body' : '" + comment_body + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
page_num = 1;
getComments();
clearComment()
}
});
}
And the web service looks like that:
//posting the comment to database
[WebMethod]
public int postComment(int article_id, string comment_body)
{
try
{
using (ForMarieDataContext forMarie = new ForMarieDataContext())
{
tbl_article_comment newComment = new tbl_article_comment();
newComment.article_id = article_id;
newComment.comment_author = "Dmitri";
newComment.comment_date = DateTime.Now.ToString();
newComment.comment_body = comment_body;
forMarie.tbl_article_comments.InsertOnSubmit(newComment);
forMarie.SubmitChanges();
}
return 1;
}
catch(Exception ex)
{
return 0;
}
}
}
This is the basic code and i will add more to it to check for security.
However for now, i need to somehow do something with the escape characters in text.
Thanks in advance.

Let jQuery handle the escaping and encoding of the parameters:
$.ajax({
type: "POST",
url: "Article.asmx/postComment",
data: { article_id: article_id, comment_body: comment_body },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
page_num = 1;
getComments();
clearComment()
}
});
Pay attention to the data property.

Related

WebMethod access page control and set value

My page name
public partial class AtamaGorevDegistir : System.Web.UI.Page
{}
My webmethod ajax side
var path = getLocation(location.href);
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
// data: "{" + str + "}",
contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
}
});
My webmethod
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string KisiBilgiDoldur(string KayitID, string TeklifID)
{
AtamaGorevDegistir atama = new AtamaGorevDegistir();
atama.AtananSuren.Value = "123";
return null;
}
But my problem my Control is null . But i can access this method but didnt set value and give error message. Why this happened?
WebMethod and ScriptMethod can't access the controls collection of the calling page. Think of it as outside the normal Web Forms lifecycle. When you use AJAX, you need to pass all data to the server side method it needs, and your server side should return all data that the client side needs. Then the client side should take that returned data and manipulate the DOM as necessary to display the result.
In your WebMethod, return the data instead of trying to assign it to a control, remove the return null;.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string KisiBilgiDoldur(string KayitID, string TeklifID)
{
return "123";
}
In your client side success handler, get the returned data and set the value of the control using JavaScript.
var path = getLocation(location.href);
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
// data: "{" + str + "}",
contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
//set control value to data.d here
}
});
You don't set the control value with a webmethod. Your return a value and from the api and do something with it, in the browser. Working with webmethods are not like webforms. The value you return in your webmethod is null... you're setting that null value into 'dd' in js, but you don't do anything with it. When you get your value back from the webmethod you need to do something with it. try 'alert(data.d)' in your success callback to see what i mean. Then $('#elm').text(data.d) if you want it on the page.
You should add parameters to data.
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
data:JSON.stringify({ KayitID: '1', TeklifID:'2' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
}
});

(JSON.stringify) ---> (asp.net function) ----> (JSON.parse) ---->Microsoft JScript runtime error: Invalid character

I have a simple javascript object. I serialize it with JSON.stringify I send it to a asp.net web function that just return it. But when I try to parse the returned string with JSON i get
Microsoft JScript runtime error: Invalid character
$(document).ready(function() {
$.ajax({
type: "POST",
url: "test.aspx/PassBackdata",
contentType: "application/json; charset=utf-8",
data: "{'args': '" + JSON.stringify(MyObject) + "'}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
});
function AjaxSucceeded(result) {
var a=JSON.parse(result);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
};
<System.Web.Services.WebMethod()> _
Public Shared Function PassBackdata(args As String)
Return args
End Function
How can I solve this problem? Thank you
If the error occurs on succes function, you may want to check the format of the result object. I had to use var a=JSON.parse(result.d); because that is how it was returned by webservice, it wasn't a direct json, but an object with a "d" field which was the json.
For checking the result I use fiddler.
Instead of:
"{'args': '" + JSON.stringify(MyObject) + "'}"
Try this:
JSON.stringify({args: MyObject})
Don't do yourself what JavaScript can do for you ;)
It would help to know what MyObject looks like, however:
JSON must have key names in double quotes, not single quotes. Try something like this instead:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "test.aspx/PassBackdata",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({args:MyObject}),
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
});
function AjaxSucceeded(result) {
var a=JSON.parse(result);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
};
if I do: JSON.parse(result.d) instead of JSON.parse(result) it works.
function AjaxSucceeded(result) {
var a=JSON.parse(result.d);
}
don't know why

Jquery AJAX with WebMethod removes zero from front

I have following code. Jquery Ajax calls webmethod . If i pass zipcode "07306" it returns and sets session to "7306" . No idea why it removes zero from front!
function onChangeLocation(){
var newzip =$('#<%= txtNewLocation.ClientID %>').val();
$('#<%= lblDefaultLocation.ClientID %>').html(newzip);
$.ajax({
type: "POST",
url: "/WebMethods.aspx/ChangeLocation",
data: "{newLocation:" + newzip + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
}
});
}
[System.Web.Services.WebMethod()]
public static String ChangeLocation(String newLocation)
{
HttpContext.Current.Session["ClientZipCode"] = newLocation.ToString();
return newLocation.ToString();
}
Can someone please explain why it removes zero from front ?
The problem is that JS thinks it an integer changing
$('#<%= lblDefaultLocation.ClientID %>').html(newzip);
to
$('#<%= lblDefaultLocation.ClientID %>').html(newzip + '');
Should fix it.

2 page methods on an aspx page

I'm calling a page method with jquery and it works just fine. I'm creating a second one and it's not working at all; all I get is the error function. Is it possible to put more than 1 page method in an aspx page?
Here's my jquery on the client:
function LoadCount() {
var TheObject = $.toJSON(CurrentForm);
var TheParameter = "{'TheParameter' : '" + TheObject + "'}";
$('#testobj').html("loading");
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/GetCount",
data: TheParameter,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
function successFn(thedata) { $('#result').html(thedata.d); };
function errorFn() { alert("problem getting count"); };
function LoadData() {
var ConfirmLoad = "test";
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/GetLoaded",
data: ConfirmLoad,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successLoad,
error: errorLoad
});
};
function successLoad(thedata) { alert((thedata.d)); };
function errorLoad() { alert("problem getting loaded"); };
And on the server side, I have this:
[WebMethod]
public static string GetCount(string TheParameter)
{
// some code
return JsonResult;
}
[WebMethod]
public static string GetLoaded(string ConfirmLoad)
{
return "test string";
}
LoadCount and GetCount work great, I thought I'd copy the implementation to create another page method but the second time, nothing good happens. Thanks for your suggestions.
You need to set dataType: "text" in the $.ajax() call properties if you're just returning plain text instead of a JSON encoded string.
You might also want to leave the contentType unspecified (at the default value of 'application/x-www-form-urlencoded') if your're sending plain text instead of a JS object.

JQuery and ASP.Net

Well im trying to return a more complex type than a string or bool but i fail what am i doing wrong?
JavaScript
<script language="javascript" type="text/javascript">
///<Reference Path="~/Script/jquery-1.3.2-vsdoc.js" />
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Test.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.Name);
},
failure: function() { alert("Failed") }
});
});
});
</script>
C# (This is not a webservice just a normal webpage)
[WebMethod]
public static ImageDC GetDate()
{
ImageDC dc = new ImageDC();
dc.Id = 1;
dc.Name = "Failwhale";
dc.Description = "Hurry the failwale is going to eat us!";
dc.IsPublic = true;
return dc;
}
I'm not sure what version .NET your running, but there is a breaking change with object returned from a web service. Check out this article.
http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/
If you use fiddler to look at the request/response, it should be easy to tell if this is the problem.
http://www.fiddler2.com/fiddler2/
You should return a string.
return "dc = {Id:"+dc.Id+", Name:" + dc.Name +", Description: " +dc.Description + ", IsPublic: " +dc.IsPublic "}";

Resources