简体   繁体   中英

ajax form submitting but calling error function

This is a simple form which takes 2 dates from and to and I am submiiting those to values to server.

<form action="#" method="get">
<label for="from">From</label>
<input type="text" id="from"  name="fromDate">
<label for="to">to</label>
<input type="text" id="to"  name="toDate">

 <input type="button" value="Recv Amount" id="recv">
 </form>

and the following is the controller code

@RequestMapping("getPayments")
@ResponseBody
public void getPayments(HttpServletRequest request,Model uiModel)
{
    String toDate=request.getParameter("toDate");
    String fromDate=request.getParameter("fromDate");
    System.out.println(fromDate+" "+ toDate);
}

and this is js code

$('#recv').click(function(){
      var fromDate=$('#from').val();
      var toDate=$('#to').val();
      $.ajax({
          type: "GET", 
           url: url,  
              data:{"fromDate":fromDate,"toDate":toDate},
              dataType:"json",

         success: function( data ) {
             console.log('success');


         },
         error:function()
         {
             console.log('failed');
         }
        }); 
  });

when ever I hit the button I can see todate and from date in the server console (This means System.out.println(fromDate+" "+ toDate); is executed) but in the browser console failed is printed(this means console.log('failed'); is executed)

I do not have any error in browser console but the success function of ajax is never executed.

What could be the reason behind it?

jsfiddle

EDIT:

Based on the information provided issue is that data is expected the way you formed your success parameter. Since no data is returned (void method) it won't actually do anything.

Therefore you need to use:

statusCode: { 200: function() { alert( "success" ); } } 

Remove success and error as success won't work (no data being returned) and error will display (simply because no data is returned) and replace them with relevant status codes.

You are waiting for a JSON answer, but you are not returning anything. jQuery is going to give you an error. Remove 'dataType' from your ajax request or return a valid json object.

From jQuery documentation:

"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)

jQuery ajax query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM