Request problem via ajax

Asked

Viewed 73 times

0

I have a JSP page to login to my system, but when trying to make a request via ajax to authenticate me, the form does not seem to be being sent correctly, as the redirection is done to the login page itself.

Ajax code:

$( document ).ready( function()
{
    $( '#submitLogin' ).click( function( e )
    {                        
        e.preventDefault();

        $.ajax
        ({
            type: 'POST',
            url: '/system/users?parameter=login',
            data: $( '#loginForm' ).serialize(),
            success: function( msg ) 
            {
                if ( $.trim( msg ) === "ERROR" )
                {
                    loginErrorAlert();

                    $( '#userLogin' ).val( "" );
                    $( '#userPassword' ).val( "" );

                    $( '#userLogin' ).focus();
                }
            }
        });
    });
});

Post method:

protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
    String parameter = request.getParameter( "parameter" );

    if ( parameter.equals( "login" ) ) 
    {   
        try
        {
            if ( LoginController.getInstance().authenticateUser( request, response ) )
            {                   
                response.sendRedirect( "home.jsp" );
            }

            else
            {                    
                response.setContentType( "text/plain" );
                response.setCharacterEncoding( "UTF-8" );

                response.getWriter().println( "ERROR" );
            }
        }

        catch ( Exception e )
        {
            System.out.println( e.toString() );
        }
    }
}

web xml.:

<servlet>
    <servlet-name>Users</servlet-name>
    <servlet-class>servlet.Users</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>Users</servlet-name>
    <url-pattern>/users</url-pattern>
</servlet-mapping>

1 answer

1


Has a if checking that the message is equal to ERROR, but there is no action if it is different from that. You can put a window.location.href='pagina que deseja'. You won’t be able to redirect with this code.

 if ( LoginController.getInstance().authenticateUser( request, response ) )
 {                   
    response.sendRedirect( "home.jsp" );
  }

Instead do response.getWriter().println( "home.jsp" );

And in javascript:

 if ( $.trim( msg ) === "ERROR" )
 {
     loginErrorAlert();

     $( '#userLogin' ).val( "" );
     $( '#userPassword' ).val( "" );

     $( '#userLogin' ).focus();

 }elseif($.trim( msg ) === "home.jsp")
 {
     window.location.href= $.trim( msg );
 }

A better solution would be to use the http response codes, and if it went wrong return a 403 for example. And with that you would add a function error{ //código }, shortly after the success in javascript

Browser other questions tagged

You are not signed in. Login or sign up in order to post.