Chuyển tới nội dung
Home » Spring Mvc Ajax Post Example | Spring Components

Spring Mvc Ajax Post Example | Spring Components

How to integrate JQuery Ajax POST/GET & Spring MVC | Spring Boot | Java Techie

Quick Reference

1.1 In HTML, use jQuery

$.ajax()

to send a form request.


jQuery(document).ready(function($) { $("#search-form").submit(function(event) { // Prevent the form from submitting via the browser. event.preventDefault(); searchViaAjax(); }); }); function searchAjax() { var data = {} data["query"] = $("#query").val(); $.ajax({ type : "POST", contentType : "application/json", url : "${home}search/api/getSearchResult", data : JSON.stringify(data), dataType : 'json', timeout : 100000, success : function(data) { console.log("SUCCESS: ", data); display(data); }, error : function(e) { console.log("ERROR: ", e); display(e); }, done : function(e) { console.log("DONE"); } }); }

1.2 Spring controller to handle the Ajax request.


@Controller public class AjaxController { @ResponseBody @RequestMapping(value = "/search/api/getSearchResult") public AjaxResponseBody getSearchResultViaAjax(@RequestBody SearchCriteria search) { AjaxResponseBody result = new AjaxResponseBody(); //logic return result; } }

HTTP Request: GETPOST

Two commonly used methods for a request-response between a client and server are: GET and POST.

  • GET – Requests data from a specified resource
  • POST – Submits data to be processed to a specified resource

GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data.

POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.

To learn more about GET and POST, and the differences between the two methods, please read our HTTP Methods GET vs POST chapter.

How to integrate JQuery Ajax POST/GET & Spring MVC | Spring Boot | Java Techie
How to integrate JQuery Ajax POST/GET & Spring MVC | Spring Boot | Java Techie

Spring MVC AJAX Hello World Example – Kiến thức cơ bản HTTP và AJAX

Bài đăng này đã không được cập nhật trong 2 năm

Khi tìm hiểu về giao thức HTTP mình có đọc 1 số bài hướng dẫn trả lời phỏng vấn về giao thức HTTP như:

Phương thức POST bảo mật hơn GET vì dữ liệu được gửi ngầm bằng mắt thường không thể nhìn thấy được


Phương thức GET luôn luôn nhanh hơn POST vì dữ liệu gửi đi được Browser giữ lại trong cache


Phương thức GET dữ liệu được gửi tường minh, chúng ta có thể thấy trên URL nên nó không bảo mật.

Các câu trả lời ở bên trên chưa chính xác là do bạn chưa hiểu đúng về giao thức HTTP

**Trong bài hướng dẫn này mình sẽ nói đến các vấn đề sau**

1) Các khái niệm cơ bản về giao thức HTTP (GET, POST)

2) Tạo 1 web application sử dụng Spring MVC với AJAX

Giao thức HTTP( Hyper Text Transfer Protocol) là gì ? HTTP là giao thức quy ước chung để cho 2 đối tượng A và B có thể giao thông ( giao tiếp ) với nhau. Cụ thể là giao tiếp với nhau bằng 1 định dạng sử dụng chữ (text)

Ta đã biết phép căn bản của phần mềm là 2 phép đọc (read) và ghi (write) dữ liệu (Phần mềm viết ra là để xử lý dữ liệu) – phép ghi còn tách ra làm 3 phép thêm, sửa, xóa. Khi người ta thiết kế ra giao thức HTTP cũng xoay quanh các phép căn bản này của phần mềm. Từ 4 phép căn bản này sẽ tạo ra 7 HTTP method:

  • 4 phép đại diện cho đọc (read):
  1. GET
  2. Trace: đọc lỗi
  3. Option
  4. Head: đọc phần header
  • 3 phép đại diện cho ghi (write):
  1. PUT
  2. POST
  3. DELETE

Nhưng trong quá trình làm việc chúng ta gần như chỉ sử dụng 1 phép đại diện cho đọc là GET, 1 phép đại diện cho ghi là POST. Từ đây dẫn đến sự khác nhau giữa GET và POST:

  1. Ví dụ A muốn gửi 1 thông điệp (message) rằng A muốn đọc dữ liệu (GET) của B, như vậy A không cần mang dữ liệu lên B. Nhưng khi A muốn gửi (POST) 1 bức ảnh đến B, A phải mang dữ liệu lên B. Như vậy GET đại diện cho phép đọc sẽ không có phần body mà chỉ có header, còn POST đại diện cho phép ghi sẽ có phần body (đưa dữ liệu vào body)
  2. Sự khác nhau giữa cấu trúc của GET và POST sẽ ảnh hưởng đến điểm mạnh điểm yếu của POST và GET.
  • GET sẽ

    nhanh

    hơn POST: GET sẽ đi nhanh hơn POST trong môi trường mạng vì nó k có body. Phần server khi xử lý message này sẽ nhanh hơn vì GET chỉ có header (khi nói đến

    nhanh

    ta phải nhắc đến 2 khía cạnh: traffic và performance)
  • Điểm mạnh của POST là đưa được data lên. Nếu muốn đưa 1 đoạn video, 1 bức ảnh GET sẽ k thể nào làm được => Nhưng vì GET đi nhanh hơn nên người ta có xu hướng dùng GET nhiều hơn, thế nên những dữ liệu mà mang lên server đủ nhỏ thì người ta có thể chuyển dữ liệu theo đường GET
  • GET và POST đều có tính bảo mật như nhau, vì đối với GET ta có thể sử dụng kỹ thuật ajax để parametter k hiển thị lên trên url

**Tạo 1 project sử dụng Spring MVC + Ajax bằng maven, server chạy bằng jetty **

Ajax là gì ? Ajax là một khái niệm có thể mới lạ với những bạn newbie mới học lập trình web nên đôi lúc các bạn nghĩ nó là một ngôn ngữ lập trình mới. Nhưng thực tế không như vậy, ajax là một kỹ thuật viết tắt của chữ AJAX = Asynchronous JavaScript and XML, đây là một công nghệ giúp chung ta tạo ra những Web động mà hoàn toàn không reload lại trang nên rất mượt và đẹp. Đối với công nghệ web hiện nay thì ajax không thể thiếu, nó là một phần làm nên sự sinh động cho website

Các công nghệ sẽ sử dụng trong phần hg dẫn này:

  1. Spring 4.2.2.RELEASE
  2. Jackson 2.6.3
  3. Logback 1.1.3
  4. jQuery 1.10.2
  5. Maven 3
  6. JDK 1.8
  7. Tomcat 8 or Jetty 9
  8. Eclipse 4.5
  9. Boostrap 3

**Cấu trúc project **

**1)Project dependency: **


4.0.0


com.viblo


viblo-spring-learn-ajax
war
1.0-SNAPSHOT


viblo-spring-learn-ajax Maven Webapp


http://maven.apache.org

1.8


4.2.2.RELEASE


2.6.3


1.1.3


1.7.12


1.2


3.1.0



org.springframework


spring-webmvc


${spring.version}




commons-logging


commons-logging







com.fasterxml.jackson.core


jackson-core


${jackson.version}




com.fasterxml.jackson.core


jackson-databind


${jackson.version}





javax.servlet


jstl


${jstl.version}





org.slf4j


jcl-over-slf4j


${jcl.slf4j.version}




ch.qos.logback


logback-classic


${logback.version}






javax.servlet


javax.servlet-api


${servletapi.version}


provided





viblo-spring-learn-ajax

org.apache.maven.plugins


maven-surefire-plugin


2.12.4



true


-Xmx2524m


org.apache.maven.plugins


maven-compiler-plugin


3.1


1.8

1.8


UTF-8


true



-XDignore.symbol.file



org.eclipse.jetty


jetty-maven-plugin


9.3.0.M1



-Xmx2048m -Xms1536m -XX:PermSize=128m -XX:MaxPermSize=512m


manual




lib


${basedir}/target/viblo-spring-learn-ajax/WEB-INF/lib




8080
60000




${basedir}/src/main/webapp


${basedir}/src/main/webapp/WEB-INF/web.xml


${basedir}/target/classes

2)AjaxController AjaxController sẽ xử lý các ajax request từ phía client như thêm, hoặc tìm kiếm ! Sau đó trả về kết quả dưới dạng json cho client.


@Controller @RequestMapping("/home") public class AjaxController { private List listPerson = new ArrayList (); @RequestMapping(method = RequestMethod.GET) public ModelAndView home() { ModelAndView mv = new ModelAndView("web.home"); return mv; } @RequestMapping(value = "/addnew", method = RequestMethod.GET) public @ResponseBody String addNew(HttpServletRequest request) { String name = request.getParameter("name"); String age = request.getParameter("age"); Person person = new Person(name, Integer.parseInt(age)); listPerson.add(person); ObjectMapper mapper = new ObjectMapper(); String ajaxResponse = ""; try { ajaxResponse = mapper.writeValueAsString(person); } catch (JsonProcessingException e) { e.printStackTrace(); } return ajaxResponse; } @RequestMapping(value = "/search", method = RequestMethod.GET) public @ResponseBody String searchPerson(HttpServletRequest request) { String query = request.getParameter("name"); Person person = searchPersonByName(query); ObjectMapper mapper = new ObjectMapper(); String ajaxResponse = ""; try { ajaxResponse = mapper.writeValueAsString(person); } catch (JsonProcessingException e) { e.printStackTrace(); } return ajaxResponse; } public Person searchPersonByName(String query) { for (Person p : listPerson) { if (p.getName().equals(query)) { return p; } } return null; }

**3)Model Class ** Person class có nhiệm vụ đóng gói dữ liệu của người dùng nhập vào hoặc dữ liệu được trả về của server !


public class Person { private String name; private int age; public Person() { } public Person(String name, int age) { this.name=name; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }

**4)Jquery Ajax **
Trong file JSP, ta tạo 2 form thêm và tìm kiếm đơn giản gửi ajax request bằng

$.ajax


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<br /> Spring Ajax Example<br />


Add New Person

Search Person by name


Spring MVC Ajax JSON Response Example

Name:

Age:



Running and Testing the Application

To run and test the application, follow these steps:

  1. Deploy the application on the Apache Tomcat server.
  2. Open a web browser and navigate to

    http://localhost:8080/spring-mvc-ajax-json-example/

    .
  3. The page should display the name and age retrieved from the Ajax request.

That’s it! You have successfully created a Spring MVC Ajax JSON response example.

Frequently Asked Questions

How to get JSON response in Ajax call using Spring MVC?

To get a JSON response in an AJAX call using Spring MVC, you can use the

@ResponseBody

annotation in your controller method. This will indicate to Spring that the method should return the response as JSON. You can then use jQuery’s

$.ajax()

method to make the AJAX call and handle the JSON response.

How to send JSON data to Spring MVC controller using AJAX?

To send JSON data to a Spring MVC controller using AJAX, you can use the

contentType

and

data

options in jQuery’s

$.ajax()

method. Set the

contentType

option to

'application/json'

and the

data

option to a JavaScript object representing the JSON data you want to send. Spring will automatically deserialize the JSON data into a Java object that can be used in your controller method.

How to return JSON data from Spring MVC controller?

To return JSON data from a Spring MVC controller, you can use the

@ResponseBody

annotation in your controller method. This will indicate to Spring that the method should return the response as JSON. You can then return a Java object that will be automatically serialized to JSON by Spring.

How to show data using AJAX in Spring MVC?

To show data using AJAX in Spring MVC, you can use jQuery’s

$.ajax()

method to make the AJAX call to your Spring controller. In the success callback function, you can then use jQuery’s DOM manipulation functions to update the HTML elements on your page with the data returned by the controller.

How to implement Ajax call in Spring security?

To implement an AJAX call in Spring Security, you will need to configure Spring Security to allow AJAX requests. You can do this by adding a CSRF token to your AJAX requests and configuring Spring Security to accept requests with the CSRF token. You can also configure Spring Security to return a JSON response for AJAX requests by using the

@ResponseBody

annotation in your controller methods.

How to use jQuery to make a REST API POST request in Spring MVC?

To use jQuery to make a REST API POST request in Spring MVC, you can use the

$.ajax()

method with the

type

option set to

'POST'

and the

url

option set to the URL of your REST API endpoint. You can then use the

data

option to specify the data you want to send in the POST request, and the

contentType

option to set the content type to

'application/json'

. In your Spring MVC controller, you can use the

@RequestBody

annotation to automatically deserialize the JSON data into a Java object.

Spring MVC: Ajax & JQuery

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.

Ajax in Spring MVC Framework
Ajax in Spring MVC Framework

Refactoring Spring MVC

2.1 Create a POJO to store the Ajax POST data.


public class HostingForm { private boolean display; private boolean cdn; private boolean hosting; private boolean paas; private String whoisPattern; private long id; private String domain; private String name; private String desc; private String tags; private String affLink; private String imageUrl; private String favUrl; //getters and setters

2.2 Accept the Ajax POST data with

@RequestBody


@RestController //... @RequestMapping(value = "/path-to/hosting/save", method = RequestMethod.POST) public String updateHosting(@RequestBody HostingForm hostingForm) { //... }

With

@RequestBody

, Spring will maps the POST data to

HostingForm

POJO (by name) automatically. Done.

You mat interest at this tutorial – Complete Spring 4 MVC + Ajax Form Post example

Spring Components

Only the important classes will be displayed.

4.1

@RestController

to handle the Ajax request. Read the comments for self-explanatory.


package com.mkyong.web.controller; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.annotation.JsonView; import com.mkyong.web.jsonview.Views; import com.mkyong.web.model.AjaxResponseBody; import com.mkyong.web.model.SearchCriteria; import com.mkyong.web.model.User; @RestController public class AjaxController { List

users; // @ResponseBody, not necessary, since class is annotated with @RestController // @RequestBody - Convert the json data into object (SearchCriteria) mapped by field name. // @JsonView(Views.Public.class) - Optional, filters json data to display. @JsonView(Views.Public.class) @RequestMapping(value = "/search/api/getSearchResult") public AjaxResponseBody getSearchResultViaAjax(@RequestBody SearchCriteria search) { AjaxResponseBody result = new AjaxResponseBody(); if (isValidSearchCriteria(search)) { List

users = findByUserNameOrEmail(search.getUsername(), search.getEmail()); if (users.size() > 0) { result.setCode("200"); result.setMsg(""); result.setResult(users); } else { result.setCode("204"); result.setMsg("No user!"); } } else { result.setCode("400"); result.setMsg("Search criteria is empty!"); } //AjaxResponseBody will be converted into json format and send back to the request. return result; } private boolean isValidSearchCriteria(SearchCriteria search) { boolean valid = true; if (search == null) { valid = false; } if ((StringUtils.isEmpty(search.getUsername())) && (StringUtils.isEmpty(search.getEmail()))) { valid = false; } return valid; } // Init some users for testing @PostConstruct private void iniDataForTesting() { users = new ArrayList

(); User user1 = new User("mkyong", "pass123", "[email protected]", "012-1234567", "address 123"); User user2 = new User("yflow", "pass456", "[email protected]", "016-7654321", "address 456"); User user3 = new User("laplap", "pass789", "[email protected]", "012-111111", "address 789"); users.add(user1); users.add(user2); users.add(user3); } // Simulate the search function private List

findByUserNameOrEmail(String username, String email) { List

result = new ArrayList

(); for (User user : users) { if ((!StringUtils.isEmpty(username)) && (!StringUtils.isEmpty(email))) { if (username.equals(user.getUsername()) && email.equals(user.getEmail())) { result.add(user); continue; } else { continue; } } if (!StringUtils.isEmpty(username)) { if (username.equals(user.getUsername())) { result.add(user); continue; } } if (!StringUtils.isEmpty(email)) { if (email.equals(user.getEmail())) { result.add(user); continue; } } } return result; } }






4.2 The “json data” will be converted into this object, via

@RequestBody

.


package com.mkyong.web.model; public class SearchCriteria { String username; String email; //getters and setters }

4.2 Create a dummy class for

@JsonView

, to control what should be returned back to the request.


package com.mkyong.web.jsonview; public class Views { public static class Public {} }

4.3 User object for search function. Fields which annotated with

@JsonView

will be displayed.


package com.mkyong.web.model; import com.fasterxml.jackson.annotation.JsonView; import com.mkyong.web.jsonview.Views; public class User { @JsonView(Views.Public.class) String username; String password; @JsonView(Views.Public.class) String email; @JsonView(Views.Public.class) String phone; String address; //getters, setters and contructors }

4.4 This object will be converted into json format and return back to the request.


package com.mkyong.web.model; import java.util.List; import com.fasterxml.jackson.annotation.JsonView; import com.mkyong.web.jsonview.Views; public class AjaxResponseBody { @JsonView(Views.Public.class) String msg; @JsonView(Views.Public.class) String code; @JsonView(Views.Public.class) List

result; //getters and setters }

The


@JsonViewbelongs to Jackson library, not Spring framework.

File Upload Spring MVC - Maven - JQuery - JavaScript - Ajax
File Upload Spring MVC - Maven - JQuery - JavaScript - Ajax

Preparations

I need to modify the SmartphoneController class by removing methods which are not required any more. This is a first step of AJAX integration.

//imports are omitted @Controller @RequestMapping(value="/smartphones") public class SmartphoneController { @Autowired private SmartphoneService smartphoneService; @RequestMapping(value="/create", method=RequestMethod.GET) public ModelAndView createSmartphonePage() { ModelAndView mav = new ModelAndView("phones/new-phone"); mav.addObject("sPhone", new Smartphone()); return mav; } @RequestMapping(value="/create", method=RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Smartphone createSmartphone(@RequestBody Smartphone smartphone) { return smartphoneService.create(smartphone); } @RequestMapping(value="/edit/{id}", method=RequestMethod.GET) public ModelAndView editSmartphonePage(@PathVariable int id) { ModelAndView mav = new ModelAndView("phones/edit-phone"); Smartphone smartphone = smartphoneService.get(id); mav.addObject("sPhone", smartphone); return mav; } @RequestMapping(value="/edit/{id}", method=RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Smartphone editSmartphone(@PathVariable int id, @RequestBody Smartphone smartphone) { smartphone.setId(id); return smartphoneService.update(smartphone); } @RequestMapping(value="/delete/{id}", method=RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Smartphone deleteSmartphone(@PathVariable int id) { return smartphoneService.delete(id); } @RequestMapping(value="", method=RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public List< Smartphone > allPhones() { return smartphoneService.getAll(); } @RequestMapping(value="", method=RequestMethod.GET) public ModelAndView allPhonesPage() { ModelAndView mav = new ModelAndView("phones/all-phones"); List< Smartphone > smartphones = new ArrayList< Smartphone >(); smartphones.addAll(allPhones()); mav.addObject("smartphones", smartphones); return mav; } }

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.
  • The second type performs CRUD operations (REST methods)

Project Dependencies


4.0.0


com.mkyong


spring4-mvc-maven-ajax-example
war
1.0-SNAPSHOT


spring4 mvc maven ajax example

1.8


4.2.2.RELEASE


2.6.3


1.1.3


1.7.12


1.2


3.1.0



org.springframework


spring-webmvc


${spring.version}




commons-logging


commons-logging







com.fasterxml.jackson.core


jackson-core


${jackson.version}




com.fasterxml.jackson.core


jackson-databind


${jackson.version}





javax.servlet


jstl


${jstl.version}





org.slf4j


jcl-over-slf4j


${jcl.slf4j.version}




ch.qos.logback


logback-classic


${logback.version}






javax.servlet


javax.servlet-api


${servletapi.version}


provided




org.apache.maven.plugins


maven-compiler-plugin


3.3


${jdk.version}

${jdk.version}


org.eclipse.jetty


jetty-maven-plugin


9.2.11.v20150529



10



/spring4ajax



org.apache.maven.plugins


maven-eclipse-plugin


2.10



true


true


2.0


spring4ajax


org.apache.maven.plugins


maven-war-plugin


2.6



false


org.wildfly.plugins


wildfly-maven-plugin


1.1.0.Alpha5



127.0.0.1
9990
admin
admin
spring4ajax.war

Spring 4 MVC Ajax JQuery Example - Spring MVC Tutorial for beginners
Spring 4 MVC Ajax JQuery Example - Spring MVC Tutorial for beginners

jQuery $.get() Method

The

$.get()

method requests data from the server with an HTTP GET request.

Syntax:

The required URL parameter specifies the URL you wish to request.

The optional callback parameter is the name of a function to be executed if the request succeeds.

The following example uses the

$.get()

method to retrieve data from a file on
the server:

Example

$.get("demo_test.asp", function(data, status){

alert("Data: " + data + "\nStatus: " + status);

});

});

The first parameter of

$.get()

is the URL we wish to request ("demo_test.asp").

The second parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.

Tip: Here is how the ASP file looks like ("demo_test.asp"):

response.write("This is some text from an external ASP file.")

%>

jQuery $.post() Method

The

$.post()

method requests data from the server using an HTTP POST request.

Syntax:

The required URL parameter specifies the URL you wish to request.

The optional data parameter specifies some data to send along with the request.

The optional callback parameter is the name of a function to be executed if the request succeeds.

The following example uses the

$.post()

method to send some data along with the
request:

Example

$.post("demo_test_post.asp",

name: "Donald Duck",

city: "Duckburg"

},

function(data, status){

alert("Data: " + data + "\nStatus: " + status);

});

});

The first parameter of

$.post()

is the URL we wish to request ("demo_test_post.asp").

Then we pass in some data to send along with the request (name and city).

The ASP script in "demo_test_post.asp" reads the parameters, processes them, and returns a result.

The third parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.

Tip: Here is how the ASP file looks like ("demo_test_post.asp"):

dim fname,city

fname=Request.Form("name")

city=Request.Form("city")

Response.Write("Dear " & fname & ". ")

Response.Write("Hope you live well in " & city & ".")

%>

Using Spring MVC + MySQL + Hibernate + JSP + AJAX (CRUD) [Step By Step] PART - 3 | CodeWithNaval
Using Spring MVC + MySQL + Hibernate + JSP + AJAX (CRUD) [Step By Step] PART - 3 | CodeWithNaval

Spring MVC server site POST methods example

In this section simple Spring backend that handle POST method requests is presented.


import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class EchoPostController { @RequestMapping(value = "/examples/echo-message", method = RequestMethod.POST) @ResponseBody public String sendPostMessage(@RequestParam("message") String message) { return message; } }

AJAX helps you to load data in the background and display it on the webpage, without reloading the complete webpage. It provides a smoother user experience while you are working with paging, sorting or filtering features in FlexGrid. This topic describes how to bind a FlexGrid at client side using an AJAX call.

This topic comprises the following steps:

The following image shows how the FlexGrid appears after completing the steps above:

Back to Top


Sale.cs. For more information on how to add a new model, see Adding Controls.


Sale.csmodel. We are using Sale class to represent sales order data in the database. Each instance of Sale object will correspond to a record in the FlexGrid control.

Sale.cs

Copy Code

using System; using System.Collections.Generic; using System.Linq; namespace AjaxDataBinding.Models { public class Sale { public int ID { get; set; } public DateTime Start { get; set; } public DateTime End { get; set; } public string Country { get; set; } public string Product { get; set; } public string Color { get; set; } public double Amount { get; set; } public double Amount2 { get; set; } public double Discount { get; set; } public bool Active { get; set; } public MonthData[] Trends { get; set; } public int Rank { get; set; } private static List

COUNTRIES = new List

{ "US", "UK", "Canada", "Japan", "China", "France", "German", "Italy", "Korea", "Australia" }; private static List

PRODUCTS = new List

{ "Widget", "Gadget", "Doohickey" }; ///

/// Get the data. ///

/// /// public static IEnumerable

GetData(int total) { var colors = new[] { "Black", "White", "Red", "Green", "Blue" }; var rand = new Random(0); var dt = DateTime.Now; var list = Enumerable.Range(0, total).Select(i => { var country = COUNTRIES[rand.Next(0, COUNTRIES.Count - 1)]; var product = PRODUCTS[rand.Next(0, PRODUCTS.Count - 1)]; var color = colors[rand.Next(0, colors.Length - 1)]; var startDate = new DateTime(dt.Year, i % 12 + 1, 25); var endDate = new DateTime(dt.Year, i % 12 + 1, 25, i % 24, i % 60, i % 60); return new Sale { ID = i + 1, Start = startDate, End = endDate, Country = country, Product = product, Color = color, Amount = Math.Round(rand.NextDouble() * 10000 - 5000, 2), Amount2 = Math.Round(rand.NextDouble() * 10000 - 5000, 2), Discount = Math.Round(rand.NextDouble() / 4, 2), Active = (i % 4 == 0), Trends = Enumerable.Range(0, 12).Select(x => new MonthData { Month = x + 1, Data = rand.Next(0, 100) }).ToArray(), Rank = rand.Next(1, 6) }; }); return list; } public static List

GetCountries() { var countries = new List

(); countries.AddRange(COUNTRIES); return countries; } public static List

GetProducts() { List

products = new List

(); products.AddRange(PRODUCTS); return products; } } public class MonthData { public int Month { get; set; } public double Data { get; set; } } }










HomeController.csfrom the Controllers folder.

C#

Copy Code

[HttpPost] public JsonResult GetData() { List

saleList = Sale.GetData(10).ToList

(); return Json(saleList); }


Index.htmlfrom View/Home folder.

HTML

Copy Code

We'll bind data to the control on the client side using JavaScript to make an AJAX call to the Action created in the HomeController.cs file. When we bind the grid at client-side in the Load function below, instead of assigning the result data of AJAX call to FlexGrid itemSource property, we should update the sourceCollection of FlexGrid's collectionView at client-side to retain the server-side features of collectionView. We have also added a code check for any errors in date values of JSON data.


Index.htmlfile inside the Home folder and copy the following JavaScript code.

Index.html

Copy Code

Index.html

Copy Code

jQuery - AJAX get() and post() Methods

The jQuery get() and post() methods are used to request data from the server with an HTTP GET or POST request.

References

About Author

Comments

i sending formdata to controller class. in controller how to access these data?

$(“button#submitMDRtable”).click(function(){var data = [];var minAmt, maxAmt, type, minCap, maxCap;$(“table tbody tr”).each(function(index) {minAmt = $(this).find(‘.minAmt’).text();maxAmt = $(this).find(‘.maxAmt’).text();type = $(this).find(‘.type’).text();minCap = $(this).find(‘.minCap’).text();maxCap = $(this).find(‘.maxCap’).text();//alert(minAmt+”–“+maxAmt+”–“+type+”–“+minCap+”–“+maxCap)//—->Form validation goes heredata.push({minAmt: minAmt,maxAmt: maxAmt,type: type,minCap: minCap,maxCap: maxCap});});submitFormData(data);console.log(data);});

function submitFormData(formData) {var url= ‘/mdrcharges’;alert(url);$.ajax({type: ‘POST’,data: formData,cache: false,processData: false,contentType: false,beforeSend: beforeSendHandler,url: url,success: function(result){if(result.success == true) {$(‘.alert-success’).show();$(‘.alert-danger’).hide();$(“#successmsg”).html(result.msg);setTimeout(function() {$(“.alert-success”).alert(‘close’);}, 10000);} else {$(‘.alert-danger’).show();$(‘.alert-success’).hide();$(“#error”).html(result.msg);setTimeout(function() {$(“.alert-danger”).alert(‘close’);}, 10000);}}});}

OK. This is an easy example, and everyone saw it a hundred times. But tell us what do you will do if you have here is a JSON:

{“abc”:{“sr”:”ok”,”citi”:[{“id”:”c2″,”value”:”london”},{…}…,{…}]}}

etc ?

Just send a POST request, along with your JSON data.

Spring 4 MVC Ajax Hello World Example

In this tutorial, we will show you how to create a Spring MVC web project and submit a form via Ajax.

Technologies used :

  1. Spring 4.2.2.RELEASE
  2. Jackson 2.6.3
  3. Logback 1.1.3
  4. jQuery 1.10.2
  5. Maven 3
  6. JDK 1.8
  7. Tomcat 8 or Jetty 9
  8. Eclipse 4.5
  9. Boostrap 3

P.S If the Jackson library is found in the project classpath, Spring will use Jackson to handle the json data to / from object conversion automatically.

Try this – Spring Boot Ajax example

Spring Boot AJAX  jQuery CRUD | CREATE  | READ | UPDATE | DELETE
Spring Boot AJAX jQuery CRUD | CREATE | READ | UPDATE | DELETE

Common Issues and Solutions

Debugging Ajax Issues in Spring MVC

When working with Ajax requests in Spring MVC, it is common to encounter issues related to the request not being sent or received properly. Here are some common issues and solutions:

  • Incorrect URL: Ensure that the URL in the Ajax request matches the URL in the Spring MVC controller. Check for any typos or missing slashes in the URL.
  • Missing Request Parameters: Check if all the required request parameters are being sent in the Ajax request. Use the browser’s developer tools to inspect the request and response headers and data.
  • Cross-Origin Resource Sharing (CORS): If the Ajax request is being sent from a different domain than the one hosting the Spring MVC application, then CORS restrictions may apply. Check if the server is configured to allow CORS requests.

Optimizing JSON Response

Sending JSON data in Spring MVC can be optimized to improve the performance of the application. Here are some tips to optimize the JSON response:

  • Minimize the JSON payload: Only send the required data in the JSON response. Remove any unnecessary data to reduce the payload size.
  • Use GZIP compression: Compress the JSON response using GZIP compression to reduce the payload size and improve the response time.
  • Use caching: Cache the JSON response on the client-side or server-side to reduce the number of requests and improve the response time.

By following these tips, we can optimize the JSON response and improve the performance of the Spring MVC application.

jQuery Ajax

In JSP, create a simple search form and send the form request with jQuery

$.ajax

.


<%@page session="false"%> <%@taglib prefix="spring" uri="http://www.springframework.org/tags"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

Search Form



Spring Boot-Ajax: Thêm, hiển thị danh sách
Spring Boot-Ajax: Thêm, hiển thị danh sách

You just add new Person

" + "Name: " + data.name + "
" + "Age: " + data.age; $("#ajax-response").html(result); }, error : function(e) { console.log("ERROR: ", e); } }); } function searchViaAjax() { var name = $("#query").val(); $.ajax({ type : "GET", contentType : "application/json", url : "${home}home/search/", data : { name : name }, dataType : 'json', timeout : 100000, success : function(data) { console.log("SUCCESS: ", data); if (data != null) { var result = "

You just search Person: " + data.name + "

"; $("#ajax-response").html(result); } else { var result = "

No person found

"; $("#ajax-response").html(result); } }, error : function(e) { console.log("ERROR: ", e); } }); }



5)Demo
Bật terminal hoặc lên, đưa con trỏ vào vị trí của project và gõ lệnh

mvn jetty:run

**5.1) Nhập tên và tuổi **

**5.2) Kết quả ajax trả về từ server **

Ta đã sử dụng HTTP method GET nhưng dữ liệu vẫn k bị hiển thị lên url => việc nói POST bảo mật hơn GET vì dữ liệu không được đưa lên url là chưa đúng !

How to call Rest Api by using Javascript AJAX in Spring Boot | Spring MVC
How to call Rest Api by using Javascript AJAX in Spring Boot | Spring MVC

jQuery AJAX Reference

For a complete overview of all jQuery AJAX methods, please go to our jQuery AJAX Reference.

POST request using AJAX by making Custom HTTP library

The task is to show how the

XMLHttpRequest

can be used to

POST

data to an API by making custom HTTP library. We will be taking a fake API which will contain Array of objects as an example and from that API we will show to

POST

data by

XMLHttpRequest

method by making a custom HTTP library.

Used API: https://jsonplaceholder.typicode.com/posts
What is Ajax?
Ajax

or Asynchronous JavaScript and

XML

is used to communicate with the server without refreshing the web page and thus increasing the user experience and better performance. To read more about

Ajax

click on

https://www.geeksforgeeks.org/ajax-introduction/.
Prerequisites:

Only the basic knowledge of HTML, CSS, and JavaScript is required to go.

Note:

First make a HTML file and add the HTML markup according to the requirement. In the bottom of the body tag attach two scripts file as library.js and app.js in the same order.

Steps required to make library.js File:

  1. In library.js file, make a function easyHTTP to initialize a new XMLHttpRequest() method.
  2. Set easyHTTP.prototype.post to a function which contains three parameters ‘url’, data and callback.
  3. Now open an object using this.http.open function. It takes three parameters, the first one is request type (GET or POST or PUT or DELETE), second is the URL for the API and last one is a boolean value (true means asynchronous call and false means synchronous call).
  4. Now we will use onload function to display the data. But before that first we need to set content-type with this.http.setRequestHeader method and also assign this keyword to self to have scope of this keyword into onload function. The onload function is executed after the API call is done. This function will run a callback function which has two arguments as error and response text.
  5. Last step is to send the request using the send() function. It should be noted that send() function needs to send data after converting object data to string using JSON.stringify(data).

Steps required to make app.js File:

  1. First of all instantiate easyHTTP with new keyword.
  2. Create a custom data(object) to post.
  3. Pass URL, data and a callback function in post prototype function.
  4. The callback function contains two arguments error to print if any error occurs and response to get the actual response.

Filename: index.html


html


lang


"en"


head


meta


charset


"UTF-8"


meta


name


"viewport"


content


"width=device-width, initial-scale=1.0"


title


>POST request


title




head


body


h1


POST request using xmlhttpRequest/Ajax


by making custom HTTP library.




h1


script


src


"library.js"


>


script


script


src


"app.js"


>


script




body




html

Filename: app.js


const http =


new


easyHTTP;


const data = {


title:


'Custom HTTP Post'


body:


'This is a custom post data'


};


http.post(


data,


function


(err, post) {


if


(err) {


console.log(err);


else


console.log(post);


});

Filename: library.js


function


easyHTTP() {


this


.http =


new


XMLHttpRequest();


easyHTTP.prototype.post =


function


(url, data, callback) {


this


.http.open(


'POST'


, url,


true


);


this


.http.setRequestHeader(


'Content-type'


'application/json'


);


let self =


this


this


.http.onload =


function


() {


callback(


null


, self.http.responseText);


this


.http.send(JSON.stringify(data));

Output:

Open your

index.html

file in any browser and open its console by

right click->Inspect element->console

. Hence you will see the below result.

Note:

It contains one additional key-value pair as ‘id’ 101. Don’t worry about this as this is created by default.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Last Updated :
18 Jul, 2020

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

In this article, we will discuss how to implement AJAX and JSON in a Spring MVC application. AJAX is a powerful tool for creating dynamic web applications by allowing data to be loaded asynchronously from a server without requiring a page refresh. JSON, or JavaScript Object Notation, is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate.

In a Spring MVC application, AJAX can be used to send requests to a server and retrieve data in JSON format. This allows for a more responsive user interface and reduces the amount of data that needs to be transferred between the client and server. By using AJAX and JSON in combination with Spring MVC, we can create web applications that are both powerful and efficient.

In this article, we will provide a step-by-step guide on how to implement AJAX and JSON in a Spring MVC application. We will cover everything from setting up the necessary dependencies to creating the controller and view components. By the end of this article, you will have a solid understanding of how to use AJAX and JSON in your Spring MVC applications.

Keywords searched by users: spring mvc ajax post example

How To Use Ajax And Jquery In Spring Web Mvc (.Jsp) Application • Crunchify
How To Use Ajax And Jquery In Spring Web Mvc (.Jsp) Application • Crunchify
Code-With-The-Flow: Jquery Ajax Requests In Spring Mvc Example
Code-With-The-Flow: Jquery Ajax Requests In Spring Mvc Example
Asp.Net Core Mvc Ajax Form Requests Using Jquery-Unobtrusive | Software  Engineering
Asp.Net Core Mvc Ajax Form Requests Using Jquery-Unobtrusive | Software Engineering
Javascript - Ajax Post Formdata Throw Exception In Spring Mvc - Stack  Overflow
Javascript – Ajax Post Formdata Throw Exception In Spring Mvc – Stack Overflow
Jquery Ajax Call To Mvc Controller With Parameters - Sensible Dev
Jquery Ajax Call To Mvc Controller With Parameters – Sensible Dev
How To Integrate Jquery Ajax Post/Get & Spring Mvc | Spring Boot | Java  Techie - Youtube
How To Integrate Jquery Ajax Post/Get & Spring Mvc | Spring Boot | Java Techie – Youtube
Problem Passing A Record Size From Ajax To Controller In Asp Net Core 5 Mvc  - Microsoft Q&A
Problem Passing A Record Size From Ajax To Controller In Asp Net Core 5 Mvc – Microsoft Q&A
Spring Mvc Jquery Ajax Example: Hướng Dẫn Thực Hành - Hanoilaw Firm
Spring Mvc Jquery Ajax Example: Hướng Dẫn Thực Hành – Hanoilaw Firm
Part 5 # Spring Mvc Application With Ajax | Ashok It - Youtube
Part 5 # Spring Mvc Application With Ajax | Ashok It – Youtube
Get And Post Calls To Controller'S Method In Mvc
Get And Post Calls To Controller’S Method In Mvc
Spring Mvc Ajax Hello World Example - Kiến Thức Cơ Bản Http Và Ajax
Spring Mvc Ajax Hello World Example – Kiến Thức Cơ Bản Http Và Ajax
How To Use Ajax And Jquery In Spring Web Mvc (.Jsp) Application • Crunchify
How To Use Ajax And Jquery In Spring Web Mvc (.Jsp) Application • Crunchify
Code Example - How To Make Ajax Calls With Java Spring Mvc - Analytics Yogi
Code Example – How To Make Ajax Calls With Java Spring Mvc – Analytics Yogi
Update Data[Put] Using Java Web Service And Jquery Ajax - B2 Tech
Update Data[Put] Using Java Web Service And Jquery Ajax – B2 Tech
Using Jquery Ajax To Send Post Requests In Asp.Net Core
Using Jquery Ajax To Send Post Requests In Asp.Net Core
Spring 3 Mvc Autocomplete With Jquery & Json Tutorial & Example
Spring 3 Mvc Autocomplete With Jquery & Json Tutorial & Example
Spring Boot Ajax Jquery Example - Learning To Write Code For Beginners With  Tutorials
Spring Boot Ajax Jquery Example – Learning To Write Code For Beginners With Tutorials
Demo Submit Form With Ajax In Spring Mvc - Youtube
Demo Submit Form With Ajax In Spring Mvc – Youtube
Using Spring Mvc + Mysql + Hibernate + Jsp + Ajax (Crud) [Step By Step]  Part - 3 | Codewithnaval - Youtube
Using Spring Mvc + Mysql + Hibernate + Jsp + Ajax (Crud) [Step By Step] Part – 3 | Codewithnaval – Youtube
Spring Mvc - Multiple File Upload With Progress Bar In Ajax And Jquery
Spring Mvc – Multiple File Upload With Progress Bar In Ajax And Jquery
Spring Mvc Multiple File Upload With Progress Bar In Ajax And Jquery
Spring Mvc Multiple File Upload With Progress Bar In Ajax And Jquery
Github - Stevehanson/Spring-Mvc-Ajax: Sample Spring Mvc Application  Demonstrating Json Ajax Requests With Java Spring Mvc Back-End.
Github – Stevehanson/Spring-Mvc-Ajax: Sample Spring Mvc Application Demonstrating Json Ajax Requests With Java Spring Mvc Back-End.

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *