I'm trying to run an AJAX Webservice request on a VB ASP.NET page.
When the page loads, I'm trying to call the webservice but I get a 500 error in the console.
My WebService file looks like this:
<System.Web.Script.Services.ScriptService()>
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")>
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)>
<ToolboxItem(False)>
Public Class usrDataSave
Inherits System.Web.Services.WebService
<WebMethod()>
Public Function saydata(abc As String)
MsgBox(abc)
Return abc
End Function
My ASP.NET page looks like this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "usrDataSave.asmx/saydata",
data: "hello_world",
contentType: "application/json",
datatype: "json",
success: function(responseFromServer) {
alert(responseFromServer.d)
}
});
});
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
I expect the page to load and a message box to popup server side that says 'hello_world' as well as the web browser to create a popup that says the same. However, this does not happen as I get a 500 error instead.
I've tried to fix this by using different versions of jQuery as well as enabling requests in the web.config file like this:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
This doesn't work and I still get that "the server responded with a status of 500" in the web browser console. No errors are logged within the application's debug console.
How can I fix this?
Ok, assuming both pages are in the SAME folder - at the same level?
Then this should work:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: usrDataSave.asmx/saydata
data: "{abc: 'hello_world'}",
contentType: "application/json",
datatype: "json",
success: function (responseFromServer) {
alert(responseFromServer.d)
}
});
});
</script>
Note how your data has to match your parmaters..
So, say you have this:
<WebMethod()>
Public Function saydata(abc As String, def as string) as string
MsgBox(abc)
Return abc & " " & def
End Function
And note how we set the function as string - you should give the function a type - in this case "string".
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "WebService1.asmx/saydata",
data: "{abc: 'hello', def: 'world'}",
contentType: "application/json",
datatype: "json",
success: function (responseFromServer) {
alert(responseFromServer.d)
}
});
});
</script>
Edit:
Follow up question was how to return more then one value?
Well, the easy way? Create a structure or class - let the built in serialization convert that to a json string for you.
So our web method could say be this:
Structure Hotel
Dim FirstName As String
Dim LastName As String
Dim HotelName As String
End Structure
<WebMethod()>
Public Function GetHotel() As Hotel
Dim MyHotel As New Hotel
MyHotel.FirstName = "Albert"
MyHotel.LastName = "Kallal"
MyHotel.HotelName = "Banff Springs Hotel"
Return MyHotel
End Function
I often use a struct in place of a class - since then I just shove it in right before my web method as per above.
Now, lets drop in a button on the page - and js function to call this:
eg:
<asp:Button ID="cmdHotel" runat="server" Text="Get Hotel"
OnClientClick="GetHotel();return false;" />
<script>
function GetHotel() {
$.ajax({
type: "POST",
url: "WebService1.asmx/GetHotel",
data: "{}",
contentType: "application/json",
datatype: "json",
success: function (r) {
s = "FirstName = " + r.d.FirstName + "\n"
s = s + "LastName = " + r.d.LastName + "\n"
s = s + "Hotel Name = " + r.d.HotelName
alert(s)
}
});
}
And when we run, we get/see this:
So, you can often just return a simple string. But, if you create a structure server side, then you can quite much reference the result client side as a js object as per above.
Related
I do have two page. One is Default.aspx and another one is DetailView.aspx. What I want to do is that I want to redirect page from Default.aspx to detailView.aspx using ajax call and I want to pass one value also. I have done something but it is not calling function that is defined into class.
I am calling this function from Default.aspx webfile
$.ajax({
type: 'POST',
url: 'DetailView.aspx/Test',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{pid:' + result + '}',
success: function (data) {
}
});
this is class file of DetailView.aspx
[WebMethod(EnableSession = true)]
public static string Test(string pid)
{
return " ";
}
I was debugging this function but it is not calling this function at all when ajax being called.
You want to convert a JavaScript value to a JSON using JSON.stringify() before posting data.
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoWebForm.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<button type="button" onclick="ajaxPostData();">Post Data to Detail View</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function ajaxPostData() {
var data = { pid: "One" };
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/DetailView.aspx/Test") %>',
data: JSON.stringify(data),
contentType: "application/json",
success: function (msg) {
console.log(msg.d);
}
});
}
</script>
</form>
</body>
</html>
DetailView.aspx.cs
using System.Web.Services;
namespace DemoWebForm
{
public partial class DetailView : System.Web.UI.Page
{
[WebMethod(EnableSession = true)]
public static string Test(string pid)
{
return "Hello " + pid;
}
}
}
From your ajax Method Declaration i.e
URl Part in your Ajax Calling this one :
url: 'DetailView.aspx/Test'
I'm assuming that Your are Using the FriendlyURL .
So in your RouteConfig.cs please comment this line
settings.AutoRedirectMode = RedirectMode.Permanent;
You can send params to your Ajax as follows
var params = "{'pid:' " + result + "}";
Replace that variable in your AJax calling as follows
data: params
Make sure that you have enabled ajax call in the webservice, to do so add this line before defining the webservice class
[System.Web.Script.Services.ScriptService()]
Hello there I am totally new to ASP.NET and learning it to my own. I am good at Java J2EE (Struts2 Framework)! I know how can i update or change any control/text inside any div element using struts2 and ajax code.
My Problem
Actaully, I'm trying to do the same thing in ASP.NET just for the learning! Suppose that I have a Default.aspx page with the javascript and ajax methods as:
<head runat="server">
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script type="text/javascript">
function Change() {
$.ajax({
type: "GET",
url: "temp.aspx",
dataType: "text/html;charset=utf-8",
success: function(msg) {
$("#changer").html(msg);
}
});
}
</script>
<title>Untitled Page</title>
</head>
<body>
<div id="changer">//this is the div i want to update it using ajax
Hello Old Text
</div>
<input type="button"id="but" value="Hello Changer" onclick="Change()"/>
</body>
and suppose that I have my temp.aspx as:
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<div id="changer">
Hello New Text
</div>
</body>
I just want to know if this is possible in ASP.NET because with Java I am familiar with such an operation but I don't know why this is not working in case of ASP.NET!
Any hints or clues are favorable for me, Please don't mind for my question because I am totally new to ASP.NET but I am good at Java
Thanks in Advance!
dataType must define as html like this;
function Change() {
$.ajax({
type: "GET",
url: "temp.aspx",
dataType: "html",
success: function(msg) {
$("#changer").html(msg);
}
});
}
From jQuery Docs;
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
Additionally, you can inspect errors using error.
function Change() {
$.ajax({
type: "GET",
url: "temp.aspx",
dataType: "html",
success: function(msg) {
$("#changer").html(msg);
},
error: function(xhr, status, err) {
console.error(status, err.toString());
}
});
}
This is not related to ASP.NET or other web frameworks. It is just related to jQuery and Javascript. jQuery didn't recognise this "text/html;charset=utf-8". If you didn't use dataType, the ajax request worked successfully. It is just verification and result is interpreted according to dataType. For example, you are returning a JSON and the mime type of the your endpoint is not json (considering its mime type is html) just changing of the dataType as "JSON" you can parse the result as object.
I wrote a little script, in first example, I set dataType as HTML and in other example, I set dataType as JSON.
You could add a generec handler called Temp.ashx wich return the new text.
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello New Text");
}
In your ajax call you need to specify you are expecting a text.
<script type="text/javascript">
function Change() {
$.ajax({
type: "GET",
url: "temp.ashx",
dataType: "text/plain",
success: function(msg) {
$("#changer").html(msg);
}
});
}
</script>
I need to send a script to the page from WebMethod used by Ajax that fires when click HTML link. I couldn't use the script manager with "Me" or "Page" control and can't reference any controls.
I just need to return that session is nothing , Any Ideas?
The button clicked to send Ajax is HTML link and all I need to check if session expired (which I can check it on load) so if it's expired want to alert user since I already don't complete the process after checking it in code behind
<WebMethod()> _
Public Shared Function Send(ByVal data As String) As String
If Not System.Web.HttpContext.Current.Session("MemberID") Is Nothing Then
Try
''''' my code
''''''''''''''''''''''
If Not System.Web.HttpContext.Current.Session("MemberID") Is Nothing Then
Return "Success"
Else
Return "noSession"
End If
Catch ex As Exception
Return "failure"
End Try
Else
ScriptManager.RegisterStartupScript(Me, GetType(String), "Checkeng", [String].Format("LevelsMsg();"), True)
End If
End Function
JQuery Ajax
It's more complecated but I thinkk this is the main part:
$(document).on("click", "#Add", function() {
var _fulldata = $('#basket').html();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Order.aspx/SendOrder',
data: "{'fulldata':'" + _fulldata + "'}",
async: false,
success: function(response) {
},
error: function() {
alert("There is a problem in saving data");
}
});
});
Your WebMethodis a Shared function which is equivalent to a Static function in C#. This means you will not be able to access any variables other than those declared inside of this Shared function. However, the nature of WebMethods allow a return to "its" caller via "Success" or "error" which can be "intercepted". Thus, no need to use ScriptManager.RegisterStartupScript since your POST will return to AJAX realm anyway, which means you can call any JavaScript function there.
You could Change your code this way:
VB.NET Code-Behind:
<WebMethod()> _
Public Shared Function Send(ByVal data As String) As String
If Not System.Web.HttpContext.Current.Session("MemberID") Is Nothing Then
Try
' YOUR CODE
Return "Success"
Catch ex As Exception
Return "Failure"
End Try
Else
Return "NoSession";
End If
End Function
JavaScript:
$(document).on("click", "#Add", function() {
var _fulldata = $('#basket').html();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Order.aspx/SendOrder',
data: "{'fulldata':'" + _fulldata + "'}",
async: false,
success: function(response) {
/* since we put "NoSession", then we should check for it here */
if(response.d == "NoSession") {
/* This is where you "replace" the use of RegisterStartupScript
by safely calling any JS function here */
LevelsMsg();
}
},
error: function() {
alert("There is a problem in saving data");
}
});
});
I have a page (default.aspx) with codebehind. The a$.ajax url is getting a response from one place, and on its success I want to call the codebehind function.
(In case I made a mistake while obfuscating the code, the $.ajax works perfectly and I get the desired response).
How is this possible?
Code I'm using:
jQuery.support.cors = true; // force cross-site scripting (as of jQuery 1.5)
$.ajax({
type: "POST",
url: URL,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var resultCount = response.d
alert("*** RESULT ****" + resultFields);;
var string = StringReturn(); // the codebehind
alert(string);
},
error: function (e) {
alert("Unavailable");
}
});
Codebehind:
[WebMethod]
protected static string StringReturn()
{
return "StringReturn() success";
}
However, I'm getting error messages saying that StringReturn isn't a valid function.
Any help would be appreciated?
I've added the following lines of code to the page as advised:
<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"> </asp:ScriptManager>
I've also changed the code to call a javascript function on the Success event, the function being:
function HelloWorlds() {
alert("HelloWorld() method");
message = PageMethods.StringReturn();
message.toString();
alert(message);
}
however that doesn't appear to work. What am I missing?
You need to have a scripmanager on your page and then you can call it like this PageMethods.StringReturn()
I'm trying to implement voting very similar to Stack Overflow's. There are multiple items that all have a vote button next to it. Currently, I have it working, but it's done server side, posts back, and takes a while to reload the data. Here is the flow:
You click the vote button,
it fires a javascript function which clicks a hidden ASP.NET button (did it this way because there are multiple vote buttons per page),
the button fires,
it updates the database, and then
the page posts back and refreshes, showing the update.
How do I leverage javascript and AJAX to eliminate this bad user experience? I want it to work like Stack Overflow's, but I'm not using MVC. Any help, examples, suggestions would be great. Thanks.
Update:
I have this implemented, but when I place breakpoints on the Web Method it doesn't even fire and I always get the error alert. Any ideas?
javascript:
<script type="text/javascript">
$(document).ready(function () {
$("[id^=VoteMeUp]").click(function (event) {
var dta = '{ "VoteId":' + $(event.target).val() + '}';
$.ajax(
{
type: 'POST',
data: dta,
url: 'Default.aspx/SaveUpVote',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//$(event.target).text("Vote Casted");
alert("Vote Casted");
},
error: function (x, y, z) {
alert("Oops. An error occured. Vote not casted! Please try again later.");
}
}
);
});
});
</script>
Code Behind (you can use C#, I'm familiar with both):
Imports System.Web.Services
Imports System.Web.Script.Services
<WebMethod()>
Public Shared Function SaveUpVote(ByVal VoteID As Integer) As Boolean
Dim test As Boolean = False
Dim mySQL As New SQLHandler
test = mySQL.UpdateVoteByID(VoteID)
Return test
End Function
HTML:
<input type="image" src="images/vote.png" id="VoteMeUp1" value="321" />
When a vote is cast for a given button, call the server method using ajax (for aspx) as follows:
$(document).ready(function() {
$("[id^=VoteMeUp]").click(function(event) {
var dta = '{ "VoteId":' + $(event.target).val() + '}';
$.ajax(
{
type: 'POST',
data: dta,
url: 'Default.aspx/SaveUpVote',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$(event.target).text("Vote Casted");
},
error: function(x, y, z) {
alert("Oops. An error occured. Vote not casted! Please try again later.");
}
}
);
});
});
In Default.aspx.cs
[WebMethod]
public static void SaveUpVote(int VoteId)
{
string UpdateSQL = "UPDATE TableName SET Votes = Votes + 1 WHERE PKID = #VoteId";
//do DB stuff
return;
}
Sample HTML:
...
<body>
<button id="VoteMeUp1" value="817">1 - Vote for this</button>
<button id="VoteMeUp2" value="818">2 - Vote for that</button>
</body>
...
the easiest method to do this would be WebMethods.
Add a ScriptManager to your page with EnablePageMethods set to true
aspx page:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
Assign a web method attribute to the method which increments the votes in your (c# here) code behind:
c# code behind:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string ChangeVote(string Arg){
...logic to change votes
}
in your javascript event, you can then access the code behind via pagemethods, and define functions to call on success and fail cases:
javascript:
PageMethods.ChangeVote("sent item", OnChangeVoteComplete,OnChangeVoteFail);
function OnChangeVoteComplete(arg){
//arg is the returned data
}
function OnChangeVoteFail(arg){
//do something if it failed
}
the success function receives the data returned by the WebMethod. You can use this to update the display on the page.
When use clicks on the UpVote button, make an ajax call to the server where you execute a query againist the database to increment the vote.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>
Vote UP
</body>
<script type="text/javascript">
$(function(){
$("#aUpVote").click(function(){
$.post("myajaxserverpage.aspx?qid=12",function(data){
alert(data);
});
});
});
</script>
</head>
and in the server page (myajaxsever.aspx), read the values and execute your query to increment the Vote column value. value of qid is the question id this you can read from the page because it is going to be dynamic.