I have a scenario like when user clicks on the hyperlink from the HTML page, it has to go with the ID (passed id in the onclick method of hyperlink) and call the Java method that accepts the ID parameter. Based on the ID, it returns some of the values as an Array to the Javascript function.
This is my java script function
function showTestCaseReport(testCaseId, testSteps)
{
var jObject = Java.type('Practice.myclasses.GenerateReport');
var stepResult = jObject.getTestStepsByCaseId(testCaseId);
alert(stepResult.length);
}
But its not working and not even showing alert dialog when click on the hyperlink.
Is there any way to integrate javascript function and java method?
You need to make a ajax call to a page where you execute you Java function and return your data back to your JS
$.ajax({
url: "java_page.jsp",
data: ID
}).done(function(data) {
//Do what you need with data(your array) hear
});
PS. the best practice is to return a JSON format data so your java code should return JSON
In HTML:
<a href="<c:url value="/test/${object.Id}" />" >Test</a>
In Java controller:
You have to use #PathVariable to get the ID passed.
#RequestMapping(value = "/test/{Id}", method = RequestMethod.GET)
public String Controller(#PathVariable("Id") String Id) {
...
}
You can directly hit the controller with href along with the Id.
If you want to hit the Java controller via JS Ajax.
In JS: AJAX Call
$.ajax({
type: "POST",
url: "test",
data: loginData,
success: function (result) {
// do something.
},
error: function (result) {
// do something.
}
});
Hope this helps..!
Related
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.
This is a simplified version of a problem I'm having. How do I send data to a Spring Boot Controller via an AJAX Query and then open a new JSP page? When I send data to the url in the AJAX Query to the matching URL in my controller class it seems to run the code within that method but not open the JSP (or return type).
For example if I were to send the following data from an Ajax Query
var hello = "Hello World!";
$.ajax({
type: "POST",
url: "/message1",
data: {
message: hello,
},
datatype: 'json'
});
}
To this method in my Controller class
#RequestMapping(value = "/message1", method = RequestMethod.POST)
public String MessageReceiver(#RequestParam("message")String message,
BindingResult bindingResult,
Model model) {
System.out.println(message);
return "NewPage";
}
"Hello" will print in the console but the JSP page NewPagewill fail to open and will prompt no errors?
Usually if I just call the url in the controller (for example /message1) via a href link, or button etc the NewPage JSP page will open. It seems that the AJAX query is missing something. Do I have to update the URL in the Ajax Query to something similar to /message1/NewPage (tried this, didn't work), or add something to the controller because the NewPage JSP page will not open.
Add the success callback function to your ajax like so:
$.ajax({
type: "POST",
url: "/message1",
data: {
message: hello,
},
datatype: 'json',
success: function(data){
if(data === "NewPage"){
//Open new page
}
}
});
}
I am using MVC 5 with jQuery and am having difficulties with posting the anti forgery token using Ajax. i have looked on SO at various fixes, but nothing appears to work.
I have the following code within my view.
#using (Html.BeginForm("None", "None", FormMethod.Post, new { #id = "js-form" }))
{
#Html.AntiForgeryToken()
....
other code
....
<button class="button-primary button expand js-button-search" type="button">Search</button>
}
Then using jQuery I have added an event handler to the button above by selecting the element via the class: js-button-search. The main Ajax call is as per below
$.ajax({
url: url,
method: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(_self.JsonData),
success: function (result) {
// Success code
},
error: function (jqXHR, textStatus, errorThrown) {
// Failure code
}
});
Where my confusion is, is around the data parameter. I have an object which is populated on demand that contains a large amount of elements that can be used for searching.
The object takes the form of (shortened as we current have over 40 search fields):
_self.JsonData = { "searchData": {"DocIdFrom" : "426737", "DocIdTo" : "753675", "DocIdTypeSearch" : "between", "DocDateFrom" : "06/02/2017", "DocDateTo" : "", "DocDateTypeSearch" : "greater than", .....
etc...
}}
As you can see, the data is parsed using JSON.stringify. All of this work as long as the [ValidateAntiForgeryToken] attribute is commented out on the controller function.
Controller as follows:
[HttpPost]
//[ValidateAntiForgeryToken]
public JsonResult GetSearchResultsJson(SearchCriteria searchCriteria, int? page)
{
// code in here
}
When I uncomment the anti forgery attribute, the page stops working.
Now i know about the need to pass the token across with the post and have tried the following without success:
how-can-i-supply-an-antiforgerytoken-when-posting-json-data-using-ajax
asp-net-mvc-5-ajax-request-on-edit-page-error-requestverificationtoken-is-not
The main difference between what I have appears to be a complex object, but i think that is a red herring as Stringify converts the object into a string.
Sorry, forgot to add. Fiddler return the following message when the [ValidateAntiForgeryToken] is enabled
[Fiddler] ReadResponse() failed: The server did not return a complete response for this request. Server returned 0 bytes.
I would like to thank Stephen Muecke for providing the solution to the problem.
Firstly my Json object was converted to the following:
var data = { "__RequestVerificationToken":$('[name=__RequestVerificationToken]').val(),
"searchData":
{
"DocIdFrom" : "426737",
"DocIdTo" : "753675",
..............
etc
}
}
Then, I removed the contentType parameter from the Ajax call and stopped stingifying the Json data.
This has had the desired effect and now i can call the MVC controller using the [ValidateAntiForgeryToken] attribute.
You might pass RequestVerificationToken (AntiForgeryToken) on Ajax call by using one of the methods below:
Method I: When using serialize() or FormData() methods, it is not necessary to add the token to the data parameters separately (it will be included id the formdata parameter):
//Send the values of all form controls within the <form> tags including the token:
var formdata = $('#frmCreate').serialize();
//or
var formdata = new FormData($('#frmCreate').get(0));
Method II:
var token = $('[name=__RequestVerificationToken]').val();
$.post(url, { comment: comment, IssueID: postId, __RequestVerificationToken: token },
function (data) { … })
Then you can use the Controller as shown below:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult AddComment(string comment, int IssueID){
//...
}
I'm taking an input from user named as category. On every key up i want to perform an ajax request to search if category with the similar name exists or not. If yes, then a there is a blank div below that input which i want to fill with the similar name categories.
So i created a form. Used ajax via jquery but i'm not receiving the response.
This is the jquery ajax code that i'm using
$("#category").keyup(function () {
$.ajax({
url: "categories/categoryajaxrequest",
type: "get",
data: {
category: $("#category").val()
},
success: function (response) {
$("#category_suggestion").html(response);
}
});
});
This is the route part which is used as url in ajax request
Route::get('categories/categoryajaxrequest', array('as' =>'categoryajaxrequest', 'uses' =>'CategoryController#categoryAjaxRequest'));
and this is the controller part
//app/controllers/CategoryController.php
....
public function categoryAjaxRequest(){
echo "working";
}
So, the input text has an id of "category" and below the input, there is a div with an id of "category_suggestion". At every keyup on the input, i expect it to perform an ajax request and show "success" in div . But it's not doing anything.
However, if i go directly to "/categories/categoryajaxrequest" on my browser, it outputs "working".
Try putting the action directly in the url: property of the $.ajax() method, then no route is needed:
Laravel gives us the liberty to do that. The curly braces {{ }} are used in views. As the JavaScript stuff is usually called in a view, it is legitim to do it that way.
The URL::action part is described in the docs as follows:
To generate a URL to a controller action, we may use the URL::action
method or the action helper method:
$url = URL::action('FooController#method');
$url = action('FooController#method');
So the combination of the template system & the URL::action gives us the possibility of doing it this way:
$("#category").keyup(function () {
$.ajax({
url: "{{URL::action('CategoryController#categoryAjaxRequest')}}",
type: "get",
data: {
category: $("#category").val()
},
success: function (response) {
$("#category_suggestion").html(response);
}
});
});
I wrote a page Page method in my aspx page. in web service method I need to call FindControl method return textbox and get text box value. But my findControl will take MasterPage object to iterate.
Please see my code
<script type = "text/javascript">
function ShowCurrentDateTime() {
$.ajax({
type: "POST",
url: "HRDefault.aspx/GetDate",
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
}
function OnSuccess(response) { }
</script>
<System.Web.Services.WebMethod()> _
Public Shared Function GetDate() As String
Dim txt22_2 As TextBox = CType(RenderControls.FindControlRecursive
(Page.Master, "txt22_2"), TextBox)
Dim str As String
str = txt22_2.Text
Return String.Empty
End Function
But I am getting compiler error when use Page.Master:
Reference to non-shared member requires an object reference
How to pass Master Page object or Page to Page method?. So I can use in Sared method.
Is there any way I can access Textbox value directly in Page method? I need access couple of controls in Page Method.
don't know about $.ajax, but this works fine for me:
<asp:ScriptManager runat="server" EnablePageMethods="true" />
<!-- ...................... -->
<script type="text/javascript">
function ShowCurrentDateTime() {
x = document.getElementById('<%= TextBox1.ClientID %>').value;
PageMethods.GetDate(x, OnSuccess, OnFailure);
}
function OnSuccess(response) {
alert(response);
}
function OnFailure(response) {
alert(response._message);
}
</script>
and in code behind:
<System.Web.Services.WebMethod()> _
Public Shared Function GetDate(x as String) As String
' do something with x
' u can add more params if you need
Return String.Empty
End Function
hope the syntax is ok, i don't remember much of vb :P
HttpContext.Current.Handler may get you the reference to page object but it will not be useful because page life cycle is not executed in PageMethods (so no view-state or request data). You have couple of alternatives:
Pick control values from java-script. If needed, pass them to PageMethod using data parameter while making service call.
Use Session (HttpContext.Current.Session) or cache to store data on page and then retrieve it in PageMethod. I will prefer using cache with new guid as a key and then pass guid to PageMethod.
Since you're already posting data, you should be able to get reference to Request.Form collection which you can use to read posted textbox values