I have to use JQuery.Ajax() to autocomplete some fields. The problem is that it works on local but not once on the server. I wrote a test page where I only call Ajax (Test.aspx).
JQuery in Test.aspx:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "Test.aspx/getData",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{}', // same problem without that line
success: function (response) {
alert(response);
},
error: function (request, status, error) {
alert(error);
}
});
});
</script>
The url is good : when I only specify url : "Test.aspx" it fires Page_Load.
When I specify url : "Test.aspx/getData" it doesn't hit the function and Ajax returns the whole HTML page (meaning that it could not reach the function). I also tested url : "Test.aspx/getData/"without success.
C# in Test.aspx.cs
[System.Web.Services.WebMethod]
public static string getData()
{
Dictionary<string, string> name = new Dictionary<string, string>();
name.Add("1", "Valeur 1");
name.Add("2", "Valeur 2");
string myJsonString = (new JavaScriptSerializer()).Serialize(name);
return myJsonString;
}
Here I think I have specified all the required stuff: WebMethod, the static attribute, the function returns a JSON oject...
In my web.config, I have this line in system.web :
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e3"/>
</httpModules>
My application is hosted on a Windows Server 2008 (IIS 6.1).
I spent hours on that problem and didn't find anything on the web to resolve it.
Edit 1 :
I also tried PageMethods.getData after including <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />inside the form. The result is still the HTML page.
I made some changes to your code. Posted here works:
aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#doAjax").click(function () {
$.ajax({
type: "POST",
url: "Test.asmx/getData",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{}', // same problem without that line
success: function (response) {
alert(response.d);
},
error: function (request, status, error) {
alert(error);
}
});
})
})
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="button" value="doAjax" id="doAjax" />
</form>
</body>
</html>
Web Service:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Test : System.Web.Services.WebService
{
[WebMethod]
public string getData()
{
Dictionary<string, string> name = new Dictionary<string, string>();
name.Add("1", "Valeur 1");
name.Add("2", "Valeur 2");
string myJsonString = (new JavaScriptSerializer()).Serialize(name);
return myJsonString; }
}
Related
This question already has an answer here:
How to refer http handler file from jQuery ajax under different directory of asp.net web application
(1 answer)
Closed 5 years ago.
I created a http handler file in following directory of my application
I am referring this handler from common.js file using jQuery ajax and common.js file referred in aspx pages StoresSummary.aspx & EmoloyeeProfile.aspx
From EmoloyeeProfile.aspx I am able to call the handler and getting the output, but from StoresSummary.aspx jquery ajax call getting failed.
I know the cause of failure because the path of CommonHandler.ashx file does not map correctly due to location hierarchy of StoresSummary.aspx.
This is a sample code I am posting, the http handler file I need to call from jQuery ajax and aspx pages may exists in different directory of same web application.
How do I give path of CommonHandler.ashx in ajax jQuery call so any location hierarchy of my aspx page can call it.
This is my code
common.js
function GetMessage(key) {
var message = '';
$.ajax({
type: 'POST',
url: '../../Common/Handlers/CommonHandler.ashx', /*Working for EmoloyeeProfile.aspx but not for StoresSummary.aspx*/
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: { 'MessageKey': key },
success: onSucess,
error: OnFailed,
async: false
});
function onSucess(res) {
message = res;
}
function OnFailed(res) {
alert('failed');
}
return message;
}
CommonHandler.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
namespace DemoWebApp.Common.Handlers
{
/// <summary>
/// Summary description for CommonHandler
/// </summary>
public class CommonHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(GetData(context.Request["MessageKey"]));
context.Response.ContentType = "text/html";
context.Response.Write(result);
}
private string GetData(string Id)
{
return DateTime.Now.ToString(); //just to demostrate
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
StoresSummary.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../../../Common/Scripts/common.js"></script>
<script src="../../../Common/Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Get Message" OnClientClick="return CallMethod();" />
</div>
</form>
<script type="text/javascript">
function CallMethod() {
var msg = GetMessage('001');
alert(msg);
return false;
}
</script>
</body>
</html>
EmoloyeeProfile.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../Common/Scripts/common.js"></script>
<script src="../Common/Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Get Message" OnClientClick="return CallMethod();" />
</div>
</form>
<script type="text/javascript">
function CallMethod() {
var msg = GetMessage('001');
alert(msg);
return false;
}
</script>
</body>
</html>
Provide absolute path to the handler. You are providing relative path now. See the ajax url section.
$.ajax({
type: 'POST',
url: '/Common/Handlers/CommonHandler.ashx', /*Working for EmoloyeeProfile.aspx but not for StoresSummary.aspx*/
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: { 'MessageKey': key },
success: onSucess,
error: OnFailed,
async: false
});
I'm trying to consume Web service developed in ASP .net with html and Java Script/AJAX. But it is not working .
Here is Web Service Method:
[ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
//[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string HelloWorld()
{
String msg = "Hello User";
return new JavaScriptSerializer().Serialize(msg);
}
Here is my html page:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" >
function Logon()
{
$.ajax({
url: "http://localhost:49804/Service1.asmx/HelloWorld",
data: "{}", //ur data to be sent to server
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
success: function (data) {
alert(data);
},
error: function (x, y, z) {
alert(x.responseText +" " +x.status);
}
});
}
</script>
</head>
<body>
<form name="form1" onSubmit="Logon()" autocomplete="on">
username:<input type="text" id="fname"><br>
password: <input type="text" id="lname"><br>
<input type="submit">
</form>
</body>
</html>
Here is my Web service method in browser:
Please ignore username and password fields, I want to use it later.
Is it a problem of Web service? I see SOAP request and response listed in browser page? or its a js problem ?
Thanks
I have this simple code WebForm2.aspx which runs an ajax request to get some data, but when I run this code, I'm getting this error: Too many characters in character literal What is going on?
The output I get is:
cccccccccccccccccccccccccc
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication24.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>FirstAjax</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '/AjaxTest/FirstAjax';
$.ajax({
type: "POST",
url: serviceURL,
data: param = "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Probably your error is here:
$.ajax({
type: "POST",
url: serviceURL,
data: param = "", ///// HERE, try: data: {param:""}, but, I don't know what contains `param`
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
Your problem is wit your data property:
data: param = "",
Use this instead
data: {param: ""},
I'm trying to do the following :
- Call thru JQuery a function on a handler,
- once the treatment is done, redirect to a page.
The issue is that the page does not seems to be load.
I made the following code in order to be clearest.
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication3._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript" src="js/jquery-ui.js"></script>
<script type="text/javascript" src="js/jquery.js""></script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script type="text/javascript" language="javascript">
function CallHandler() {
console.info("Entering CallHandler");
$.ajax({
type: 'POST',
url: "Handlers/MyFunction.ashx",
data: { helloworld: 'hello world'},
success: function (data) {
console.info(data);
}
});
}
</script>
<asp:HyperLink runat="server" ID="linkForTest" onclick='CallHandler();' Text='Click Me' />
</asp:Content>
and my handler is like the following :
/// <summary>
/// Summary description for MyFunction
/// </summary>
public class MyFunction : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write(context.Request["HelloWorld"]);
context.Response.Redirect("~/Login/WebForm1.aspx");
}
public bool IsReusable
{
get
{
return false;
}
}
}
It should called my page "Login/Webform1.aspx", but it calls nothing.
However, Firebug dont seems to find an issue... just it keeps trying to load a page... And failed.
Any ideas ?
I'm pretty sure a redirect in response to an ajax request will not redirect the host page. There are several ways to handle this. One way is you can do a client side redirect in response to some sort of notification or status code from your handler.
it's looping?
is it redirecting even when its on the page its redirecting to?
maybe you need to check the context.Request.Url before redirecting
You're passing the handler helloworld and reading it as HelloWorld see if that's a null reference error? Also, use an error handler on the $.ajax call and see if it is being thrown.
console.info("Entering CallHandler");
$.ajax({
type: 'POST',
url: "Handlers/MyFunction.ashx",
data: { HelloWorld: 'hello world'},
success: function (data) {
console.info(data);
},
error: function (data) {
console.error(data);
}
});
}
when redirecting, the content of the page you want to redirect will be passed as ajax result.
you can call response.redirect another way by client side call using javascript
console.info("Entering CallHandler");
$.ajax({
type: 'POST',
url: "Handlers/MyFunction.ashx",
data: { HelloWorld: 'hello world'},
success: function (data) {
window.location.href ="WebForm1.aspx" ;
},
error: function (data) {
console.error(data);
}
});
}
I have button and that jQuery script (to start the progress bar):
<script src="../_Files/JScripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="../_Files/JScripts/jquery-ui-1.7.2.custom.min.js" type="text/javascript"></script>
var intervalID;
$("#<%=this.Button1.ClientID%>").click(
function() {
intervalID = setInterval(updateProgress, 500);
$.ajax({
type: "POST",
url: "CustomerImport.aspx/ExecuteImport",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function()
{
$("#progressbar").progressbar("value", 100);
clearInterval(intervalID);
$("#result").text('ok');
}
});
return false;
}
);
function updateProgress() {
$.ajax({
type: "POST",
url: "CustomerImport.aspx/GetProgress",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
$("#result").text = msg.d;
var value = $("#progressbar").progressbar("option", "value");
if (value < 100) {
$("#progressbar").progressbar("value", msg.d);
$("#result").text(msg.d);
}
else {
clearInterval(intervalID);
window.location = window.location;
}
}
});
}
the method:
[System.Web.Services.WebMethod]
public void ExecuteImport()
{
_Presenter.ExecuteImport();
}
the problem is, that method is NOT being invoked. Why ?
When I replace the $.ajax for the e.g alert('ok'); the alert shows, so it works
Did you decorate your service class with the [ScriptService] attribute? Also try changing the data parameter to: data: { }. What does FireBug says about this? Is there a request being sent? If yes what does the server respond?
Also you have a mistake in your url (web services have the ASMX extension). You wrote:
CustomerImport.aspx/ExecuteImport
While it should be:
CustomerImport.asmx/ExecuteImport
Here's a complete working example that you may adapt to your needs:
Web service:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService]
public class CustomerImport : WebService
{
[WebMethod]
public void ExecuteImport()
{
}
}
Calling web page:
<%# Page Language="C#" %>
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript" src="scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'POST',
url: '/CustomerImport.asmx/ExecuteImport',
data: { },
success: function () {
alert('ok');
}
});
});
</script>
</head>
<body>
<form runat="server">
</form>
</body>
</html>
Add in the error function to the ajax call... Hopefully you'll get some info back, as to why the call failed.
Are you using firebug? Watch the net tab.
$.ajax({
type: "POST",
url: url,
async: false,
data: jsonEncodedParams,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
}, //success
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (textStatus == "timeout") {
alert('The request timed out, please resubmit');
} //if
else {
alert(errorThrown);
} //else
} //error
}); //ajax
Since your server-side endpoint is a "page method", it must be declared as static:
[System.Web.Services.WebMethod]
public static void ExecuteImport()
{
_Presenter.ExecuteImport();
}