I'm building a Web Application in which I'm trying to call a WebMethod in a WebForm, I've tried every single page in google but I'm still getting nothing. This is an example of the Jquery Ajax Call
$.ajax({
type: "Post",
url: "Default.aspx/Return",
data: {dato:'Hello'},
contentType: "application/json; chartset:utf-8",
dataType: "json",
success:
function (result) {
if (result.d) {
alert(result.d);
}
},
error:
function (XmlHttpError, error, description) {
$("#grdEmpleados").html(XmlHttpError.responseText);
},
async: true
});
And this is the WebMethod in the codebehind
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public static string Return(string dato)
{
return dato;
}
You can't access a Static method this way. Remove the "Static" reference and it will work. Also, like someone else said - do not use that as your method name "Return".
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string Return(string dato)
{
return dato;
}
I think, on your success event the function with result is used, which is a string and u are trying to access property named d assuming result is an object.
use of only alert(result);
User F12 tool to debug and find your error.
Make sure that you have enabled page methods in your ScriptManager element:
<asp:ScriptManager ID="scriptManager" runat="server" EnablePageMethods="true" />
and your method
$.ajax({
type: "Post",
url: '<%= ResolveUrl("~/Default.aspx/Return") %>',
data: {dato:'Hello'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (result) {
alert(result);
},
error:
function (XmlHttpError, error, description) {
$("#grdEmpleados").html(XmlHttpError.responseText);
},
async: true
});
Try this
var url = window.location.pathname + "/Return";
$.ajax({
type: "Post",
url: url,
data: {dato:'Hello'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (result) {
alert(result.d);
},
error:
function (XmlHttpError, error, description) {
$("#grdEmpleados").html(XmlHttpError.responseText);
},
async: true
});`
Related
I have this simple ajax method:
$.ajax({
type: 'POST',
url: 'http://localhost:1195/widget/postdata',
datatype: "jsondata",
async: false,
success: function (data) {
alert("ok")
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
And this simple method in c#:
[HttpPost]
public JsonResult PostData()
{
return Json("1");
}
When I check the inspector console I have "1" in response but my ajax method always goes to error function.
Why is it so?
In your AJAX call it should be dataType: "json" and not datatype: "jsondata". You can refer to the docs
Also use #Url.Action tag in your url call: url: '#Url.Action("postdata", "widget")'
For a small test, I have used the following AJAX call to the same controller method that you have posted and I am getting the correct result:
$(document).ready(function () {
$("#button_1").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url:'#Url.Action("PostData", "Home", null, Request.Url.Scheme)',
datatype: "json",
async: false,
success: function (result) {
alert(result);
},
error: function (error) {
alert(error);
}
});
});
});
</script>
<button id="button_1" value="val_1" name="but1">Check response</button>
Output:
Change the Ajax request to the following :
$.ajax({
type: 'POST',
url: '/widget/postdata',
datatype: "json",
async: false,
success: function (data) {
console.log(data);// to test the response
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
Always use relative URL instead of full URL that contains the domain name, this will make the deployment easier so you don't have to change the URls when going live
Ajax:
var test = "test";
$.ajax(
{
type: "POST",
url: "project/function",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { input: test },
success: function (response) {
$("#lblMsg").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
C# function:
[WebMethod]
public void function(string input)
{
}
The connection is made successfully when I don't include a parameter. I have tried different single and double quote permutations of the 'data' portion of the ajax call, to no avail.
I have also tried setting the dataType to "text" with similar results.
What am I missing?
I would suggest that you shouldn't send your data as JSON. Just remove the
contentType: "application/json; charset=utf-8"
and jQuery will serialise the data into normal url-encoded form data format, which is what the WebMethod is expecting.
try this one may be resolve your issue
var test = "test";
$(document).ready(function () {
$.ajax({
type: "POST",
url: "project/function",
contentType: "application/json; charset=utf-8",
datatype: "json",
data:JSON.stringify({ 'input': test }),
success: function (response) {
$("#lblMsg").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
});
i have some problem when i use jquery.when function in web form using master page
This is my code in web form using master page
$(document).ready(function(){
$.when(masterPageFunction()).done(function(){
webFormFunction();
});
})
And this my master page
function masterPageFunction() {
//In this function i call 2 ajax like this
$.ajax({
type: "POST",
url: "/api/master/xxx/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.ajax({
type: "POST",
url: "/api/master/xxx2/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
}
})
}
})
}
result is web function is running when master page function not done
please help, thank you so much
You're close, but the when, then and done functions rely on promises. You aren't returning any promises in your code, so it's just running straight through.
First, you'll need to obtain the result of the promise after it completes in the done function in your master page. We'll do that by adding a response parameter to the callback, then passing it through to webFormFunction.
$(document).ready(function(){
$.when(masterPageFunction()).done(function(response){
webFormFunction(response);
});
})
Next, we need to add a promise to masterPageFunction and return it. You resolve the promise with the response you want to send back to the done function in your master page. Like so:
function masterPageFunction() {
// Create the promise
var deferred = $.Deferred();
//In this function i call 2 ajax like this
$.ajax({
type: "POST",
url: "/api/master/xxx/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.ajax({
type: "POST",
url: "/api/master/xxx2/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// Resolve the promise with the response from $.ajax
deferred.resolve(response);
}
});
}
});
// Return the promise (It hasn't been resolved yet!)
return deferred.promise();
}
In this way, webFormFunction won't be called until the second ajax call completes, which resolves the promise.
This is supposedly very easy but for some reason it has taken me about 2 hours and countless searches and nothing is working
I am trying to call a WebMethod from ajax, and it works quite well.
As soon as I try to change the c# function to accept parameters and send one from ajax everything fails
Code:
c#:
[WebMethod]
public static string GetBGsForSelectedCrop(string cropName)
{
return "asdasd";
}
jquery:
$().ready(function () {
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetBGsForSelectedCrop",
data: "Wheat",
success: function (msg) {
$("#Result").text(msg.d);
alert(msg.d);
console.log(msg)
}
});
});
});
I have tried datatype: "json", contentType: "application/json; charset=utf-8", and tried without both and datatype: "string" and datatype: "text", GET, data: "{'ABCD'}, data:{"cropName: Wheat"}, and data: json.Stringify("Wheat").
I get undefined for msg.d and sometimes HTTP error 500 if I take it too far.
What am I missing? It is just a simple task and should've been done in seconds..
As the guys in the comments says, you need to change your code for:
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetBGsForSelectedCrop",
data: JSON.stringify({ cropName: "Wheat" }),
dataType:'text',
contentType: "application/json; charset=utf-8",
success: function (msg) {
$("#Result").text(msg.d);
alert(msg.d);
console.log(msg)
}
});
});
Your error is the data is no good encoded, and you are missing the datatype.
What is the stringfy It Convert any value to JSON.
I am trying to post to a method using jQuery and Ajax. My Ajax code is as follows:
var isMale = $(e.currentTarget).index() == 0 ? true : false;
$.ajax({
type: "POST",
url: "Default.aspx/SetUpSession",
data: { isMale: isMale },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
// Go to next question
}
});
And here is my WebMethod:
[WebMethod]
public static void SetUpSession(bool isMale)
{
// Do stuff
}
I get a 500 (Internal Server Error) looking at the console, the method never get's hit. After I changed data to "{}" and removed the bool from the method signature the method then gets hit, so I'm assuming its something to do with the Ajax.data attribute I'm trying to pass.
Two things you need to modify :-
1) Make sure that this line is written in your web service page and should be uncommented.
[System.Web.Script.Services.ScriptService]
2) Modify the "data" in the code as :-
$.ajax({
type: "POST",
url: "Default.aspx/SetUpSession",
data: '{ isMale:"' + isMale + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
// Go to next question
}
});
Pass string instead of bool
[WebMethod]
public static void SetUpSession(string isMale)
{
// Do stuff
}
Alternative you can use pagemethods through script manager.
Try following code:
var params = '{"isMale":"' + $(e.currentTarget).index() == 0 ? true : false + '"}';
$.ajax({
type: "POST",
url: "Default.aspx/SetUpSession",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
responseType: "json",
success: function (data) {}
});
[WebMethod]
public static void SetUpSession(string isMale)
{
// Do stuff
}