Can anyone please provide me your inputs on how to proceed. the below requirement.
I have web application developed in VS professional 2015 and have separate Web API application. So far the existing web application implemented in 3 layered architecture. Now we wanted to implement the new pages using Web API calls without 3 layered architecture.
First of all, I wanted to create a infrastructure/architecture in my web application to call the web API application. So that all the new page requests go through this infrastructure/architecture and call web API.
Please help me with your valuable inputs/suggestions.
Thank you in advance.
as we are using API there is no need to create a complex infrastructure/architecture unless one is willing to use ReactJs or AngularJs.
Its even not mandatory for them too but it will let you keep the code clean. you just simply need to call the API using JavaScript
For example you've a API controller method and wish to access it.
Simple Method of products
#region Get Method
// GET api/product
[Queryable]
[Route("Products")]
[Route("All")]
public HttpResponseMessage Get()
{
try
{
var products = _productServices.GetAllProducts();
var productEntities = products as List<ProductEntity> ?? products.ToList();
if (productEntities.Any())
{
return Request.CreateResponse(HttpStatusCode.OK, productEntities);
}
throw new ApiDataException(1000,"No Products Found",HttpStatusCode.NotFound);
}
catch (Exception)
{
throw;
}
}
#endregion
just call the respected method from ajax like this
$(document).ready(function () {
var a = "Test";
$.ajax({
url: "v1/products/product/All",
type: "GET",
data: { a : a },
success: function (response) {
alert(response);
},
error: function (response) {
alert(response);
}
});});
Hope This helps
Related
I'm extending a create controller for one of my models:
async create(ctx) {
let entity;
if (ctx.is('multipart')) {
const { data, files } = parseMultipartData(ctx);
entity = await strapi.services.complaint.create(data, { files });
} else {
entity = await strapi.services.complaint.create(ctx.request.body);
}
const sanitized = sanitizeEntity(entity, { model: strapi.models.complaint });
strapi.emitToAllUsers('complaint::created', sanitized);
return sanitized;
},
It works fine if I do the request from Postman for example, but is it possible to do the same if the user creates the new object from the Admin UI?
When I see the console from Strapi when I send the request from Postman:
debug POST /complaints (58 ms) 200
But, if I create a new object from the admin UI I see this instead:
debug POST /content-manager/explorer/application::complaint.complaint (1017 ms) 200
Any ideas? Is it even possible? I'm using latest Strapi version (v3)
Thanks
If you want to execute something from Admin UI, I think you might want to look at how to implement it in models using lifecycle hooks.
https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#models
From what I know, controller only called on API, while service are a set of reusable functions. Models are called both by API and Admin UI.
complaint/models/complaint.js
module.exports = {
lifecycles: {
afterCreate(result, data) {
strapi.emitToAllUsers('complaint::created', result);
}
}
};
You can also create a function in service and call it models lifecycle hooks.
I am new to Angular, and set up a simple example with a REST Api config in Codeigniter that returns a json (default) thread list. No problems!
Until, I add an update to the Database. If I clear/then call getThreads again, I receive the same list of items. A page refresh solves this. I can see in firebug that its only calling the url:api/example/threadlist/id/'x' once per page load.
function ThreadsCtrl($scope, $http, $templateCache) {
$scope.getThreads = function(id) {
if (!id) { id = 'reset'; }
$http({method: 'GET', url: 'api/example/threadlist/id/' + id, cache: $templateCache}).
success(function(data) {
$scope.threadslist = data; //set view model
}).
error(function(data) {
$scope.threadslist = data || "Request failed";
});
};
How would I make it so that it always calls a new list of data rather than reuses the old.
Thanks!
If i understood your question correctly your ajax call is being cached so you have to remove cache:$templatecache from your code
I am developing a RESTful web service using NetBeans, GlassFish server and MySQL as the backend. I want to create a RESTful web service client using JavaScript which will consume all services through it. I already have created a client that implements the GET, POST and DELETE methods. However, I'd like to implement the PUT method in JavaScript.
It's pretty much a matter of changing type specification on the client side - but you may have to write some client or server-side logic (e.g. upper-casing or lower casing before evaluation, as part of your input sanitizing), depending on your support parameters. See the link at the end for more details.
With jQuery:
$.ajax({
url: restfulPutUrl,
type: "PUT"
}).done(function() {
$(this).addClass("done");
});
see jQuery docs, especially:
Other HTTP request methods, such as PUT and DELETE, can also be used [with the type parameter], but they are not supported by all browsers.
Without:
function createXMLHttpRequest() {
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
alert("XMLHttpRequest not supported");
return null;
}
var xhReq = createXMLHttpRequest();
xhReq.open("PUT", "restfulPutUrl", true);
see ajaxpatterns.org if needed
PUT is not implemented uniformly, http://annevankesteren.nl/2007/10/http-method-support for more details.
Investigating the Web API as part of an MVC 4 project as an alternative way to provide an AJAX-based API. I've extended AuthorizeAttribute for the MVC controllers such that, if an AJAX request is detected, a JSON-formatted error is returned. The Web API returns errors as HTML. Here's the AuthorizeAttribute that I'm using with the MVC controllers:
public class AuthorizeAttribute: System.Web.Mvc.AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "area", "" },
{ "controller", "Error" },
{ "action", ( filterContext.HttpContext.Request.IsAjaxRequest() ? "JsonHttp" : "Http" ) },
{ "id", "401" },
});
}
}
How could I reproduce this to provide equivalent functionality for the Web API?
I realize that I need to extend System.Web.Http.AuthorizeAttribute instead of System.Web.Mvc.AuthorizeAttribute but this uses an HttpActionContext rather than an AuthorizationContext and so I'm stuck by my limited knowledge of the Web API and the seemingly incomplete documentation on MSDN.
Am I even correct in thinking that this would be the correct approach?
Would appreciate any guidance.
To get the equivalent functionality in a Web API filter you can set the HttpActionContext.Response property to an instance of HttpResponseMessage that has the right redirect status code and location header:
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) {
var response = new HttpResponseMessage(HttpStatusCode.Redirect);
response.Headers.Location = new Uri("my new location");
actionContext.Response = response;
}
I would very much go with Marcin's answer - at the end of the day, he has written the code!
All I would add is that as Marcin is saying, your best bet is to have a dedicated controller to return the errors as appropriate - rather than setting the response code 401 with JSON content in the attribute.
The main reason is that Web API does the content-negotiation for you and if you want to do it yourself (see if you need to serve JSON or HTML) you lose all that functionality.
I want to make an ajax call inside my jsp file which calls processAction method of a portlet, based on the success message from processAction method i need to make another call to serveResource method of portlet,please provide some examples..
In portlets, processAction() methods are automatically followed by render method and hence ajax response will get embedded with HTML fragment generated by render method. So writing ajax in portlets is a bit tricky.
Have a look at this blog of mine.
http://ajax-and-portlets.blogspot.com/2011/09/ajax-best-practice-in-portlets.html
It gives an insight view of what's the best practice to implement ajax in portlets (for both JSR-168 and JSR-286 portlets).
In case you want sample portlets, you can contact me through the contact details from the blog. I'll be happy to help you.
Thanks
Jignesh
This question worked for me.
Basically, the Controller
#Controller
#RequestMapping("VIEW") // VIEW mapping (as opposed to EDIT)
public class MyPortlet {
#RenderMapping
public String handleRenderRequest(RenderRequest request, RenderResponse response) {
return "defaultRender";
}
#ResourceMapping("myURL")
public void handleMyResource(ResourceRequest request, ResourceResponse response) {
OutputStream outStream;
try {
outStream = response.getPortletOutputStream();
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(outStream, "Hello world!");
} catch (IOException ex) {
// TODO : Do something with errors.
}
}
}
And the JSP:
<portlet:resourceURL id="myURL" var="myURL"/>
<script type="text/javascript">
var urlink = "<%= myURL %>";
$.ajax({
url: urlink,
cache: false,
type: "POST",
success: function(jsondata) {
console.log(jsondata);
}
});
</script>
based on the success message from processAction method
That's not the right way to do it.
On calling portlet action URL in response you get usual render response, so you'll get page with all the portlets.
Instead you should use Portlet 2.0 resource serving feature, and return your response as a resource.
You can check out my portlet which has examples for both serveResource and processAction methods calling.
Ajax Jquery Portlet