0

The PHP code for login validation works properly when run from the html page by using form action but when run using ajax script it fails to load.

PHP code not involving database seems to run fine though.

JavaScript

< script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" > < /script> <
  script >
  $(document).ready(function() {
    $("#login").submit(function(event) { //Trigger on form submit
      $('#name + .throw_error').empty(); //Clear the messages first
      $('#success').empty();
      var postForm = { //Fetch form data
        'name': $('input[name=name]').val(),
        'password': $('input[name=password]').val() //Store name fields value
      };

      $.ajax({ //Process the form using $.ajax()
        type: 'POST', //Method type
        url: '.php', //Your form processing file url
        data: postForm, //Forms name
        dataType: 'json',
        success: function(data) {

          if (!data.success) { //If fails
            if (data.errors.name) { //Returned if any error from process.php
              $('.throw_error').fadeIn(1000).html(data.errors.name).append('<p>' + data.error + '</p>'); //Throw relevant error
              alert("Nope");
            }
          } else {
            $('#success').fadeIn(1000).append('<p>' + data.name + '</p>'); //If successful, than throw a success message
            alert("yes");
          }
        }
      });
      event.preventDefault(); //Prevent the default submit
    });
  }); < /script>

PHP Code

<?php
    $errors = array();
    $form_data = array();
   include("config.php");
   if (session_status() == PHP_SESSION_NONE) {
   session_start();}
        else{
      $_SESSION['ses']="Already in session":
       /* Write already in session code */
   }
   if($_SERVER["REQUEST_METHOD"] == "POST") {
      // username and password sent from form 

      $myusername = mysqli_real_escape_string($db,$_POST['username']);
      $mypassword = mysqli_real_escape_string($db,$_POST['password']);    

      $sql = "SELECT * FROM users WHERE user_name = '$myusername' and password = '$mypassword'";
      $result = mysqli_query($db,$sql);
      $row = mysqli_fetch_array($result,MYSQLI_ASSOC);


      $count = mysqli_num_rows($result);

      // If result matched $myusername and $mypassword, table row must be 1 row
        if (empty($_POST['name'])) { //Name cannot be empty
        $errors['name'] = 'Name cannot be blank';
    }

    if (!empty($errors)) { //If errors in validation
        $form_data['success'] = false;
        $form_data['errors']  = $errors;
    }
    else{
      if($count == 1) {
         $_SESSION['login_user'] = $myusername;

      }else {
         $error = "Your Login Name or Password is invalid";
         $_SESSION["error"] = $error;
      }
   }
   }
       echo json_encode($form_data);
?>
Punit
  • 11
  • 1
  • [Have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server?](http://jayblanchard.net/basics_of_jquery_ajax.html) – Jay Blanchard Feb 27 '17 at 18:39
  • **Never store plain text passwords!** Please use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). Make sure you ***[don't escape passwords](http://stackoverflow.com/q/36628418/1011527)*** or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Feb 27 '17 at 18:39
  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! [Don't believe it?](http://stackoverflow.com/q/38297105/1011527) – Jay Blanchard Feb 27 '17 at 18:39
  • Is this url in your jq.query a calid url at all?? '.php' - shouldn't there be for eg. 'index.php'? What is your php code file name? – brzuchal Feb 27 '17 at 18:41
  • Your code is insecure. You MUST not store pazswords in db you MUST hash it and compare hashes only! It's very dangerous to store plain password in db. Look for ´password_hash´ function in PHP – brzuchal Feb 27 '17 at 18:44
  • I left the url by mistake when i was editing in overflow, as for the password is it the problem behind the script not running coz i'm doing this for a better understanding and just keeping it simple – Punit Feb 28 '17 at 02:46

0 Answers0