$.ajax & passing data to .asmx webservice - c#

I'm quite confused as to why this is happening.
I can't seem to pass data successfully via $.ajax, the URL gets all mangled up instead of the data being passed in a query string.
I've cleaned up the code for brevity, see below.
Webservice (using GET)
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string TestMethod(string country, string city)
{
return country + city;
}
jQuery
$.ajax({
url: "Test.asmx/TestMethod",
type: "GET",
data: '{"country":"' + country + '","city":"' + city + '"}',
dataType: "json",
success: function(msg) {
alert(msg.d);
}
});
Resulting URL and Error (in Firebug)
http://example.com/Test.asmx/TestMethod?{%22country%22:%22NZ%22,%22city%22:%22AK%22}
System.InvalidOperationException: Missing parameter: country.

Try to change
data: '{"country":"' + country + '","city":"' + city + '"}'
To
data: "country="+country+"&city="+city

Adding a "contentType" property to the options list would be the easiest change in my mind.
I also use JSON.stringify() to reduce the introduction of quotation errors.
$.ajax({
url: "Test.asmx/TestMethod",
type: "GET",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ country: country, city: city }),
dataType: "json",
success: function(msg) {
alert(msg.d);
}
});

Related

calling ajax server-side method with mappage route c#

Salam aleykum, i'm trying here to call an ajax server-side method using the mappage route but it always says: POST 404 (Not found)
here is the code c#:
[System.Web.Services.WebMethod]
public static bool RemovePhotofromAlbum(string list_photos_hotel)
{
.....
return true;
}
and here the jquery code should like :
function RemovePhotofromAlbum(list_photos_hotel) {
$.ajax({
type: "POST",
url: $(location).attr('pathname') + "/RemovePhotofromAlbum",
data: '{list_photos_room_type: "' + list_photos_hotel + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
....
},
failure: function (response) {
alert(response.d);
}
});
}
Without using the mappage route it's working.
but here i want to use the mappage route
i know that there is a problem with the URL in the ajax method but i don't know how to fix it.
any help would be appreciated.
:)
If it's impossible just tell me
$(location).attr('pathname')
This line is used for add attribute in DOM
So if you want to save baseurl,Keep it in web.config, hidden field or any other js file and than use it
You should use $(location).attr('href') and not $(location).attr('pathname')
and you have an error with your parameter name it should be 'list_photos_hotel' and not 'list_photos_room_type'
try this :
function RemovePhotofromAlbum(list_photos_hotel) {
$.ajax({
type: "POST",
url: $(location).attr('href') + "/RemovePhotofromAlbum",
data: '{list_photos_hotel: "' + list_photos_hotel + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
failure: function (response) {
alert(response.d);
}
});
}
assuming you run the script from the same aspx page your server method runs.
Edit :
Because you use map route, you get 404. you should pass the physical location.
Your method is in the path : Manage/admin_2/index.aspx :
function RemovePhotofromAlbum(list_photos_hotel) {
$.ajax({
type: "POST",
url: "/Manage/admin_2/index.aspx/RemovePhotofromAlbum",
data: '{list_photos_hotel: "' + list_photos_hotel + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
failure: function (response) {
alert(response.d);
}
});
}

webmethod isn't catching ajax POST

I'm trying to call a server side method with ajax. This is what I've got:
Client side:
function accept(thisButton) {
$.ajax({
type: "POST",
url: "Default.aspx/editMaxUsers",
data: '{param: "' + $(thisButton).prev().val() + '" }',
contentType: "application/json: charset=utf-8",
dataType: "json",
success: function (result) { alert("successful" + result.d); }
});
}
Server side:
[System.Web.Services.WebMethod]
public static string editMaxUsers(string maxUsers)
{
return maxUsers; //I also have a breakpoint here that isn't stopping the execute
}
When I check the calls with firebug I can see that the POST is being sent and looks fine. But Nothing seems to be happening on server side. What am I doing wrong?
EDIT: Don't know if it's relevant, but the url already contains some parameters. I've tried the following url: "Default.aspx/" + window.location.search + "editMaxUsers" but no success.
The parameters of your WebMethod need to match the parameter name you are passing in.
Change
data: '{param: "' + $(thisButton).prev().val() + '" }',
to
data: '{maxUsers: "' + $(thisButton).prev().val() + '" }',
1.Go to App_Start/RouteConfig and change
settings.AutoRedirectMode = RedirectMode.Permanent;
to
settings.AutoRedirectMode = RedirectMode.Off;
2.As #F11 said the paramter in the WebMethod and the key in the json object should be with the same name and what I strongly recommend is not to build json object manually. It is better to do:
function accept(thisButton) {
var data = {};
data.maxUsers = $(thisButton).prev().val();
$.ajax({
type: "POST",
url: "Default.aspx/editMaxUsers",
data: JSON.stringify(data),
contentType: "application/json: charset=utf-8",
dataType: "json",
success: function (result) { alert("successful" + result.d); }
});
}

Ajax call not working

I am making an ajax call to C# function but it is not being call.
This is ajax call:
$('#button1 button').click(function () {
var username = "username_declared";
var firstname = "firstname_declared";
$.ajax({
type: "GET",
url: "practiced_final.aspx/ServerSideMethod",
data:{username1:username,firstname1:firstname},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#myDiv').text(msg.d);
},
error: function (a, b, c) {
alert(a + b + c);
}
});
return false;
});
This is C# code:
[WebMethod]
public static string ServerSideMethod(string username1, string firstname1)
{
return "Message from server with parameter." + username1 + "hello" + firstname1;
}
This method is not getting hit and shows a error message like this:
object XMLHttpRequest]parsererrorundefined
Any help will be highly appreciated.
$('#button1 button').live('click', function () {
var username = "username_declared";
var firstname = "firstname_declared";
$.ajax({
url: "/practiced_final.aspx/ServerSideMethod", type: "GET", dataType: "json",
data: JSON.stringify({ username1: username, firstname1: firstname }),
contentType: "application/json; charset=utf-8",
success: function (msg) {
$('#myDiv').text(msg.d);
},
error: function (a, b, c) {
alert(a + b + c);
}
});
});
$('button#button1') or $('#button1') or $('#button1 button')
check u selector also. put one alert message inside click event and see
Finally it is working.This is the final code.
Thanks everyone for your wise replies.
$.ajax({
type: "POST",
url: "practiced_final.aspx/hello_print",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
$('#myDiv').text(msg.d);
}
})
return false;
Enjoy.
In your code I can see : dataType: "json",
But you're not sending a Json through your C# function... When you're telling ajax that the dataType is a json, it will JSON.parse() the response. Maybe that's where the failure is.
Try changing the dataType, or removing it (jQuery will try to guess it).
Please Change below line in Jquery function.
data:{username1:username,firstname1:firstname},
to
data:"{'username1':'" + username + "','firstname1':'" + firstname + "'}",
Hope this will help you.
$('button#button1') //Or check selector put one alert inside onclick
$('#button1').live('click', function () {
var username = "username_declared";
var firstname = "firstname_declared";
$.ajax({
type: "GET",
url: "practiced_final.aspx/ServerSideMethod",
data: JSON.stringify({ username1: username, firstname1: firstname }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#myDiv').text(msg.d);
},
error: function (a, b, c) {
alert(a + b + c);
}
})
return false;
it may help
Try changing this line:
data:{username1:username,firstname1:firstname},
to
data:JSON.stringify({username1:username,firstname1:firstname}),
Edit:
I'm not sure if this is the cause of the problem, but this is one thing I noticed different between our jQuery ajax calls. Also, changed result string to reflect #dana's criticism in the comments of my answer.

How can i read POSTED Json Data in C#.net?

I want to read data which is posted in JSON in my c#.net application? I am very new with this JSON and POST method?
Can anyone please help me?
I am posting data from page1. to other page2 (smsstaus.aspx in my case) for testing purspoe.
I want to read that JSON posted data in PageLoad of Page2.
Sample code.....
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
}
You could define a WebMethod in your smsstatus.aspx (SendStatus for example)
An implementation could look something like this (from the top of my head)
[WebMethod]
public static void SendStatus(string sid, string status)
{
// retrieve status
}
Now you can create a request to consume this method, like this:
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx/SendStatus",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
.NET wil deserialize the json string to and pass them as arguments to SendStatus
when you are using Jquery and you throw JSON in the data thingy it will change in a normal Post but what you are now doing is gonna give problems change the code to:
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: {"SmsSid":$("#<%= txtSmsSid.ClientID%>").val(),"SmsStaus": $("#<%= txtSmsStaus.ClientID%>").val()},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
}
and you can use the normal POST but if you want to play with JSON in C# see this aritcle
http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx
Do not change the contentType if you want to request the aspx (WebForm) and not the WebMethod. (When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded").
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
dataType: "json", // The type of data that you're expecting back from the server.
success: function (msg) {
alert(msg.d);
},
error: function () { }
});
Receive data from the Page_Load handler,
//Read Form data
string testData = Request["SmsSid"] + " " + Request["SmsStaus"];
//Prepare Json string - output
Response.Clear();
Response.ContentType = "application/json";
Response.Write("{ \"d\": \"" + testData +"\" }");
Response.Flush();
Response.End();

How to use jQuery to make a call to c# webservice to get return value

I want to use jQuery to make a call to a c# web service called c.ashx which checks whether that username is valid and returns an error message as a string.
What should I put for data: and content type: if the return value of the c# webservice is a string value?
jQuery.ajax({
type: "GET",
url: "/services/CheckUserName.ashx",
data: "",
contenttype: "",
success: function (msg) {
alert("success");
},
error: function (msg, text) {
alert(text);
}
});
I have created a .asmx file instead, but it doesn't get called by the jQuery. Is the following correct?
jQuery.validator.addMethod("UsernameCheck", function (value, element) {
jQuery.ajax({
type: "POST",
url: "/services/CheckUsername.asmx?CheckUsername",
data: '{ "context": "' + jQuery("#username").value + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert("success");
},
error: function (msg, text) {
alert(text);
}
});
});
Data should contain the parameters of the method you are calling in a web service. However, the ashx extension is for an HTTP Handler, which is not a good choice for this scenario. A web service should by used instead.
So if you were calling /services/LoginServices.asmx?CheckUserName, and CheckUserName.asmx had a webmethod ValidateUser such as
public string ValidateUser(string username)
then the data attribute for jQuery would be
data: '{ "username": "' + usernameValue + '"}'
your contentType should be application/json; charset=utf-8, and dataType should be "json".
Note that you're not going to call /services/CheckUserName.asmx, the name of the method in the web service has to be appended to the webservice url, /services/LoginServices.asmx?CheckUserName.
Also, you'll need to change your type to "POST".
Here's a complete example:
$.ajax({
type: 'POST',
url: 'LoginServices.asmx/CheckUserName',
data: '{"username": "' + usernameValue + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
alert("Result: " + msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus);
}});
Hope this helps
The jQuery code wasn't working because it wasn't calling the webservice. I fixed this by creating a HTTP handler class and passing it the username. I changed the value for data: to the following and it passed the username entered by the user:
data: "username=" + jQuery("#username").val(),

Categories

Resources