I am trying to learn Spring MVC and I wanted to get hands on in MVC. I have a simple web application where I am inputting a string from the user and displaying some results from a database back to the user. All this is happening in a single page without the page refresh. We can use RequestParam in the controller and access the elements in the JSP page. ( I am using Bootstrap for this project)
For example in home.jsp,
<form class="navbar-form navbar-right">
<input type="text" name="myValues" class="form-control" placeholder="product..." >
</form>
and, in the controller,
#RequestMapping(value={"", "/", "/home"}, method = RequestMethod.GET)
public String home(Locale locale, Model model,#RequestParam(value="myValues", required=false) String myValues) {
logger.info("Welcome home! The client locale is {}.", locale);
This will help me get the form query string in the controller.
I can then do the necessary processing and use addAttribute in the controller to return the list. (Retailerdetail is my class to implement the backend database)
ArrayList <RetailerDetail> rlist = mydata.getData();
model.addAttribute("name",rlist);
return "home";
and display it in the jsp page.
<c:forEach items="${name}" var="element">
<tr>
<td>${element.name}</td>
</tr>
</foreach>
At this point of time I am doing this without using Jquery or js. I have seen some code where people use jquery or js for ajax implementation in Spring MVC.
My question, is this AJAX? We are getting similar functionality as AJAX without using Javascript or Jquery. Why is jquery or js used for implementing AJAX when using Spring MVC. Can you please give a specific example where I might have to do the same? I have gone through tutorials of MVC as well as AJAX quite a bit, but dont have a complete understanding of the concept. I realize that I am missing some basic concepts here. But it will help me get a lot of clarity if you could explain.
To quote from What is AJAX, really?
This is the answer by Nosredna:
"The rough idea in English: You have a web page. Some event (can be
a button press or other form event, or just something triggered by a
timer) occurs and triggers JavaScript code that asks the server for
fresh information (like the latest value of GOOG stock). There's a
piece of code on the server that collects the info you passed and
sends some info back. That's different from the page-serving job the
server usually has. When the server answers, a callback function
(that you specified in the JavaScript call to the server) is called
with the info from the server. Your JavaScript code uses the info to
update something--like a GOOG stock chart."
In my code the same functionality is achieved without using Javascript? That means we can implement the AJAX functionality without using any Javascript? When do we really have to use Javascript for implementing AJAX in this case?
If you open developer tools in your browser (f12), open the network tab, and then perform the request from your web-page, you will see the the entire html page is returned in the response.
Using AJAX, the server will return just a JSON key-value map. Your javascript code can then use this to populate a section of your page, leaving most of the page unchanged.
This is more efficient and quicker.
Related
Generally speaking when you're doing a POST request you want to reload the page. Though not always. When using a GET method to retrieve data you may consider using AJAX. However I am relatively new to Razor Pages and ASP.net core altogether. I am being told we should always load the page. That since we are using Razor Pages it is not correct to use AJAX to submit anything to the code-behind. Otherwise whats the purpose of using Razor Pages.
My concern is it leaves a bad user experience. If I want to run a report, retrieve the data, and show the data using a handler. I require the page to reload. If I use AJAX I require JSON but it doesn't require the page to reload. If I use a handler I can get back a model which I can use to display on the reloaded page without having to convert it to JSON.
What is the best practice with Razor Pages? It seems like if you must reload every time we are going back in time to 2003.
It's perfectly fine to use AJAX to submit to the Razor Pages code-behind, I've built a blog application's Admin Panel based on this with satisfactory results https://github.com/FanrayMedia/Fanray
The Razor Pages model-behind class serves as convenient end points that return JSON to your AJAX calls. For example, my blog's composer which is a Razor Page has an auto-save draft feature, in the view I have js code like
axios.post('/admin/compose?handler=save', this.payload, { headers: { 'XSRF-TOKEN': this.tok } }) ...
which posts to this model-behind class code
public async Task<JsonResult> OnPostSaveAsync([FromBody]PostVM post)
{
...
return new JsonResult(postVM);
}
Hope this helps!
I am doing a POST-request using jQuery which seems to succeed. But how can I work with that on server side and modify the response?
Do I need another servlet because the Faces Servlet is just not designed to deal with this?
$.ajax({type:'POST', data:{"status":status}, success: function(response) {
alert("Qapla'");
}});
It is used for the following process:
user inputs address and hits commandButton which invokes JS
JS retrieves geodata using google maps and sends it to server (which I am considering to use the above code for)
the servers responds sending some close places from database
JS retrieves exact distances using google maps again and sends them to server
server redirects client to next page with results
There is one case where a failing validation for the used inputText might be needed: At point 2 the server rates the geodata as not valid.
If sending the ajax POST by usual JSF means (UICommand component, jsf.ajax.request(), etc, in flavor of <h:commandButton>, <p:remoteCommand>, <o:commandScript>, etc) is really not an option for some reason left unspecified in your question, then you'd indeed better create a separate servlet or even JAX-RS or JAX-WS webservice listening on those requests and returning e.g. XML, JSON, etc. JSF is a HTML form based MVC framework not a web service framework.
You only need to take into account that you deal properly with JSF view state when you manipulate the HTML representation of JSF components afterwards. E.g. when you use custom JS/ajax to enable a disabled HTML button as generated by <h:commandButton> without involving/notifying JSF, then it won't appear as enabled in JSF component state and its action would never be invoked.
See also:
How to use Servlets and Ajax?
How to generate JSON response from JSF?
How to invoke a JSF managed bean on a HTML DOM event using native JavaScript?
What is the need of JSF, when UI can be achieved from CSS, HTML, JavaScript, jQuery?
I've been researching this like crazy, but I can't find a way to to get this error from triggering. I'm hoping someone here can help me.
I have a drop down list object on my page that I'm creating as a server control, but which I'm dealing with entirely client-side at run time. The reason why I'm using a server control at all is because I need it to trigger an AJAX updatepanel elsewhere on my page. Anyway, this dropdown list starts blank, but gets populated with options by some jquery code based on user input. Up to this point there's no problem, but when the user makes a selection from this dropdown, I get the ClientScriptManager error. Selecting from this dropdown triggers an ajax json call to get data from the server.
I'm registering all my client-side script files (including the one that contains the offending json call) with ClientScriptManager.RegisterClientScriptInclude. Registering the dropdown itself with RegisterforEventValidation doesn't work, because the dropdown has no options at load time.
The application works in spite of this, but the error is defeating some enhancements I want to make, so I need to put this to rest. You can see the application (and view the error in your browser's debugging console) at https://www.heritagecutter.com/MillingCalc/; the dropdown your looking for is the one headed "Series", which will become active after you make selections in Material Group and Material Type above. The error appears after you select a series.
Thanks in advance for any guidance.
Found a solution, for anyone who may stumble across this in the distant future:
So the situation with my code was that I was using mostly HTML objects, with ASP.NET server controls for those few instances where I was dealing with the server, even though those server controls were triggering client-side code at runtime. I did this because I are noobsauce.
I was already using client-side AJAX calls to contact the server for my data, so I cleared out the clever-clogs server controls (my offending drop down list, and the Ajax UpdatePanel in toto) and replaced them with HTML objects. I kept the .aspx page that contains my code, because I needed the code-behind to store the web methods being called by client-side script, and I left my web methods and ajax code alone, because the didn't need to be changed, and the error went away on the first try.
I go away somewhat embarrassed, but wiser for it.
Hello first I’d like to say, please excuse my ignorance to this all, as I’m very new to this all. I just started and still trying to understand this.
So far I have a database set up and I’m trying to retrieve values from a database to fill in a form on a page when it loads. The record or row/values that need to be retrieved from a database depend on the page’s URL.
I’m ok with html and css but still trying to learn more about jquery, JavaScript, sql, php and so on and so forth. I realize I have a ways to go and honestly some of the guides and tutorials online are kind of confusing because everyone has a different way of coding. So I’m a bit confused.
I’ve included a simple chart to breakdown what I’m trying to do.
If someone could point me in the right direction I’d be really grateful! Thanks.
If I understand you well, you want to setup a form and populate some fields of this form with a query forms a database, the primary key of the record being relative to the url.
The first step is to build the url, you can pass some parameters to an url by adding a ? at the end of the url followed by the parameter name, the = sign and the parameter value. If you have more than one parameter, you should separate each parameter with the sign &.
So your url could be something like this :
www.examplesite.com/page&.html?key=key_A1
Then, you'll have to choose if you want to build the page on the server side with a language like php, in which case you retrieve the parameter, query the database, build the html form and send it to the client.
You can also go client side with plain javascript or jquery, in which case you will still have to do some server side programming to query the database but will use an ajax call to get the data and will populate the fields in Javascript or JQuery.
You can do this using Javscript(using Ajax)
U need the key to search for get the results from database
Using ajax call get the data, You might have to write code to get the details from database using any server side prog language
Using javascript to fill the form input with the received data.
Google for jquery ajax examples, and how to populate input using javascript.
There are many frameworks out there that have DataBinding built-in that do the same job a lot easier. My favourite would be Angular Js, you can try Ember and lot more out there, choose the one you feel comfortable with.
I am making a website but I get a bit lost programming dynamic sites.
The user needs to enter x (inside a textbox), click submit, process in java (serverside) and present outcome as a report to the user (using javascript).
I'm at the moment using JSP to process the users input but now I need to pass the JSON code into the javascript. The javascript requires JSON data.
At the moment I have JSP which returns the necessary JSON code and the Javascript which works with hardcoded JSON code. I need to somehow store the returned JSON (from the JSP) in a variable and pass it to the Javascript. I have a vague understanding of AJAX - i'm just unsure if this is possible and how to link it all together.
Thank you.
Your JSP "page" can simply generate JSON directly. There's no reason the output from JSP has to be HTML. From the client, therefore, you POST to the server, the JSP runs, and the result (pure JSON from your JSP) is sent back to the client as the ajax response.
Sounds like the perfect place for AJAX - you can submit the request with javascript, and when it comes back process it further with javascript. Unless you want the page to refresh.
If you are using jQuery, you can look here to see how to implement it, should be relatively painless: http://api.jquery.com/jQuery.post/