Viewed   63 times

Just having a few issues submitting a login form via ajax, I am primarily a PHP developer, I don't use Jquery + Ajax all that often with PHP.

At the moment If i check the firebug POST data after the form has been submit it does appear to get the username and password that have been added to the form, however the page just reloads regardless of whether an incorrect username and password are added or if they are correct and no session is created.

This is the form:

    <form id="loginform" method="post">
    Username: <input type="text" name="username" id="username" value="">

    Password: <input type="password" name="password" id="password" value="">

    <input type="submit" name="loginsub" id="loginsub" value="Login">
    </form>

This is the Ajax/Jquery:

    <script type="text/javascript">
    $(document).ready(function() {

    $('#loginform').submit(function() {

    $.ajax({
        type: "POST",
        url: '/class/login.php',
        data: {
            username: $("#username").val(),
            password: $("#password").val()
        },
        success: function(data)
        {
            if (data === 'Login') {
                window.location.replace('/user-page.php');
            }
            else {
                alert('Invalid Credentials');
            }
        }
    });

});

});
</script>

And this is the PHP:

    class Users {
 public $username = null;
 public $password = null;

 public function __construct( $data = array() ) {
     if( isset( $data['username'] ) ) $this->username = stripslashes(        strip_tags( $data['username'] ) );
     if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
 }

 public function storeFormValues( $params ) {
    $this->__construct( $params ); 
 }

 public function Login() {
     $success = false;
     try{
        $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); 
        $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";
                    $user = username;

        $stmt = $con->prepare( $sql );
        $stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
        $stmt->bindValue( "password", md5($this->password), PDO::PARAM_STR );
        $stmt->execute();

        $valid = $stmt->fetchColumn();

        if( $valid ) {
        $success = true;
                    session_start();


        session_regenerate_id();
        $_SESSION['user'] = $user['user'];
        session_write_close();
        echo ('Login');
        exit();

        }

        $con = null;
        return $success;
        }catch (PDOException $e) {
        echo $e->getMessage();
        return $success;
     }

 }

I guess it is not working because I am not calling the class and function, but I am not sure how to succesfully do so. I tried creating a controller page in between the 2 that would initiate the php class and function but to no avail.

Just to edit, the login does work correctly if I remove the ajax and just call the php page via the login form action.

Any ideas?

 Answers

4

whole issue is in jquery use this instead

$(document).ready(function() {
  $('#loginform').submit(function(e) {
    e.preventDefault();
    $.ajax({
       type: "POST",
       url: '/class/login.php',
       data: $(this).serialize(),
       success: function(data)
       {
          if (data === 'Login') {
            window.location = '/user-page.php';
          }
          else {
            alert('Invalid Credentials');
          }
       }
   });
 });
});
Tuesday, November 29, 2022
2

It's as secure as any other method of form submission would be to the same URL.

Saturday, August 6, 2022
1

I have found the solution. Here is what I added to my javascript,

<script>
    $(document).ready(function(){
        $('#_submit').click(function(e){
            e.preventDefault();
            $.ajax({
                type        : $('form').attr( 'method' ),
                url         : '{{ path("fos_user_security_check") }}',
                data        : $('form').serialize(),
                dataType    : "json",
                success     : function(data, status, object) {
                    if(data.error) $('.error').html(data.message);
                },
                error: function(data, status, object){
                    console.log(data.message);
                }
            });
        });
    });
</script>

And here is my onAuthenticationFailure method from my handler,

public function onAuthenticationFailure(Request $request, AuthenticationException $exception) {
    $result = array(
        'success' => false, 
        'function' => 'onAuthenticationFailure', 
        'error' => true, 
        'message' => $this->translator->trans($exception->getMessage(), array(), 'FOSUserBundle')
    );
    $response = new Response(json_encode($result));
    $response->headers->set('Content-Type', 'application/json');

    return $response;
}

I think that it was the URL from my Ajax method that was wrong. Thank you for your advices.

Saturday, October 1, 2022
 
4

I think you've got almost everything. The callback function you have under success needs an argument which stands for the results from search.php

     success: function(res) {
             goToByScroll("result");
             $('#result').html("<br><br><br><br><br><br><br><br><br><br><div class='center'><img src='img/loader.gif' /></div>").hide().fadeIn(2500, function() {
                 $('#result').html(res + "<br /><br /> Finished");
             });
         } 

res is everything outputted be search.php. Echo, stuff outside of php tags, etc Anything you'd see if you loaded search.php itself.

I don't know if you wanted 'Finished' to still be there. Take it out if you dont.

Tuesday, October 18, 2022
 
3

i think your problem may be in ajax code since you are using formData object . try append the message variable with it

$('#submit').on('click', function(){

  var fd = new FormData(this);
  fd.append('file',$('#file')[0].files[0]);
  fd.append('message ',$('#message').val());

  $.ajax({
    method:"POST",
    url:"<?php echo site_url('home/send_chat');?>",    
    data: fd,  
    cache: false,
    contentType: false,
    processData: false,   
    success: function(data){                 
      alert(data);
    },
    error: function(xhr, status, error) {
      alert(xhr.responseText);
    }  
  });
});
Saturday, November 12, 2022
 
malina
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :