i am really new to the REST world, or in fact the WebApp side of java, so please don't mind if it's a silly question.
I have a web page where pressing a button will call the following JS function:
function testFunction(){
$(document).ready(function() {
$.ajax({
url: "http://localhost:8080/test/webapi/myresource",
type: 'get',
success: function (data) {
console.log(data)
}
});
});
}
where the above url is handled by my OWN web service(which is in java), that is the above GET will call the following Web Service:
#Path("myresource")
public class MyResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it!";
}}
All i wanna do here is instead of returning "Got It", i wanna call another javascript function(dedicated to handle server kind of request) involving EXTERNAL rest call such as this:
function externalResource() {
$(document).ready(function() {
$.ajax({
url: "any_external_rest_call",
type: 'get',
dataType: 'json',
success: function (data) {
document.getElementById('demo').innerHTML = "Perfect"
}
});
});
}
where i wanna return the data from the externalResource function to getIt() to finally the testFuntion(), i know its possible, but couldn't find much of the details online. It would be really helpful if someone could clear this up to me.
You cannot call JavaScript code from your REST method in Java. However, you can use the ClientBuilder of the javax.ws.rs.client package.
Your method could look like this:
#Path("myresource")
public class MyResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() {
client = ClientBuilder.newClient();
target = client.target("http://api.anotherRestService.com/details/")
return target.request(MediaType.APPLICATION_JSON)
.get();
}
}
This is just an example, I didn't try it in a real environment, but this is how you can do it. Now, you can call with your JS method testFunction the REST method of your Java backend. In you REST method getIt you call another rest service with the created client. The result of the second rest call is returned to your JS method testFunction.
Take a look at his: RestTemplate. This is Spring, however. Seeing as you are using JAX-RS maybe take a look at this: Jersey.
The flow you describe is not possible, it is however possible to chain several requests while using data from the response of the previous response:
$(document).ready(function() {
$.ajax({
url: "http://localhost:8080/test/webapi/myresource1",
type: 'get',
success: function (data) {
$.ajax({
url: "http://localhost:8080/test/webapi/myresource2?id="+data.id,
type: 'get',
success: function (data) {
console.log(data)
}
});
}
});
});
If you wish to call another URL from your server, its a redirect call. Following would be an example server side code if you are using Spring framework.
#RequestMapping("/to-be-redirected")
public RedirectView localRedirect() {
RedirectView redirectView = new RedirectView();
redirectView.setUrl("http://www.google.com");
return redirectView;
}
As others have mentioned, you can also use Spring RestTemplate to do this.
Related
I tried to call c# function in javascript so i used this: var a = <%=MYC#FUNCTION()%>, but the function in the weird brackets execute even before my page load. like executing the function is the top priority of my code.
i want the function to execute when i am calling it in my javascript code.
Please help me, i need this for my project in school.
i tried to use this but i didnt really understood this ->
<script type="text/javascript"> //Default.aspx
function DeleteKartItems() {
$.ajax({
type: "POST",
url: 'Default.aspx/DeleteItem',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
</script>
[WebMethod] //Default.aspx.cs
public static void DeleteItem()
{
//Your Logic
}
You are misunderstanding the life cycle of the request/response. In your code, the order of execution will be
Web browser sends a request to your web server.
Web server (C# code) now handles the request and start creating HTML response.
Web server uses your controller/view (MVC) or .aspx/.aspx.cs (web form) to create the response.
Your code "MYC#FUNCTION()" is now executed. Let assume it returns a number 123.
After this, your html response is sent back to web browser.
Web browser receives the response and display to UI. Now, if you inspect HTML you will see "var a = 123;" (123 coming from your "MYC#FUNCTION()")
If you want to execute "MYC#FUNCTION()" after page load. Then you need to look at AJAX.
I have a C# Project, and a ASP.NET project (without database).
I want to call some methods from my C# Project, get the results in JSON and use it in my javascript without using the [WebMethod], I tried to make a Controller but I'm a little bit lost.
If you have any tips it would be nice, thank you.
The code in the controller should look like:
public class HomeController : Controller
{
[...]
public virtual ActionResult GetExample()
{
[...]
var result = ...;
return Json(result, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public virtual ActionResult Update(MyModel model)
{
[...]
var result = model
return Json(result);
}
[...]
}
And from your java script file you make an ajax call:
$.ajax({
url: "<path>/Home/GetExample",
type: "GET",
dataType: "json",
cache: false,
success: function (html) {
[...]
}
})
or:
$.ajax({
url: "<path>/Home/Update",
type: "POST",
dataType: "json",
data: $(#my-form).serialize(),
cache: false,
success: function (html) {
[...]
}
})
I don't have enough reputation so adding my comments here. You probably want to use Web Api here which is the reason you created controller. You probably need to refer Web Api site which will help you build controllers and expose interface to be called from javascript.
Web API
I'm trying to make a simple jquery ajax call to a WEB API method.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
url: 'http://redrock.com:6606/api/values/get',
dataType: "jsonp",
crossDomain: true,
success: function (msg) {
alert("success");
},
error: function (request, status, error) {
alert(error);
}
});
});
</script>
WEB API action:
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
ajax call does not hitting the WEB API. I get the below error in browser console.
GET http://redrock.com:6606/api/values/get?callback=jQuery18207315279033500701_1383300951840&_=1383300951850 400 (Bad Request)
Unless you are doing a cross domain call, there is no need to use jsonp (jsonp also requires a custom formatter in Web API).
$.getJSON('http://redrock.com:6606/api/values', function(data){
console.log(data);
});
EDIT:
To install a jsonp media type formatter, have a look at this project: https://github.com/WebApiContrib/WebApiContrib.Formatting.Jsonp
Download the formatter using nuget
Register the formatter
Update your routeconfig
You haven't included the code for the route setup, but assuming it is correct, the problem is probably caused by the fact that you have named you WebApi method 'Get' while you are trying to hit it using a POST request. This happens because WebApi tries to figure out the HTTP verb from the action name.
I would suggest either renaming the action or adding the [HttpPost] attribute to your action method. You may also try the WebApiRouteDebugger package.
Earlier today I posted another post where #Darin Dimitrov helped me great, however once again I'm stucked...
My javascript calls the AddWebsite ActionResult which does it job as it should, however the error function in the $.ajax() is always firing since
return PartialView(ListPartialView, MapUserToViewModel);
isn't valid JSON.
I've come across examples where people use something like
RenderPartialViewToString(partialview, model);
and throws it into a JSON object... but it's just too "hackish" if you ask me.. isn't there an easier way to accomplish this?
... And the code:
// DashboardController.cs
[HttpPost]
public ActionResult AddWebsite(CreateWebsiteViewModel website)
{
if (!ModelState.IsValid)
{
throw new HttpException(400, "Client-side validation failed.");
}
if (string.IsNullOrWhiteSpace(website.URL))
{
throw new ArgumentNullException("URL", "The URL cannot be empty nor contain only whitespaces.");
}
using (_session.BeginTransaction())
{
_session.Query(new AddWebsite(_contextProvider.GetUserSession.UserId, website.URL));
_session.Transaction.Commit();
}
return PartialView(ListPartialView, MapUserToViewModel);
}
// MyJs.js
$("#testform").live('submit', function () {
var test = { URL: $("#URL").val() };
$.ajax({
url: "/Dashboard/AddWebsite",
type: "POST",
data: JSON.stringify(test),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("TRIG");
$("#content").html(data);
},
error: function () {
alert("Error");
}
});
return false;
});
Thanks in advance!
In your particular instance I think the problem is with your javascript code. You are specifying the dataType (which is what the function expects to parse in the response) as json. Based on the Action you posted you should have html as the dataType and it should solve your problem. There's nothing wrong with doing that (you don't have to use JSON for everything).
Simple data
Why are you setting dataType and contentType in the first place? Since your object test is very simple you can just provide it as is and it will be consumed by Asp.net MVC without any problems and you will return your partial view.
Complex data
If your object would be more complex then you could use a different jQuery plugin that will make it possible to send complex JSON objects without strigification.
All the examples of json I can find online only show how to submit json arrays w/ the jquery command $.ajax(). I'm submitting some data from a custom user control as a json array. I was wondering if it's possible to submit a json array as a regular post request to the server (like a normal form) so the browser renders the page returned.
Controller:
[JsonFilter(Param = "record", JsonDataType = typeof(TitleViewModel))]
public ActionResult SaveTitle(TitleViewModel record)
{
// save the title.
return RedirectToAction("Index", new { titleId = tid });
}
Javascript:
function SaveTitle() {
var titledata = GetData();
$.ajax({
url: "/Listing/SaveTitle",
type: "POST",
data: titledata,
contentType: "application/json; charset=utf-8",
});
}
Which is called from a save button. Everything works fine but the browser stays on the page after submitting. I was thinking of returning some kind of custom xml from the server and do javascript redirect but it seems like a very hacky way of doing things. Any help would be greatly appreciated.
This is an old question but this might be useful for anyone finding it --
You could return a JsonResult with your new titleId from the web page
public ActionResult SaveTitle(TitleViewModel record) {
string tId = //save the title
return Json(tId)
}
and then on your ajax request add a success function:
function SaveTitle() {
var titledata = GetData();
$.ajax({
url: "/Listing/SaveTitle",
type: "POST",
data: titledata,
contentType: "application/json; charset=utf-8",
success: function(data) { window.location = "/Listing/Index?titleId=" + data; }
});
}
That would redirect the page after a successful ajax request.
I just saw that you mentioned this at the end of your post but I think it is an easy and quick way of getting around the issue.
Phil Haack has a nice post discussing this scenario and shows the usage of a custom value provider instead of an action filter.
I don't understand why you would want to post Json if you're wanting to do a full page post. Why not just post normal form variables from the Html form element?