Using @PathVariable in Spring MVC can cause issues with Ajax functionality

I am facing an issue where I need to incorporate an ajax function on a specific page, but it seems to be not working with @PathVariable in spring mvc.
page1.jsp

<li><a href="page2/sss">WatchEvent</a></li>

1) It is working properly. In the controller:

@RequestMapping(value = "page2/{id}", method = RequestMethod.GET)
public ModelAndView WatchEvent(@PathVariable("id")String id) {
System.out.println("In getplayback :"+id);   
 List<modelone> getdetails=Serviceone.detailsToUser(id);    
System.out.println("In getplayback from db:"+getdetails);    

return new ModelAndView("page2","getdetails",getdetails);    
}    

The details are successfully sent to page2.
2) However, it is not functioning correctly.
Page2.jsp

<script type="text/javascript">
 $(document).ready(function() {
    alert("ready");
    var fun="event";

    var savedata = {    
            action:fun,             
            };
     $.ajax({
         url : "events",
         type : "POST",
         datatype:"json",
         data: savedata,
            error:function(){
                alert("Error");
            },
            success: function() { 
                alert("success");   

            }    
         });
});
</script> `

However, it fails to reach the following controller.

@RequestMapping(value="events",method=RequestMethod.POST)
 public @ResponseBody  String GetSomeEvents(){    
System.out.println("In someevent********************");    
String todayDate = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
System.out.print("today"+todayDate);
List<modelone> getlist=Serviceone.getSomeEvents();   

    return "success";   
 }

The result is an alert error message.

When inspecting through firebug: POST ......./page2/events

The error displayed is: 405 Method Not Allowed

Answer №1

Make sure to update your action in the following way:

@RequestMapping(value = "events", method = RequestMethod.POST)
public @ResponseBody String GetSomeEvents(@RequestParam String action) {    
    System.out.println("In someevent********************");    
    String todayDate = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
    System.out.print("today" + todayDate);
    List<modelone> getlist = Serviceone.getSomeEvents();   

    return "success";   
}

To ensure correctness, include your request parameters as part of your action parameters.

Answer №2

Include this code snippet above the ajax request:

$.ajaxSetup({ 
    scriptCharset: "utf-8", 
    contentType: "application/x-www-form-urlencoded; charset=UTF-8"
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The controller remains unresponsive when attempting to activate the button on the webpage

I'm a beginner in frontend development and I'm currently working on a website that uses Thymeleaf. On this website, there is a div block with a button. Please take a look at the HTML code below, specifically the button at the last three rows. &l ...

Image not being updated by AJAX HTTPHandler

My application is designed to display an image based on the user ID provided. The image tag is placed within an update panel in an AJAX TabContainer control, with the ImageUrl set to "~/ImageHandler.ashx". The ImageHandler.ashx retrieves the user's ID ...

The commandButton utilizing f:ajax functionality fails to trigger the action upon form submission

I am facing an issue with enabling/disabling a commandButton based on a checkbox selection. Initially, the command button is disabled and upon checking the checkbox, it should become enabled. However, I have observed that even though the button appears ena ...

What is the best method for incorporating a query in Ajax code while also passing parameter data?

I am currently working on a project in Laravel that involves using a create form with AJAX. After the form is completed, I need to merge data from two tables together within the AJAX code so that I can make specific selections. Here is an example of the AJ ...

Executing JavaScript code from an external link

Currently, I am in the process of developing a horizontal parallax website. The functionality is working seamlessly; when I click on the menu, the slides smoothly transition horizontally and display the corresponding content. However, I have encountered a ...

Distinguishing Between Angular and Ajax When Making Requests to a NodeJS Server

Trying to establish communication between an Angular client and a NodeJS server. Previous method using JQuery $.ajax({ url: "/list", type: "POST", contentType: "application/json", dataType: "json", success: function(data) { console.log("Data ...

When attempting to use Ajax, the operation fails; however, if I directly access the URL,

When using firebug, I attempted to make the following AJAX call: var rootUrl = 'http://172.24.105.22:8080/geoserver/Chennai_Sub/ows'; var defaultParameters = { service: 'WFS', version: '1.0.0', request: 'Get ...

Ways to turn off .removeClass()

Encountering an issue with jquery-2.1.4.js. Upon integrating a layerslider into my website, the script modified div classes. Attempted using older versions of the script without success. Currently have classes as follows: <a href="#" class="col-md-3 ...

From Jquery to PHP to MySQL: Creating dynamic forms with variable fields

I am facing an issue with a multi-page form that uses multiple MySQL tables to store entered values. One of the pages contains a form that should allow users to click a + button to add extra lines for additional information. The user can add any number of ...

Ensuring the validity of a file input through AJAX in a form built with Laravel

I am facing an issue with validating an image field in a Laravel form using AJAX. The field always appears to be empty even after selecting a file. How can I use ajax validation to check if the file input is empty or not? Here is the form code: {{ Form:: ...

Expanding list - Using individual toggles to expand and collapse multiple list items

I stumbled upon an interesting jquery script that allows for a collapsible sub menu within a list. After implementing this code: $('.menu-item-has-children').prepend('<a id="fa-menu" href="#"><i class="fa fa-plus"></i>< ...

Having trouble sending the information to Parse.com using the website

I am a beginner with the Parse database and I am currently working on implementing a code that allows users to sign up, with their information stored in the Parse database. However, I am encountering an issue where the values are not uploading as expected. ...

Using Javascript and jQuery to create an infinite animated background change with fade effect

I am struggling to figure out how to automatically change the background of a div every 3 seconds, looping through a series of images. I posted about this issue before but didn't receive much help. function animate() { change1(); change2() ...

Displaying HTML Tags in jQuery JSON Response

Whenever I execute the following code: <html> <head> </head> <body> <?php $value = isset($_GET['send_request']) ? $_GET['send_request'] : false ; if ($value) { echo $value; return ...

Encountering Issues with Implementing Bootstrap Select for Multiple Selections

I have implemented BootStrap-Select for multi-selection functionality. When selecting multiple options from a list of 10, I noticed that if I select a 4th option, another selected option gets randomly unselected. To address this issue, I am using the follo ...

Determine if the user's request to my website is made through a URL visit or a script src/link href request

Presently, I am working on developing a custom tool similar to Rawgit, as a backup in case Rawgit goes down. Below is the PHP code I have created: <?php $urlquery = $_SERVER['QUERY_STRING']; $fullurl = 'http://' . $_SERVER['SE ...

Enhancing Django's login form validation with AJAX

I'm trying to implement an AJAX login feature in Django. The goal is to check if the user has provided the correct username and password. Take a look at my current code setup: urls.py urlpatterns = [ url(r'^$', views.home_view, name=&a ...

Is it possible to identify when an element has scrolled out of view just one time?

In an attempt to determine if an element has been scrolled out of view, I have implemented the following code: $(window).bind('scroll', function(){ var $btn = $('#intro div.summary a[href=#top]'); if($(window).scrollTop() > ...

Timing problem with the getJSON function in jQuery

My program seems to be skipping the result of a JSON call. Is there a way I can implement a closure function here or make the program wait for the JSON call to return? function checkIfUsernameIsDuplicate(username) { var functionName = "get_username"; ...

Exploring the Relative Positioning of Two div Elements

Can anyone assist me with finding and comparing the positions of two '<div>' tags using an if statement? I stumbled upon a suggestion in my research, which goes like this: var obstacle = $('#obstacle').css('left', &apo ...