I have a really simple AJAX method inside my Default.aspx.cs and it looks like this:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
And the Default.aspx looks like this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" src="http://192.168.1.2/tizma.com/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
});
});
function AjaxSucceeded(result)
{
alert(result.d);
}
function AjaxFailed(result)
{
alert(result.status + " " + result.statusText);
}
</script>
</head>
<body>
<div id="Result">Click me</div>
</body>
</html>
The problem is when I click the div the ajax error function is all that is ever called with a 200 status.
What am I doing wrong?
Not sure if it's causing the problem but you have a line which reads:
data: "{}",
it should read:
data: {},
or you can omit the line altogether as it's an optional parameter to the method call. You are currently setting it to a string value when it actually expects parameters for the webmethod which might cause problems.
Also, the lines reading:
contentType: "application/json; charset=utf-8",
dataType: "json",
seem unnecessary to me because for starters, it isn't obvious that your webmethod is actually returning json. I think it's just returning a string. Try removing those three lines alltogether and see if it doesn't just start working.
Related
I create example method for throw the error.
Code behind (.aspx.cs):
public partial class Test1 : System.Web.UI.Page
{
[WebMethod]
public static int Medthod1()
{
int data = 1;
try
{
data = data / (data - 1);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); // Attempted to divide by zero.
throw;
}
return 1;
}
}
I call the method by jQuery.ajax and alert the output error.
Inline Code (.aspx):
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test1</title>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function () {
$("#button1").on("click", function (event) {
$.ajax({
type: "POST",
url: "Test1.aspx/Medthod1",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result, status, xhr) {
alert(result.d);
},
error: function (xhr, status, error) {
alert(xhr.responseText);
alert(xhr.responseText.Message);
}
});
});
});
</script>
</head>
<body>
<button type="button" id="button1">Button 1</button>
</body>
</html>
Output from the line alert(xhr.responseText);:
{"Message":"Attempted to divide by zero.","StackTrace":" at Test.Test1.Medthod1() in C:\\Project\\Test\\Test\\Test1.aspx.cs:line 29","ExceptionType":"System.DivideByZeroException"}
Output from the line alert(xhr.responseText.Message);:
undefined
However, my output expectation is only:
Attempted to divide by zero.
The response you received was just a string. So, you need to parse it to an object before assigning.
var responseText = '{"Message":"Attempted to divide by zero.","StackTrace":"...","ExceptionType":"System.DivideByZeroException"}';
console.log(JSON.parse(responseText).Message);
// in your case, it should be:
// alert(JSON.parse(xhr.responseText).Message);
More information: JSON.parse()
I have a WebMethod in the code behind which is not being hit. I've googled a lot and found lots of questions like this. I've tried all suggestions I've seen whit no success.
IDE: Visual Studio 2017
Framework: 4.0
jQuery version: 3.1.1
Project type: Webforms (yeah, I miss my beloved MVC but it's not my fault!)
The error:
{"Message":"Invalid web service call, missing value for parameter:
\u0027id\u0027.","StackTrace":" at
System.Web.Script.Services.WebServiceMethodData.CallMethod(Object
target, IDictionary2 parameters)\r\n at
System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object
target, IDictionary2 parameters)\r\n at
System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext
context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n
at
System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext
context, WebServiceMethodData
methodData)","ExceptionType":"System.InvalidOperationException"}
URL being called: GET http://localhost:65050/Default.aspx/Save?{"id":"chkEditable","wasChecked":"on"}
When I click on any of the two check boxes, I get the following error on Chrome console
GET
http://localhost:65050/Default.aspx/Save?{%22id%22:%22chkEditable%22,%22wasChecked%22:%22on%22}
500 (Internal Server Error) jquery-3.1.1.min.js:4
Here's my aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="TesteWebMethod.Default" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-3.1.1.js"></script>
<script src="Scripts/jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function () {
$('#chkVisible').change(function () {
Save('chkVisible', $('#chkVisible').val());
});
$('#chkEditable').change(function () {
Save('chkEditable', $('#chkEditable').val());
});
});
function Save(_id, _state) {
var pageUrl = '<%= ResolveUrl("~/Default.aspx")%>';
var _data = { "id": _id, "wasChecked": _state };
$.ajax({
type: "GET",
url: pageUrl + "/Save",
data: JSON.stringify(_data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: OnFailure
});
}
function OnFailure(response) {
console.log('falha');
alert(response.d);
}
function OnSuccess(response) {
console.log('sucesso');
alert(response.d);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:CheckBox runat="server" AutoPostBack="false" ID="chkVisible" Text="Visivel" />
<asp:CheckBox runat="server" AutoPostBack="false" ID="chkEditable" Text="Editavel" />
</form>
And here is the code-behind
using System;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;
namespace TesteWebMethod
{
public partial class Default : System.Web.UI.Page
{
[WebMethod(true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string Save(string id, string wasChecked)
{
bool b = wasChecked == "on";
string data = "Id " + (b ? "was checked" : "was unchecked");
JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
var json = TheSerializer.Serialize(data);
return json;
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
I really got stuck on this. Can someone tell me what I'm doing wrong?
My answer would be that the method you are calling is a GET method, but you are passing data as if the method were a POST method. Webforms will not take parameters out of the request content and act like they came from the query string. That JSON data you are including in the request needs to be URL encoded into the query string, or the method needs to be converted into a POST method as well as the AJAX call.
You shouldn't stringify your json object if you set your object to the data property jquery will know how to build a GET request.
$.ajax({
type: "GET",
url: pageUrl + "/Save",
data: {"id": _data.id, "wasChecked": "'" + _data.wasChecked + "'"},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: OnFailure
});
Notice that I had to curate the data adding single quotes to the wasChecked attribute because That's the way ASP knows that's a string, which I think it's a terrible implementation.
As Kevin said, a POST would be much better. It would
$.ajax({
type: "POST",
url: "WebMethodTest.aspx/Save",
data: JSON.stringify({ "id": 2, "wasChecked": "test" }),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
And
[WebMethod(true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string Save(string id, string wasChecked)
{
I'm using web method in C# class file(i.e not a partial class of any web form) and I have html file. I just want to call web method from html file using JQuery AJAX GET and POST methods. Is it possible to do this? Is this have any sense? or i must want use asp web form?
To answer your question it's important that you first understand the prurpose of having a web service.Web services allow us to expose any piece of software over the internet and allow clients to consume it.
In .NET ASMX web services we expose software to the outside world by decorating methods with the [WebMethod] attribute.But even if we apply the [WebMethod] attribute our method will not be available over the internet unless it's inisde a:
.asmx web service file
.aspx web page
Hopefully now you understand why you can't simply define a [WebMethod] inside a standard C# class.Below is a simple example of calling an ASMX web service from a plain html page:
MyService.asmx:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class MyService : System.Web.Services.WebService
{
[WebMethod]
public string GreetUser(string name)
{
return String.Format("Hello {0}",name);
}
}
Index.html:
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnCallService").click(function () {
$.ajax({
type: "POST",
url: "MyService.asmx/GreetUser",
contentType: "application/json;charset=utf-8",
data: '{name:"' + $("#txtName").val() + '"}',
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function (errordata) {
console.log(errordata);
}
});
});
});
</script>
</head>
<body>
<input type="text" id="txtName" />
<input type="button" value="Call Service" id="btnCallService" />
</body>
</html>
Yes you can. Your html file can include a tag with functions that make ajax calls.
Here is a simple example from W3School's site:
<!DOCTYPE html>
<html>
<body>
<div id="demo"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
</body>
</html>
You see that the button has an 'onClick' event, which calls the loadDoc function.
And this is the function:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
Here is the link to the tutorial's page:
http://www.w3schools.com/ajax/
Your Ajax Call on HTML will look very similar to this
var options = {
type: "POST",
url: '<%=ResolveUrl("~/FileLocationWhereWebMethodIsDefined") %>',
data: "{'Add Parameters if your web method needs it'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
//jQuery(".overlay").show();
//jQuery(".progress").show();
},
success: function (msg) {
},
error: function (jqXHR, textStatus, errorThrown) {
// jQuery(".overlay").hide();
// jQuery(".progress").hide();
throw Error; // "error";
}
};
jQuery.ajax(options);
I want to display data in a table based on the search criteria in a textbox. I have implemented it without using Ajax but do not know how to call controller method using jquery and update table data. Please try to solve my problem. Thanks...
Index.cshtml
#model IEnumerable<MvcApplication4.Models.tbl_product>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<script src="#Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"></script>
<title>Index</title>
<script type="text/javascript">
$(document).ready(function () {
$('#Button1').click(function () {
alert("button clicked");
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home/Index',
data: "{'searchString':'" + document.getElementById('searchString').value + "'}",
async: false,
Success: function (response) {
alert("Success");
window.location.reload();
},
error: function () { alert("error"); }
});
});
});
</script>
</head>
<body>
#* #using (#Html.BeginForm("Index", "Home"))
{*#
#Html.TextBox("searchString");
<input type="button" value="filter" id="Button1" />
#* }*#
<table id="showData">
#{Html.RenderPartial("SearchList");}
</table>
</body>
</html>
SearchList.cshtml(Partial View)
#foreach (var item in Model)
{
<tr>
<td>#item.ProductName</td>
<td>#item.ProductId</td>
<td>#item.ProductDesc</td>
</tr>
}
HomeController.cs
public class HomeController : Controller
{
//
// GET: /Home/
ProductEntities dbentity = new ProductEntities();
public ActionResult Index()
{
return View(dbentity.tbl_product.ToList());
}
[HttpPost]
public ActionResult Index(string searchString)
{
var query = dbentity.tbl_product.Where(c => c.ProductName.Contains(searchString));
return View(query.ToList());
}
}
$.ajax({
url: '/ControllerName/ActionName',
type: "POST",
data: {criteria: 'criteria'},
contentType: "application/json",
success: function (data) {
//Replace existing table with the new view (with the table).
}
});
//write ControllerName without the key controller.
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home/Index',
data: JSON.stringify({'searchString':document.getElementById('searchString').value }),
async: false,
Success: function (response) {
alert("Success");
//append the data in between table tbody like,
$('table tbody').html(response);
//No window.location.reload(); It will cause page reload initial data will appear in grid.
},
error: function () { alert("error"); }
});
return false
Hope this helps.
Your ajax request should look like:
$.ajax({
url: '/<ControllerName>/<MethodName>',
type: "POST",
data: requestData,
contentType: "application/json;charset=utf-8",
success: function (data, textStatus, XMLHTTPRequest) {
//Success callback handling
},
error: function (XMLHTTPRequest, textStatus, errorThrown) {
//Error callback handling
},
cache: false //whether you want to cache the response or not.
});
I'm not going to give you the exact answer, but to help you to get it.
There are two steps:
First you must get sure the request is being done, and the response is being get on the browser.
To do so, you can
do it on your way: leave only the alert("Success"); and check it's being run.
better than that, open the browser's developer console (I prefer Chrome, but you can also use IE or FireFox + FireBug add-on) using F12. Set breakpoints and inspect variable values and code flow. See thit tutorial for Chrome developer tools.
set a breakpoint on the server action, and check it's executed
Second Once you're sure the firs part is working fine, use your succes function to replace the table content with the data received in the response. You can do it in several ways with jQuery. For example
$('#showData').html(response);
Again, you can execute this code and inspect the contents of response from the developer's console in your browser. This makes things eaiser when you're starting to use javascript.
(If your action generated the whole table, you could use jQuery's replaceWith which replaces the target, instead of its content. Don't use this for this case).
FINAL NOTE: please, remove this code window.location.reload();!!! This reloads the whole page with the current URL, so whatever thing you do in advance will be lost.
I'm using the JQuery autocomplete plug in, and am passing in an array of strings to autocomplete (see code below). The method I'm calling to get my data (GetCustomerNames) is just returning an array of strings, and that is working fine. I need to find some way to pass in a parameter to the GetCustomerNames Method so I can filter what is being returned. Can anyone help with this?
Here is the markup code in the Default.aspx page:
<head runat="server">
<title></title>
<script type="text/javascript" src="js/jquery-1.3.2.js" ></script>
<script type="text/javascript" src="js/jquery.autocomplete.js" ></script>
<script type="text/javascript">
//Working, but uses results output to an aspx page using StringBuilder, trying
//to find a way to get the data with json
//$(document).ready(function() {
// $("#example").autocomplete('AutoCompleteData.aspx');
//});
$(document).ready(function() {
$("#example").keyup(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetCustomerNames",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#example").autocomplete(msg.d);
},
error: function(msg) {
alert("error");
}
});
});
});
</script>
Customer Name:
And here is the code in the Default.aspx.cs code behind page implementing the GetCustomerNames method:
[WebMethod]
public static string[] GetCustomerNames()
{
string[] data = new string[] {"Andrew", "Ramona", "Russ", "Russell", "Raymond"};
return data;
}
You could use the data hash to pass parameters to the method:
$.ajax({
type: 'POST',
url: 'Default.aspx/GetCustomerNames',
data: '{ parameterName: "some test value" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
$("#example").autocomplete(msg.d);
},
error: function(msg) {
alert("error");
}
});
And your web method becomes:
public static string[] GetCustomerNames(string parameterName)