I am using Zend Framework.
I have PHP class as:
FileName : AdminController.php
Path : /admin/AdminController.php
Ajax Function :
function exportToExcel()
{
$.ajax({
url: "/admin/AdminController/testFunction",
type: "POST",
success: function(output){
alert("Sucess "+output);
}
});
}
PHP Class:
class AdminController extends AbstractActionController
{
public function testFunction()
{
return 'Its a test!!!';
}
}
But i am not getting alert in sucess as:
Sucess Its a test!!!
What can be mistake?
How to call php function in particular phpclass/file???
try
class AdminController extends AbstractActionController
{
public function testFunction()
{
echo 'Its a test!!!';
}
}
when you do 'return' the function returns the object, this is how you return data from models to your controllers, but when you need to send data to the client, here using AJAX, you need to print the data.
UPDATE
try to open the url in browser, i.e. go to http://www.your.domain.com/admin/AdminController/testFunction and if the server is configerd as it should, you should see Its a test!!! on your screen.
if you don't see it, follow this guide to configure your server, especially the part about 'Create Route'
Try with full url in ajax call
url: "http://example.com/admin/AdminController/testFunction",
Make sure you have setup routes for this.
Must be send back a output with echo , print or any printing method
public function testFunction() {
echo 'Its a test!!!';
}
For more error check your browser console for errors
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.
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..!
I am learning Spring MVC and I have stuck at how to send a simple string value from client using AJAX and print it at JAVA server (controller). I have written below code for doing this. But when I click button to send string, error.... response is popped-up in my browser and the browser console displays POST http://localhost:8090/addUser 404 (). It has been a day since I am trying to solve this issue. Can someone please tell what can be the problem? Or please tell a working alternative solution for sending data from client using AJAX and printing/saving it on JAVA server (Spring-MVC).
UserController.java
#Controller
public class UserController {
#RequestMapping(value = "/addUser", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
public JSONArray addUser(#ModelAttribute("UserTest") JSONArray name) {
System.out.println(name.toString());
return name;
}
}
AJAX Request:
<script>
function addUser() {
var json = '{"uname":"John", "Age":42}';
obj = JSON.parse(json);
$.ajax({
url : "/addUser",
data : obj,
type : "POST",
async: false,
contentType: "application/json",
success : function(response) {
alert( response );
},
error : function() {
alert("error...."); //this is being popped-up in my browser
}
});
}
</script>
POST http://localhost:8090/addUser 404 ()
Your request is going to http://localhost:8090/addUser, which is not correct. Your request url should have your application and included.
http://localhost:8090/<app_name>/addUser
AFAIK, your request url should have application name included. Now, to achieve this, you are suppose to change your ajax url
url : "/<app_name>/addUser"
The URL for the ajax call is not correct. It should be like
Url:YourApplicationContextPath/ControllerName/addUser
I am doing a search for a date in the database using ajax to call the function. The problem is that it gives me a 404 result when it should be showing it and the ajax enters in error mode.
controller code that works
[HttpPost]
public ActionResult SearchDate(DateTime date)
{
code...
return View(employees);
}
ajax code
function SearchByDate()
{
var x = document.getElementById("DateInputField");
if (x.value != "")
{
$.ajax({
url: '/Employees/SearchDate',
type: 'GET',
data: { "date": x.value },
error: function (data) {
alert('Error!');
},
succes: function (data)
{
alert('Succes!');
}
});
}
else
{
alert('Date not selected!')
}
}
I ran the program with breakpoints and it exits with the right result but it is showing none and in the developer console i get ERROR 404!Not found! and also the ajax returns alert error.Please help! Ty
Update after some issues where fixed i get this error:
The view 'SearchDate' or its master was not found or no view engine supports the searched locations!
There are multiple errors:
[HttpPost] at backend and you are sending a GET request.
404 means file is not found, so your path might be not correct.
succes callback should be success.
contentType is not set instead you can look into traditional:true,.
Use Query string in place of send data from data parameter.
changed type: 'GET',datatype: "html", then created a partial view rendered it inside and changed the function in controller to HTTPGET and returned partial view as result!
I'm quite new to MVC and I'm trying to call a method int one of my controllers.
<script>
function checkCardNumber() {
var content = $('#card-number').val();
var url = "AccountController/CheckRegisteredCard";
alert("content and URL are set");
$.post(url, { cardNumber: content }, function (data) {
alert(data);
});
alert("called outside of Post");
}
</script>
and here's the C# controller side:
[HttpPost]
public string CheckRegisteredCard(string cardNumber)
{
if (/*some condition*/)
{
return "";
}
else
{
return "some string";
}
}
both alerts("content and URL are set", "called outside of post") are being triggered, but the ajax part is not working at all. What am I doing wrong here?
If your controller class is called AccountController, the url should be /Account/CheckRegisteredCard.
Have you checked the network tab of your browser? I bet there's a 404 error.
If this snippet of javascript is in a .cshtml file, I would recommend using #Url.Action() to get the url string.
I would recommend using Fiddler and having that open when the ajax call is being made. This will tell you (1) if the call is being made at all or failing immediately, and (2) what kind of response you are receiving from the controller. Also agree with Jason P about how the url should be calling the controller.