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

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

Related

Web API session managment

My requirements - I have a web api whch gives me all data from db. I have a .net website which consumes this api to get all data. Now what I want is when I'm login my website I want to manage session in "API".
I know session in web api is not a good approach but still I need to do this.
I have already implemented session management in web api(taken reference from here) and its working fine if I'm sending all my request from postman(i.e. I'm setting variables in session by calling 1 method and retrieving that session variable by calling 2nd method). But when I'm doing the same from asp.net website with jQuery then I'm not getting stored session variable(what I noticed is I'm getting session id different every time-for each request).
code of saving variable in session
$.ajax({
url: 'http://localhost:63726/api/Login/Login',
type: "GET",
dataType: "JSON",
success: function (data) {
alert("success");
},
error: function (data) {
alert("error");
}
});
code of retrieving variable stored in session
$.ajax({
url: 'http://localhost:63726/api/SessionCheck/LoginName',
type: "GET",
dataType: "JSON",
success: function (data) {
alert("success");
},
error: function (data) {
alert("error");
}
});
What I need to do to achieve my goal..Your opinion will save my days...
I found my answer Session management in web api.
Please, read this Web Api Session storage before.
To retreive data from session use javascript sessionStorage (instead ajax).

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

AJAX POST JSON to .NET Webservice gives 500 Internal Server Error

I am trying to consume a .NET webservice with AJAX and want a JSON response. Everything works fine. I have used fiddler and get the appropriate Json returnet. also using the plain URL in the browser gives the appropriate XML.
Even using PHP Curl gives me the right JSON in response but when i am trying to use AJAX i get a "500 Internal Server Error".
Any help appriciated, Thanks.
<script>
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://localhost:9000/APIs/BuyVoucherService.asmx/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data);
},
error: function(data){
alert(data);
}
});
});
</script>
It seems that you have omitted a data definition in your request, try to add something like this:
data: "{}",
The problem i have realized is that this wont work because of cross domian issues. the solution to get the AJAX call to work with a cross domain solution is to use JSONP. http://www.json-p.org/

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",

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

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.

Resources