How to use jQuery to call an ASP.NET web service? - asp.net

I'm trying to use jQuery to get data from an ASP.NET web service (SharePoint Server 2007 lists.asmx), but any call to a web service will really help as a first step in that direction.

I use this method as a wrapper so that I can send parameters. Also using the variables in the top of the method allows it to be minimized at a higher ratio and allows for some code reuse if making multiple similar calls.
function InfoByDate(sDate, eDate){
var divToBeWorkedOn = "#AjaxPlaceHolder";
var webMethod = "http://MyWebService/Web.asmx/GetInfoByDates";
var parameters = "{'sDate':'" + sDate + "','eDate':'" + eDate + "'}";
$.ajax({
type: "POST",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$(divToBeWorkedOn).html(msg.d);
},
error: function(e){
$(divToBeWorkedOn).html("Unavailable");
}
});
}
Please note that this requires the 3.5 framework to expose JSON webmethods that can be consumed in this manner.

Here is an example to call your webservice using jQuery.get:
$.get("http://domain.com/webservice.asmx", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
In the example above, we call "webservice.asmx", passing two parameters: name and time. Then, getting the service output in the call back function.

I don't know about that specific SharePoint web service, but you can decorate a page method or a web service with <WebMethod()> (in VB.NET) to ensure that it serializes to JSON. You can probably just wrap the method that webservice.asmx uses internally, in your own web service.
Dave Ward has a nice walkthrough on this.

$.ajax({
type: 'POST',
url: 'data.asmx/getText',
data: {'argInput' : 'input arg(s)'},
complete: function(xData, status) {
$('#txt').html($(xData.responseXML).text()); // result
}
});

SPServices is a jQuery library which abstracts SharePoint's Web Services and makes them easier to use
It is certified for SharePoint 2007
The list of supported operations for Lists.asmx could be found here
Example
In this example, we're grabbing all of the items in the Announcements list and displaying the Titles in a bulleted list in the tasksUL div:
<script type="text/javascript" src="filelink/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="filelink/jquery.SPServices-0.6.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$().SPServices({
operation: "GetListItems",
async: false,
listName: "Announcements",
CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",
completefunc: function (xData, Status) {
$(xData.responseXML).SPFilterNode("z:row").each(function() {
var liHtml = "<li>" + $(this).attr("ows_Title") + "</li>";
$("#tasksUL").append(liHtml);
});
}
});
});
</script>
<ul id="tasksUL"/>

I have a decent example in jQuery AJAX and ASMX on using the jQuery AJAX call with asmx web services...
There is a line of code to uncommment in order to have it return JSON.

I quite often use ajaxpro along with jQuery. ajaxpro lets me call .NET functions from JavaScript and I use jQuery for the rest.

Related

How to call server api decorated with ValidateAntiForgeryToken using Httpclientfactory Typed clients?

I am trying to incorporate a Edit Form page using GetAsync and PostAsync using typed httpclient. Everything works except my code doesn't call API actions with ValidateAntiForgeryToken. Most of the examples online do not address httpcontent used by httpclientfactory and instead use httpresponse. I am aware that the antiforgery token is missing on my request. How do I attach it to the request header? How do I retrieve it from the view? I want to use as less Javascript as possible. Here's a snippet of my Post request service.
Edit: For what it's worth, my api is dot net core and client is dot net core mvc.
var response = await _httpclient.PostAsync("api/edit/" + id, httpcontent);
response.EnsureSuccessStatusCode(); ```
In the MVC Edit view page, it will use a hidden file (named __RequestVerificationToken) to store the ValidateAntiForgeryToken, you can use F12 developer tools to check it.
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8NrAkS ... s2-m9Yw">
After modifying the data, you could use JQuery to get the updated data, then use JQuery ajax to call the API method with the ValidateAntiForgeryToken. You can refer the sample code in my reply:
if we customize antiforgery options in Startup.ConfigureServices, such as: custom the Header Name for the RequestVerificationToken.
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN"); //configure the antiforgery service to look for the X-CSRF-TOKEN header. To prevent the cross-site request forgery.
Then, we could use the following script:
$.ajax({
type: "POST",
url: "/Survey/Create",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { "CategoryName": $("#CategoryName").val(), "CategoryID": $("#CategoryID").val() },
success: function (response) {
alert(response);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
Besides, you can also refer Prevent Cross-Site Request Forgery (XSRF/CSRF) attacks in ASP.NET Core.

How do I do an AJAX post to a url within a class library but not the same IIS Web Application?

I have been working with ajax and there has been no problems below is how my ajax post code look like:
$.ajax({
type: "POST",
url: '<%=ResolveUrl("TodoService.asmx/CreateNewToDo")%>',
data: jsonData,
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function () {
//if (msg.d) {
$('#ContentPlaceHolder1_useridHiddenField').val("");
$('#ContentPlaceHolder1_titleTextBox').val("");
$('#ContentPlaceHolder1_destTextBox').val("");
$('#ContentPlaceHolder1_duedateTextBox').val("");
alert('Your todo has been saved');
// }
},
error: function (msg) {
alert('There was an error processing your request');
}
});
However, the problem came up when I try to get the url to a webservice that is located in a class library within the same solution.
This ASP.Net
says If you want to put the webservice in the classlibrary, you could try placing the Webservice.asmx.cs file in the class library and place the Webservice.asmx file in the web application project, and then using jquery to consume it in the .aspx page
If it's a different application than yours that's considered an XSS (Cross-site scripting) and it is not allowed.
You could however wrap the call to the external service in your own application (let's say in a REST service) and just call your service from jquery

JSON Web service with ASP.NET - from a frustrated php guy

I've been a PHP developer for a few years now and have developed at least a dozen APIs using JSON. Create a url that does a task, and return json_encode($array)... Piece of cake...right?
Now, I used to be a .net developer a while back (about 8 yrs ago) and I've been given the task to develop a small api/webservice for a client. I've been doing some reading on WCF and have been tinkering with it for a few hours now. My question is.. Is it me or is it incredibly over complicated to just run a RESTFUL query and return a block of JSON? In other words, why can't I just create an ASPX page that takes an array and encodes it as JSON and spits it out? Does it really HAVE to be WCF? Or even ASMX for that matter? Feels like overkill? No? Can someone offer a valid reson on why I need to go through the pain of WCF if I'm making a simple service that returns a few lines of JSON?
You can use WebMethods:
Using jQuery to directly call ASP.NET AJAX page methods
Code-behind:
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
Script:
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// alert(msg.d);
}
});

Access Session data from ASP.NET page using jquery

I'm trying to pass a variable stored in the Session object of my ASP.NET page with jQuery, representing the progress of a process running on the server as a percentage.
i.e:
Session['progress'] = 37;
I've looked through some of the answers here; my code uses the same method as a question aswered correctly here:
<head>
...
<script type="text/javascript">
function updateProgress() {
var progress = '<%Session["progress"].ToString();%>';
}
</script>
...
</head>
The ASP.NET compiler is returning a NullPointerException. I'm unsure if this is because the Session object hasn't been instantiated yet (as this is occurring at compile time); or perhaps the Session object isn't receiving the variable properly (if this is the case, how can I go about checking this out?)
Any ideas?
I need to find some way off passing this value from the server to the client so a jQuery progress bar may be updated for the user.
Thanks!
If you want to get a real-time changing number from a session variable in your page using jQuery, you'll need to make some type of ajax request. To access a value in the session state, you can write a function [WebMethod] to send gets/send the data back to your jQuery request.
jQuery Request :
jQuery.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{}',
dataType: 'json',
url: 'Default .aspx/TestMethod',
success: function(result){
alert(result.d);
}
});
Server Page WebMethod :
using System;
using System.Web.Services;
namespace JqueryAjaxText
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string TestMethod()
{
return Session["progress"].ToString();
}
}
}
I think you are misunderstanding the order in which things occur. While SageNS found your error, he did not solve your problem.
The code you have simply writes a number to the javascript code, and the user sees:
<head>
...
<script type="text/javascript">
function updateProgress() {
var progress = '37';
}
</script>
...
</head>
Successive calls to updateProgress() will always return 37.
You need to use jQuery's .ajax() function to make an asynchronous call to the server if you want to periodically update the server's progress.
You can build off Zachary's answer and take it a step further by creating a WCF service and switching your $.ajax() call to be a GET instead of a POST. It won't be as large of a request (not that the POST was that big), but you'll also be using the proper HTTP verb. (POST is used to insert; GET should be used to retrieve data).
Your jQuery call could look like this:
jQuery.ajax({
type: 'GET',
dataType: 'json',
url: 'MyService.svc/GetServerProgress',
success: function(result){
alert(result.d);
});
You would then create a WCF Service and create a service method named GetServerProgress.
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetServerProgress")]
public int GetServerProgress()
{
return 37;
}
Lastly, you'll probably want the client to have some JavaScript that calls setTimeout() to your $.ajax() method to that you periodically retrieve the server's progress from the WCF service.
Good luck!!
Use
<%=Session["progress"].ToString()%>
to output data to html page

Does authentication/authorization stop Jquery from calling a page method?

I have the following JQuery code that worked perfect in C#/Asp.net 2.0 to call a page method in the default.aspx page. Now I am trying to call a shared page method in VB.Net and the page method is not firing, I believe because of security or it is not finding it.
The page that this shared vb method is in doesn't allow anonymous access, so I was thinking that is the problem or it is a path problem to finding the method. I am just guessing here. In my C# test app the static webmethod was in the default.aspx page with no security. Thanks for any advice or help!
$.ajax({
type: "POST",
url: "Orders.aspx/GetMailPieceGroupsByAdFundTypeId",
data: myDataToSend,
contentType: "application/json; charset=utf-8",
dataType: "json",
//error: function(XMLHttpRequest, textStatus, errorThrown) {alert(errorThrown); this;},
success: function(data, textStatus){alert(success);mailPieceGroups = eval('(' + data + ')'); startSlideShow(mailPieceGroups); }
});
My issue was the path provided was not correct which caused the .ajax call not to be able to locate the method to call it.
This is correct for my scenario:
url: "../Orders.aspx/GetMailPieceGroupsByAdFundTypeId",

Resources