Search code examples
phpajaxvariablesreturn

Returning a variable from PHP to AJAX


how can I return a variable from a PHP query to AJAXA. I want the user to be redirected to the user panel using javascript after successfully entering the login and password. The query in PHP was successfully written but Ajax does not return any results.

Code Javascript:

$(document).ready(function() {
  $("#btn-login").click(function() {
    const loginAuth = $("#login-auth").val();
    const passAuth = $("#pass-auth").val();
    $.ajax({
      type: "POST", //Request type
      url: "http://localhost/game/login.php",
      data: {
        loginAuth: loginAuth,
        passAuth: passAuth
      },
      cache: false,
      success: function(data) {
        console.log(data);
      }
    });
  });
});

Code PHP:

<?php
require ('connect.php');

session_start();

// If form submitted, insert values into the database.

if (isset($_POST['loginAuth'])) {

  // removes backslashes

  $username = stripslashes($_REQUEST['loginAuth']);

  // escapes special characters in a string

  $username = mysqli_real_escape_string($con, $username);
  $password = stripslashes($_REQUEST['passAuth']);
  $password = mysqli_real_escape_string($con, $password);

  // Checking is user existing in the database or not

  $query = "SELECT * FROM `users` WHERE login='$username'
    and password='" . md5($password) . "'";
  $result = mysqli_query($con, $query) or die(mysql_error());
  $rows = mysqli_num_rows($result);
  if ($rows == 1) {
    $_SESSION['username'] = $username;

    // Redirect user to index.php

    $arr = 'udało się';
    header("Location: panel.php");
  }
  else {
    $arr = false;
    header("Location: panelLogin.php");
  }
}
else {
}

echo json_encode($arr);
?>

Thank you very much for every help.


Solution

  • you cannot redirect the user from the php script that is being called from ajax call.

    because it will redirect but not on your browser instance but the ajax one.

    you need to redirect it from javascript.

    so you can do

    echo "true";
    

    instead of

    header("Location: panel.php");
    

    and echo "false"; // in case login failed

    as an example but you can print some json text and use more informative messages

    and you can check these values from ajax success function then you can do

    window.location.href = "the url you want to redirect to";