简体   繁体   中英

Ajax not redirecting after a successful response from php

I am trying to redirect to Homepage from SignIn Page after the validation of user credentials is done. The response is working perfectly fine. On getting a successful response, I want to redirect to Homepage. I am using Javascript for client side and PHP on server side. but the success response is not getting to ajax.

Ajax call

$('#login-btn').click(function(e) {
if ($('#login-form')[0].checkValidity()) {
    e.preventDefault();

    $("#login-btn").html('<img src="images/tra.gif" /> Please Wailt..');
    if ($('#Lemail').val() == '') {
        $('#error-message').fadeIn().html('* Email is Required!');
        setTimeout(function() {
            $('#error-message').fadeOut('slow');
        }, 5000);
    } else if ($('#Lpassword').val() == '') {
        $('#error-message').fadeIn().html('* Please enter password!');
        setTimeout(function() {
            $('#error-message').fadeOut('slow');
        }, 5000);
    } else {
        $('#error-message').text('');
        $.ajax({
            url: 'actionlog.php',
            method: 'POST',
            data: $('#login-form').serialize() + '&action=login',
            success: function(response) {
                if (response === 'true') {
                    window.location = '../';
                } else {
                    $('#logAlert').html(response);
                }
            }

        });
    }
}
});

});

PHP code:

<?php
//Login Request
if (isset($_POST['action']) && $_POST['action'] == 'login') {
    if (Input::exists()) {
      $validate = new Validate();
      $validation = $validate->check($_POST, array(
        'email' => array('required' => true),
        'password' => array('required' => true)

      ));
      if ($validation->passed()) {
        $user = new User();
        //create Remember
        $remember = (Input::get('remember') === 'on') ? true : false;
        $login = $user->login(Input::get('email'), Input::get('password'), $remember);
        if ($login) {
          echo 'true';
        }
      }else{
        foreach ($validation->errors() as $error) {
          $user = new User();
          echo  $user->showMessage('danger',$error);

        }
        }
    }
      
}

please i need help

You have to trim your response....sometimes the string recieved from the server contains whitespace.....and that causes the problem to not redirect to other page.

$.ajax({
            url: 'actionlog.php',
            method: 'POST',
            data: $('#login-form').serialize() + '&action=login',
            success: function(response) {
                if ($.trim(response) === 'true') {
                    window.location = '../';
                } else {
                    $('#logAlert').html(response);
                }
            }

        });

Try to do it this way:

$.ajax({
            type: "POST",
            url: 'actionlog.php',
            data: $('#login-form').serialize()+'&action=login',
            dataType: 'json',
            beforeSend: function(){},
            success: function(response){
                window.location.href = '/';
            },
            error: function(){
                console.log('You got an error');
            }
        });

If you get a successful response from the server, this should work. This example implies that the server will return json , but you can indicate anything you like.

UPD: My bad. You can use both window.location and window.location.href . Also, in the above example I removed options

processData: false,
contentType: false,

because they are used if you send FormData . You might want to consider using FormData though and pass it to data :) which is very helpful when sending forms with files

With FormData it will look like this:

$(document).on('submit','.your-form-selector', function(e){
    e.preventDefault();

    var data = new FormData(this); // "this" is your form and includes all the form fields

    $.ajax({
                type: "POST",
                url: 'actionlog.php',
                data: data, // FormData goes here
                dataType: 'json',
                processData: false,
                contentType: false,
                beforeSend: function(){},
                success: function(response){
                    window.location.href = '/';
                },
                error: function(){
                    console.log('You got an error');
                }
            });

});

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