Jquery AJAX with WebMethod removes zero from front - asp.net

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.

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 });
}
});

Calling ajax request from html page inside asp.net project

I cannot get a simple ajax example to work from an html page inside my visual studio project. It works fine from a webform (aspx):
...
webform1.aspx and form1.html
...
function ShowCurrentTime() {
alert("before json");
$.ajax({
type: "POST",
url: "json.aspx/GetCurrentTime",
data: "{name: bob }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
alert("after json");
}
function OnSuccess(response) {
alert(response.d);
}
...
webform1.aspx and form1.html
...
<input id="btnGetTime" type="button" value="Show Current Time"
onclick="ShowCurrentTime()" />
...
json.aspx
...
[WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
If I put the code in webform1.aspx, it works fine. If I put it on form1.html, nothing comes back from json.aspx. I am running the project in debug mode from my machine using vs2013. Any help would be appreciated.
Update #1
I checked fiddler and the server is returning the following result (500):
{"Message":"Invalid JSON primitive: bob.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at ...
Your json is malformed. Strings need to be in quotes. Put bob in quotes and you should be good. I'm unsure why it's working on the ASP.NET page though, unless it has the quotes there.
function ShowCurrentTime() {
alert("before json");
$.ajax({
type: "POST",
url: "json.aspx/GetCurrentTime",
data: "{name: \"bob\" }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
alert("after json");
}
function OnSuccess(response) {
alert(response.d);
}

(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

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.

Weird issue; Button click, Jquery to consume ASMX

I'm having quite a frustrating problem that I'm sure is TRIVIAL. Whenever I move this jQuery post inside the click function it sometimes works, but most of the time does not.
If I move it outside it works and posts and gives a response like it should everytime..
::boggled:: Someone please enlighten me.
$(document).ready(function() {
$('#Button1').click(function() {
//alert(document.getElementById('TextBox1').value);
$.ajax({
type: "POST",
url: "sudoku.asmx/getSolution",
data: "{'pid':'34367'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert("succes " + msg.d);
},
error: function(msg) {
alert("fail " + msg.d);
}
});
});
});
Looks like you need to have your click event return false.
$("#Button1").click(function()
{
$.ajax(...);
return false;
});

Resources