0

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

Rudu
  • 15,682
  • 4
  • 47
  • 63
  • Need more debugging details. Is request being made? have you tried using ajax error handler? Without more details all we can do is make guesses and ask you a lot of questions – charlietfl Aug 23 '20 at 21:46
  • Add [a `dataType`, and add a JSON `Content-Type`](https://stackoverflow.com/questions/19155192/jquery-ajax-call-to-php-script-with-json-return) header. – Don't Panic Aug 23 '20 at 22:39

2 Answers2

0

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);
                }
            }

        });
DCodeMania
  • 1,027
  • 2
  • 7
  • 19
-1

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');
                }
            });

});
  • 1
    Setting `window.location ='/somepath'` is effectively the same as doing `window.location.href ='/somepath'`. Both approaches work – charlietfl Aug 23 '20 at 21:48
  • Indeed. Both are possible. I just never use it as window.location. The href variant is more explicit. But it doesn't change the point. The question was to get ajax to work, which I wrote :) – Vladimir Bakulin Aug 23 '20 at 22:02
  • Well I don't understand either why you are removing contentType and disabling processData. Can't send a post without content-type – charlietfl Aug 23 '20 at 22:03
  • Thanks but i want the error from the server side like incorrect password, or user not found to show on the page for user to see it. then if no error it should redirect to the index – UCode Tech Aug 24 '20 at 10:34
  • @UCodeTech, then it depends on the response you get from the server. For example if you get a json like `{"success": true, "data": ["some data"]}`, you can write `if (response.success) window.location.href = '/';` Then in case of success, it will redirect the user to the main page – Vladimir Bakulin Aug 25 '20 at 04:10