Ajax Jquery Mvc Example

Posted on  by admin

Today I want to demonstrate how to integrate AJAX into a Spring MVC application. I’m going to use JQuery on a client side for sending of requests and receiving of responses.

This tutorial will be based on one of my previous tutorials about Spring MVC and REST services.

  • In this article you will read how to make a web-application more interactive with the help of asynchronous requests.
  • I need to modify the SmartphoneController class by removing methods which are not required any more.
  • This is a first step of AJAX integration. You can compare the new version of the SmartphoneController with the older one.
  • Methods which process PUT, POST, DELETE requests and return ModelAndView objects were removed.
  • The methods were deleted because AJAX calls can be addressed directly to REST methods.

Now the controller contains just two types of methods:. The first type directs user to pages where CRUD operations can be performed.

Swear Jar

Scenario 2: Calling an action method that takes parameters and returns string content

The second type performs CRUD operations (REST methods). An AJAX usage implies a lot of code on a client side of a web-application.

jQuery AJAX Call with Multiple Parameters

In this section I will demonstrate a basics which will help you to understand what steps to do for implementation of AJAX calls.Let’s examine case with creation of a new smartphone in the application.

First of all I need to add JQuery library to HTML page:.
A main part of the HTML has one valuable update – extension of form action attribute was changed to .json.
And now, ladies and gentlemen, I wish to introduce a snippet of JQuery code for the creation of new smartphone:.
I’m not going to stop on this code and explain it in detail because you can read about AJAX and JQuery on official site.
Brief explanation: when someone want to submit the form with specified ID, all form fields are assigned to appropriate variables.
After that a new JSON document is generated based on the form field variables.
Then AJAX call is performed.
It directed to URL which is specified in the action attribute of form tag.
The JSON is used as a data which need to be processed.
Type of the request is POST (it can vary depending on operation, e.g.
for update it will has PUT value).
In the beforeSend function I explicitly specify required headers for JSON format.
In the end I formulate a response and insert it in DOM.
That’s it what related to creation of smartphone.
The update of smartphone is the similar, just type of the request need to be changed.
Now let’s see how to work with DELETE type of requests.
As previously I need to change extension of URLs to .json.
A JQuery code for the DELETE operation will be a little bit distinct compared to POST and PUT.
The first distinction is the selector for the element.
In case with DELETE I want to work with links but not with forms.
The type of the AJAX call is changed to DELETE value.
There is no any data which is send with the request.
And in the end I delete the row with the smartphone which need to be deleted.
I hope this short overview of the AJAX will be useful for you.
There are a lot of features which can be implemented with the help of AJAX in any web-application, so don’t ignore this convenient way for communication with a server.
You can find this application on GitHub.
Setting up a new ASP.NET MVC project with controllers and views is pretty straightforward, with comprehensive examples on the official site.
Once you get your mind wrapped around the Model-View-Controller pattern, working with those areas in the application feels comfortable.
AJAX provides the option of updating parts of your web page without reloading the entire page.
While this is attractive in some applications, adding AJAX functionality adds an additional layer of complexity that ends up getting some new (and old) developers stuck.
Furthermore, .NET has some quirks that aren’t really obvious. Let’s take a look at how to make a jQuery AJAX call to an MVC Controller with parameters.
What follows is a detailed explained of what you need to do to make the AJAX requests work.
If you’re just looking for a quick reference, jump to the summary.
When I’m trying to learn something, I try to work with examples that are as close to real-life as possible, without being too complicated.
A simple AJAX-infused app might be something like a to-do list, grocery list, or a list of social media posts.
I think those are boring.
So we’re going to make a swear jar app.
In this application, we need to have a button that the user would press whenever someone uses a curse word.
We’ll have an input to set the amount of money to be added to the jar each time.
And we’ll have a display that shows the total.
Start by creating a new ASP.NET Web application with no authentication.
Next, once the project has been created, add a new controller by right-clicking on the Controllers folder and selecting Add -> Controller….
Select the MVC 5 Controller - Empty option, and call this controller SwearJar.
Now that we have our controller, we just need to create an Index view to house our client-side markup and JavaScript.
Inside the Views folder, Right-click on the SwearJar folder.
Select Add -> View and make the Index view.
Run your application to test it out.
If you navigate to http://localhost:YOURPORT/SwearJar you should see something like the following:.
Boring, but awesome.
Let’s make it a little less boring and get it ready to make AJAX calls.
Since we’re using jQuery to make these AJAX requests, we’ll obviously need to include jQuery.
Visual Studio automatically includes jQuery on the Shared/_Layout.cshtml page, so every View ought to be able to access it already.
Otherwise, we would need to do that ourselves, like this:.
Next, I’m going to set up the view with our HTML elements.
We’ll start with something stupidly simple.
We’ll click a button, and our page will tell us how much money is in the swear jar.
In your project, go to Views -> SwearJar -> Index.cshtml.
Clear out the existing Razor markup, and replace it with this.
@section Scripts { }. Now we’re ready to begin. We’ll begin simply, by creating a method in the controller to return the amount that’s in the swear jar.
This will be a good way to see how simple data types are used in AJAX controller methods.
In the SwearJar controller, add this method:. public double GetAmount() { return 1.45; }.
Then, over in your Index.cshtml file, add this Javascript code inside the script tags.
function getAmount() { var url = “@Url.Action(“GetAmount”)”;.
$(“#btnHowMuch”).on(“click”, getAmount);.
Here, I’ve attached an event handler to the button so that, when clicked, the getAmount function gets fired.
Inside of getAmount, we retrieve the URL of our controller method by using the Url.Action HTML helper.
It’s also possible to just hard-code this as “/SwearJar/GetAmount”, which is what gets rendered to the page anyway.
Next, we use jQuery to call the controller method.
You may have seen more verbose GET syntax for jQuery before, using $.ajax(), like this:.
$.ajax({ type: “GET”, contentType: “application/json; charset=utf-8”, url: “/SwearJar/GetAmount”, success: function (data) { successCallback(data); }, error: function (data) { failureCallback(data); } });.
There’s nothing stopping you from using this, but $.get() abstracts a lot of the configuration away.
As long as it’s working, I prefer to use $.get().
Once the data is returned from the controller, we’ll display it in the swearJar div.
Let’s try it out.
Run the project, and click on the button.

Scenario 3: Calling an action method that takes parameters and returns JSON

If you noticed, we made the return type of our method a double.

jQuery AJAX Call with a Single Parameter

We have no problems returning a variety of data types in the same way, like strings and integers.

But look at what happens when we try to return a List of strings:.

Not the answer you're looking for? Browse other questions tagged phpmodel-view-controllercodeigniterjquery or ask your own question.

![trying to return a List from ajax controller](/images/jquery-ajax-call-to-mvc-controller-10.png).

jQuery POST with Multiple Parameters

For something like this, we’ll need to return our data as JSON. To make this happen in our controller, we need to make some adjustments to the Action method.

The return type needs to be JsonResult and we need to serialize our data to the JSON format.

Server-Side Controller Code

Here’s our new controller:. public JsonResult GetAmount() { var list = new List { "5 quarters", "2 nickels", "8 pennies" }; return Json(list, JsonRequestBehavior.AllowGet); }.

Client side