I have created one bootstrap modal on index.jsp. When I click on save button I have navigated my controller from .jsp file to .js file where i have written requestToChangePassword() in .js file. Now my question is, from that function i want to make ajax call request so that i can enter into one of the .java file and proceed further.
I have written ajax call like following code is in .js file:
ajaxCallFunctionget("../view/passwordChangeRequest",data,handlePasswordChangeHandler,"text", true);
In java file I have written
#Controller
public class UserGridAjaxController {
static Logger log = Logger.getLogger( UserGridAjaxController.class.getName() );
#RequestMapping(value = "/passwordChangeRequest", method = RequestMethod.GET)
#ResponseBody
public String passwordChangeRequest( /*#RequestParam("userNameForEdit")String userNameForEdit,*/HttpServletResponse response )
{
log.debug( "In passwordChangeRequest() method of class " + getClass().getName() );
System.out.println( "In passwordChangeRequest() method of class !!!" );
String result = "";
//result = delegate.deleteUser(userNameForEdit);
return result;
}
}
When I hit ajax request getting following exception in browser.
VM230 jquery.js:4 GET
http://localhost:8080/view/passwordChangeRequest?fromDate=05102019&_=1557482141385 404 (Not Found)
Hi I have created small project and shared proect on GitHub Please check and let me know where I am doing wrong.
Related
Is it possible to send a javascript variable to a controller endpoint, and then have the controller return a new view?
I've tried using a requestbody and ajax to do it, which passes the variable correctly, but is unable to load a new view.
Maybe there's a way to do it with thymeleaf?
If you're using Thymeleaf then just reference the template you want to return to the user by its filename.
#Controller
public class YourController {
#GetMapping("/someUrl")
public String getTemplate(#RequestParam String templateName){
return templateName;
}
}
This would be the bare minimum that you'd need, assuming your templates are in the correct folder - by default in resources/static. If the frontend sends a GET (/someUrl?templateName=xyz) to the backend, it would return the xyz.html from your templates. If it does not find the template that was requested in the parameters then it will return a 404.
Edit: Reading through the comments I realized there might be a confusion between #RequestParam and #PathVariable. In case you want to use a path variable to define the template name, so that the frontend can call GET (/someUrl/xyz), then you can do
#Controller
public class YourController {
#GetMapping("/someUrl/{templateName}")
public String getTemplate(#PathVariable String templateName){
return templateName;
}
}
Resources for both below:
https://www.baeldung.com/spring-request-param
https://www.baeldung.com/spring-pathvariable
I have a grid in a view, User has an option to select one/more rows from the Grid and on clicking of a "Next" button, I need to show them a another view, where they can do additional tasks.
I created two views from Same Controller.
public BatchController() : base("BATCH")
{
}
// GET: BatchProcess
public ActionResult Index()
{
return View();
}
public ActionResult Final()
{
return View();
}
Javascript:
$("#btnNext").click(e => {
var url = "/Batch/Final";
window.open('#Url.Action("Final", "Batch")');
Result:
what I am missing here?
The reason for why did your url is not correct is that #Url.Action("Final", "Batch") failed to parse successfully. When I input an incorrect URL:window.open('Url.Action("Final", "Batch")')(missing # would caused the parse failure), the generated url is as follows:
But I could see you have coded it in a correct way:window.open('#Url.Action("Final", "Batch")').So I guess this js code may be placed in an external js file.If it is an external javascript file, it cannot be parsed. The above situation will also appear.
If you must put #Url.Action in an external JavaScript file, you can add attributes to the Next button.
<button class="btn-outline-info" id="btnNext" requestUrl="#Url.Action("Final", "Batch")">Next</button>
Then the external js get the url through attribute.
window.open(document.getElementById('btnNext').getAttribute('requestUrl'))
If your js code is not in external file,please check the #Url.Action if it is be broken.You could write the #Url.Action("Final", "Batch") in your razor view(e.g Inde.cshtml):
#Url.Action("Final", "Batch")
And then run the application to see the url if it is like below:
I have a simple web application that operates with a set of words using JS. In order to test the main code I just put a needed data in a variable in my script.
CONST WORDS = [
["Computer", "Ordinateur", "https://www.lifewire.com/thmb/nNDKywb8qvKzhxelVAR95sEHBj0=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/Acer-aspire-x3300-5804ec185f9b5805c2b6b9e6.jpg"],
["Function", "Fonction", "http://latex-cookbook.net/media/cookbook/examples/PNG/function-plot.png"],
["Server", "Serveur", "https://effortz.com/wp-content/uploads/dedicated-hosting-server.png"]
]
Now I need to build a database (already done) and get such data from the server. So, the question is how do I acquire JSON file from the server using JS? I know how to make GET requests, but what should I do on the server to make it response? (or may be there is an easier way to get this data in JS, considering that I already got it from DB and can easy display on the webpage).
Here is a backend code
namespace LFrench
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Words> WordsSet = Words.GetWords("Business");//recieving from DB a set of words, that i need to use in JS
}
}
}
The thing you need to understand is the flow of your request. if you strictly want to do it in the Page_Loag event then I suppose you will have to make a method in your Javascript that will actually accept your data as parameter and then call the Javascript method from the C# CodeBehind Assuming that the data in the parameter is in JSON format. This method works but is not very efficient.
Other way is, in your JQuery side, you should make an ajax call to a WebMethod of yours in the CodeBehind that will actually send the response in JSON format. This is cleaner way of doing it.
Your JQuery should look like:
$(document).ready(function(){
$.ajax({
method: "GET", accept: "application/json; charset=utf-8;",
url: 'MyPage.aspx/GetDataFromDB', success: function(data){
console.log('Success Response in JSON: ' + data.d); // notice *data.d*, Calling from WebMethods returns the object encoded in the .d property of the object.
}, fail: function(err){
console.log(err);
}
});
});
And your CodeBehind should look like:
[WebMethod]
public static string GetDataFromDB()
{
var myData = YourDbCall(); // Some method to retrieve data from database
var body = new
{
Firstname = myData.Firstname,
Lastname = myData.Lastname,
Email = myData.Email,
// Any Other Information
};
var json = JsonConvert.SerializeObject(body);
return json;
}
EDIT
Here is how your Word Set will be sent back as JSON:
[WebMethod]
public static string GetDataFromDB()
{
List<Words> WordsSet = Words.GetWords("Business");
return JsonConvert.SerializeObject(WordsSet);
}
Make sure you have installed Newtonsoft.JSON from Nuget Package Manager Console. if not you can Open Package Manager Console and run this command:
PM> Install-Package Newtonsoft.Json
You need to make json return type method on serverside. Than call it from your get method and do your method on serverside and fill the List and return that list by converting JSON format.
I am currently using jquery to send data from javascript to a php file to execute some server side code:
$.ajax({
url: 'myfile.php', //instead of php, can I call a exe (c#) or asp page here?
type: "POST",
data: ({name: Dummy}),
success: function(data){
}
});
I am facing issues in passing values from my javascript to php file, data is dropped at adfs (eso). So I want to know if a c# exe, or an asp page can be called instead of a php and is it advisable, are there any other way of passing values from client end to server side, my website is made of html files and javascript only.
tried passing this aspx page as URL in above code
Url ="mydomain.com/site/default.aspx";
on the aspx page I am reading
string[] keys = Request.Form.AllKeys;
but the aspx page isnt getting executed (like a php does otherwise)
Take a look at this link, ASP.Net have something know as WebAPI which is great for HTTP services and potentially perfect for what you want.
EDIT:
Based on a comment here is a really basic controller with Get and Post verbs
public class DummiesController : ApiController
{
[HttpGet()]
[Route("api/dummies")]
public IHttpActionResult Get()
{
return this.Ok(new[] {new Dummy(), new Dummy()});
}
[HttpGet()]
[Route("api/dummies/{id}")]
public IHttpActionResult GetById(int id)
{
return this.Ok(new Dummy());
}
[HttpPost]
[Route("api/dummies")]
public IHttpActionResult Post(Dummy dummy)
{
int id = 1;
return this.Created($"api/dummies/{id}", dummy);
}
}
I have an MVC application which i am trying to give the user the opportunity to download a zip of files,but unsuccesfully.Let me explain further.
Inside my view(ImageViewer.cshtml) i have a div class with an on click event that when pressed i call the controller method(ImageViewerController.GetZipPhotos) which handles the download of the zip file.See below:
div class="text" onclick="GetZipPhotos()">Download</div>
and the Javascript that get called is this:
function GetZipPhotos() {
$.ajax({
url: '#Url.Action("GetZipPhotos", "ImageViewer",Request.Url.Scheme)',
type: 'POST',
contentType: 'application/zip',
error: function () {
alert('There was an error!'+result);
}
});
}
Now, inside my ImageViewerController i have the following method:
[HttpPost]
public ActionResult GetZipPhotos()
{
ZipResult newZipResult=new ZipResult(
Server.MapPath("~/File1.txt"),
Server.MapPath("~/File2.txt")
);
newZipResult.OutPutZipFileName = "PhotosZip.zip";
return newZipResult;
}
and the declaration of the ZipResult custom action is:
public class ZipResult:ActionResult
{
private IEnumerable<string> _filesToZip;
private string _outPutZipFileName="ZipFile.zip";
public ZipResult(params string[] filesToZip)
{
this._filesToZip = filesToZip;
}
public override void ExecuteResult(ControllerContext context)
{
using (ZipFile oneZipFile = new ZipFile()) {
oneZipFile.AddFiles(_filesToZip);
context.HttpContext.Response.ContentType = "application/zip";
context.HttpContext.Response.AppendHeader("content-disposition", "attachment; filename=" + _outPutZipFileName);
oneZipFile.Save(context.HttpContext.Response.OutputStream);
}
}
}
The problem is that the code ofcourse doesn't work because the name of the view that called the controller is different from the actual method(GetZipPhotos).The view's name is ImageViewer.cshtml and the controller's name is ImageViewerController.
As fas as i have understood, the MVC framework uses code conventions, so it expects the name of the method to be the same as the view.The problem is that my view and the method are diferrent so the response never gets to back to the view.
I thought of creating a new view that has basically nothing inside, just to call it from the method and return the zip file.If this could be a possible solution, how can i tell from the action result which view to send the response?
No need to use ajax for the file download. The browser will normally start the download and keep you on the same page. Also, no need for a custom action result, you can just use FileResult. Try something like this:
public FileResult GetZipPhotos()
{
var filesToZip = new List<string> { Server.MapPath("~/File1.txt"), Server.MapPath("~/File2.txt") };
var oneZipFile = new ZipFile();
oneZipFile.AddFiles(filesToZip);
return File(oneZipFile.ToByteArray(), "application/zip", "PhotosZip.zip");
}
Of course, you'll need to figure out this part oneZipFile.ToByteArray(), but the ZipFile class probably already has something like that.
Your ajax call is redirecting the response into nowhere.
I would do it like this:
use a hidden iframe, change its src to the desired path in your function and it should be prompting a file dialog.