Consuming ASP .NET Web service with Java Script JSON - c#

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

Related

Ajax doesn't hit C# on server

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

Map Control form Client Side to Server Side HTML ASP Visual studio 2010

I have some problem about Map control name from client side to server side in HTML in Client side I have control MyTextBox
<body>
<form id="form1" method="get" action="Example2.aspx" >
<div>
<input id="MyTextBox" type="text" />
</div>
</form>
</body>
and i user Jquery post data to server side
$.ajax({
url: "Defaul.aspx/Myfunction",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
// alert(objEmployee);
},
data: '{"ID":"' + ID + '","FirstName":"' + FirstName + '"}',
success: function (msg) {
alert(msg.d);
}
}); // $.ajax
In the server side I want to get control name is "MyTextBox", how can I get it?

jQuery progress bar until save in database asp.net

In an Asp.Net application I need the jQuery progress bar that runs till the data is not saved in database
For this I created a web service and the Ajax jQuery function and the progress bar Javascript plugin
HTML
<div id="progressbar"></div>
<div id="result"></div>
<asp:Label runat="server" ID="lbldisp" Text= "Percentage Completed : "/>
<asp:Label runat="server" ID="lblStatus" />
<asp:Button ID="btnSave" runat="server" Text="Save" class="buttonstyle" />
Script (I am using Sys.Application.add_load instead of document.ready function due to DOM Interruption )
<link type="text/css" href="CSS/ui.all.css" rel="stylesheet" />
<script src="js/jquery-1.8.1.js" type="text/javascript"></script>
<script src="js/ui.core.js" type="text/javascript"></script>
<script src="js/ui.progressbar.js" type="text/javascript"></script>
<script type="text/javascript">
Sys.Application.add_load(function() {
// jquery Progress bar function.
$("#progressbar").progressbar({ value: 0 });
$("#lbldisp").hide();
//button click event
$("#ctl00_ContentPlaceHolder1_btnSave").click(function() {
$("#ctl00_ContentPlaceHolder1_btnSave").attr("disabled", "disabled")
$("#lbldisp").show();
//call back function
var intervalID = setInterval(updateProgress, 250);
$.ajax({
type: "POST",
url: "JobCard.aspx/InsertData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
$("#progressbar").progressbar("value", 100);
$("#lblStatus").hide();
$("#lbldisp").hide();
$("#result").text(msg.d);
clearInterval(intervalID);
}
});
return false;
});
});
function updateProgress() {
var value = $("#progressbar").progressbar("option", "value");
if (value < 100) {
$("#progressbar").progressbar("value", value + 1);
$("#lblStatus").text((value + 1).toString() + "%");
}
}
</script>
Web service
[System.Web.Services.WebMethod]
public static string InsertData()
{
fortest jobcardForm = new fortest();
//this is a line 760 --> jobcardForm.Insert_OilService();
jobcardForm.Insert_TuningService();
jobcardForm.Insert_OtherServices();
jobcardForm.Insert_QRCService();
jobcardForm.Insert_problemTaken();
jobcardForm.Insert_ActionTaken();
jobcardForm.Insert_SpareParts();
//Insert_Technician();
dsJobCardTableAdapters.Select_JobCarRegistrationTableAdapter insertjobcard = new dsJobCardTableAdapters.Select_JobCarRegistrationTableAdapter();
string a = insertjobcard.Insert_JobCarRegistration(
jobcardForm.txtdate.Text, jobcardForm.txtTimeIn.Text,
jobcardForm.txtTimeOut.Text, jobcardForm.Txt_RegNo.Text,
jobcardForm.Txt_FleetNo.Text,
jobcardForm.chkbkdvechle.Checked, jobcardForm.chkwalkin.Checked,
jobcardForm.chkRepeatJob.Checked,
jobcardForm.txtCustomerName.Text, jobcardForm.txtRiderName.Text,
jobcardForm.txtPhoneNo.Text, jobcardForm.txtEmail.Text,
Convert.ToInt32(jobcardForm.ddl_ServiceAdvisor.SelectedValue),
Convert.ToInt32((jobcardForm.ListBox1.SelectedValue == "" ? "0" : jobcardForm.ListBox1.SelectedValue)),
jobcardForm.ddl_Model.SelectedValue,
jobcardForm.ddl_type.SelectedValue, jobcardForm.txtKMSRUN.Text,
jobcardForm.ddl_color.SelectedValue
, "1", HttpContext.Current.Session["user_id"].ToString(),
jobcardForm.txtdateout.Text, jobcardForm.txtchassis.Text,
jobcardForm.ddlyear.SelectedValue, jobcardForm.txtexpirydate.Text,
jobcardForm.txtnotes.Text,
jobcardForm.ddllocation.SelectedValue).ToString();
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.RawUrl);
return "Save Completed...";
}
Looks like the script is working fine but I am getting an error in the web browser console Window and the error is "500 Internal Server Error" at line 760 in web service jobcardForm.Insert_OilService();. But when I use the web service code in server side onclick event the data is inserted into the database. I need the progress bar, that's why I have to change the logic using web service
ERROR
I normally create an object of a class to use it in a static method and this was the simplest way to use a non-static method in a static method.
Why dont you do something like this:
function FunctionName() {
$.ajax({
type: "POST",
url: ,
data: JSON.stringify(),
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
$("#progress-bar").show();
$("#progress-bar1").hide();
},
complete: function () {
$("#progress-bar").hide();
$("#progress-bar1").show();
},
success: function () {
}
});
}
And have 2 div
<div class="gap"></div>
<div id="progress-bar" style="display:none;">
<img src="~/Images/ajax-progressbar.gif" />
</div>
<div id="progress-bar1"></div>
</div>
So before you send your request you show $("#progress-bar").show(); once once the content loaded you hide it. Hope this answer your question.

Problems with jquery and C# web service

Output from web service, "http://localhost:6833/Service1.asmx/HelloWorld":
<string xmlns="http://tempuri.org/">
[{"Name":"Pini","Age":"30","ID":"111"},{"Name":"Yaniv","Age":"31","ID":"Cohen"},{"Name":"Yoni","Age":"20","ID":"Biton"}]
</string>
HTML code:
<html>
<head>
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: "Service1.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert("Result: " + msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus);
}
});
});
</script>
</head>
<body>
</body>
</html>
When i run index.html in browser i get the Error alert.. Tried alot of things, but cant find out whats missing..
your json in encapsulated in a xml string, i guess thats your problem.
EDIT:
check this post for more information.
Try adding this before your method.
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
below
[WebMethod]

ASP.NET a problem with jQuery's ajax function

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

Categories