简体   繁体   中英

AJAX POST (JQuery) to PHP is not working. How can I fix it?

I'm facing the POST issue for a while and I still can't solve it. The AJAX doesn't send data (i think) to my php file login.php in php folder. I'm still getting error, that index usernameData is undefined/does not exist.

Uncaught TypeError: Cannot use 'in' operator to search for '119' in <br />
<b>Notice</b>:  Undefined variable: mainusername in <b>/var/www/html/php/login.php</b> on line <b>17</b><br />
[]
    at s (jquery.min.js:2)
    at Function.each (jquery.min.js:2)
    at Object.success (login.js:131)
    at j (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at x (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)

sometimes it also returns nothing, just a blank console log.

Informations:

  • im using apache2, ubuntu 21.04, php7.4
  • php.ini file: post_max_size = 2M , upload_max_filesize = 8M
  • login.js file:
      $.ajax({
          type: "POST",
          url: "/php/login.php",
          data: {
            usernameData: "DaRealAdalbertBro",
            passwordData: "123"
          },
          cache: false,
          success: function(datas){
            $.each(datas, function(idx, loginData){
              console.log(loginData.name)
              console.log(loginData.password)
            });
          },
          error: function(xhr, status, error) {
          console.error(xhr.responseText);
          console.error(status);
          console.error(error);
          }
      });
  • login.php file in php folder:
    <?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$servername = "AA";
$database = "BB";
$username = "CC";
$password = "DD";

$conn = new mysqli($servername, $username, $password, $database);

if ($conn->connect_error) {
  console.log("Connection failed: " . $conn->connect_error);
}


$mainusername = $_POST['usernameData'];
$mainpassword = $_POST['passwordData'];

$sql = "SELECT * FROM user WHERE username='$mainusername'";
$results = mysqli_query($conn, $sql);

$rawlogindata = array();
while ($row = mysqli_fetch_array($results)) {
  $arrayData = array(
    "name"         => $row['username'],
    "password"          => $row['pass']
  );
  $rawlogindata[] = $arrayData;
}

echo json_encode($rawlogindata);

mysqli_close($conn)
?>
  • my login.html form:
<form class="sign-in-form" action="login.php" method="POST" id="logform" autocomplete="off">
    
    <h2 class="title">Log in</h2>

    <div class="input-field">
        <i class="fas fa-user"></i>
        <input type="text" name="usernameData" placeholder="Username" minlength="4" maxlength="24" id="logusername" onfocusout="checkInputsUsernameLogin()" onkeyup="cleanUsername('logusername')" onkeydown="cleanUsername('logusername')" />
        <i class="erroricon fas fa-exclamation-circle"></i>
        <small class="form-login-message">Unknown Error - please contact the support.</small>
    </div>
    <div class="input-field">
        <i class="fas fa-lock"></i>
        <input type="password" name="passwordData" placeholder="Password" onpaste="return false;" ondrop="return false;" minlength="8" maxlength="255" id="logpassword" onfocusout="checkInputsPasswordLogin()" onkeyup="cleanPassword('logpassword')" onkeydown="cleanPassword('logpassword')" />
        <i class="erroricon fas fa-exclamation-circle"></i>
        <small>Unknown Error - please contact the support.</small>
    </div>

    <input type="submit" value="Login" class="btn solid" name="loginbutton" />
    

    <p class="social-text">Or Login with social platforms</p>


    <div class="social-media">
        <a href="#" class="social-icon">
            <i class="fab fa-discord"></i>
        </a>
        <a href="#" class="social-icon">
            <i class="fab fa-twitter"></i>
        </a>
        <a href="#" class="social-icon">
            <i class="fab fa-google"></i>
        </a>
        <a href="#" class="social-icon">
            <i class="fab fa-github"></i>
        </a>
    </div>
</form>
  • Also, if I change the $mainusername in /php/login.php to just a string, it works. Example: $mainusername = "DaRealAdalbertBro";

Thanks for all your responses, Adalbert.

You have used $mainusername in login.php but you haven't declared that. I guess you were trying to get the data from the form and select it. Your SQL Query is wrong. Please update that.

It's a while, but I accidentally solved this problem a few days ago. On my VPS, I have a .htaccess file, where is:

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=302,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]

This code is removing .php suffix of the web URL. The problem was, that I was sending these data to file with the suffix. So the easy fix is rewrite a action="login.php" to just action="login" , if you have this file as well.

Thank you for all responses and tips,
I hope that this solution will help to someone else,
Adalbert

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