Search code examples
liferay-aui

how to halt form submission in on submit event of aui script


This is my aui script. After going to success part the status variable is set to 0. But after this the condition if(status == 0) is not executed inside the block if(starttime.length > 0 || endtime.length > 0).

  A.one('#<portlet:namespace/>addBooking').on('submit', function(event) {
    var roomIndex =A.one("#<portlet:namespace/>roomIndex").get('value');
    var bookingdate =A.one("#<portlet:namespace/>bookingdate").get('value');
    var starttime =A.one("#<portlet:names`enter code here`pace/>starttime").get('value');
    var endtime =A.one("#<portlet:namespace/>endtime").get('value');
    var status=1;
    if(starttime.length > 0 || endtime.length > 0) {
        A.io.request('${bookingValidationURL}',{
             dataType: 'json',
             method: 'POST',
             data: { <portlet:namespace/>roomIndex: roomIndex,
                 <portlet:namespace/>starttime: starttime,
                 <portlet:namespace/>endtime: endtime,
                      },
             on: {

             success: function() {

                  var data = this.get('responseData');

                  if(data==null){
                      status="0";
                  }

                }

             }

        });



 if(status==0){   // this condition is not checked when status is 0 in success part   
      event.halt();
    }   
}

});

Solution

  • Ajax is asynchronous.. so for doing synchronous task we have to set sync=true in ajax function...so for above code

      A.io.request('${bookingValidationURL}',{
             dataType: 'json',
             method: 'POST',
             sync : true, // this is the change
             data: { <portlet:namespace/>roomIndex: roomIndex,
                 <portlet:namespace/>starttime: starttime,
                 <portlet:namespace/>endtime: endtime,
                      },
             on: {
    
             success: function() {
    
                  var data = this.get('responseData');
    
                  if(data==null){
                      status="0";
                  }
    
                }
    
             }
    
        });