-1

i cant send a form data with ajax to php. It always refresh the page. Im using bootstrap modal to register form and i want to display error message (if have) on the top of form. Always refresh the page and if i again click to reg button to open the modal i see the error message. How i can do it without refresh the page? Any idea how can i do it?

form:

<?php echo display_error(); ?>
                                
<form  id="regform" class="form-signin" action="#" method="post">
                                
                                
<input type="text" id="username" class="form-control" placeholder="username" name="username" required autofocus>
                                
 <input type="email" id="email" class="form-control" placeholder="email" name="email"required autofocus>
                                
<input type="password" id="pass1" class="form-control"  placeholder="password" name="password_1" required>
                            
<input type="password" id="pass2" class="form-control" placeholder="password again" name="password_2" required>
                                </br>

<button class="btn btn-lg btn-primary btn-block" type="submit"  name="register_btn">Register</button>

</form> 

js ajax

$('#register_btn').click(function(){

    var data = {};
    data.username = $('#username').val();
    data.email = $('#email').val();
    data.password_1 = $('#pass1').val();
    data.password_2 = $('#pass2').val();


    $.ajax({
        type: "POST",
        url: "functions.php",
        data: data,
        cache: false,
        success: function (response) {

        }
    });
        return false;
});

});

functions.php

include 'db_config.php';

    session_start();

// connect to database

// variable declaration
$username = "";
$email    = "";
$errors   = array(); 

// call the register() function if register_btn is clicked
if (isset($_POST['register_btn'])) {
    register();
}


// REGISTER USER
function register(){
    global $db, $errors;

// receive all input values from the form
$username    =  e($_POST['username']);
$email       =  e($_POST['email']);
$password_1  =  e($_POST['password_1']);
$password_2  =  e($_POST['password_2']);

// form validation: ensure that the form is correctly filled
if (empty($username)) { 
    array_push($errors, "Username is required"); 
}
if (empty($email)) { 
    array_push($errors, "Email is required"); 
}
if (empty($password_1)) { 
    array_push($errors, "Password is required"); 
}
if ($password_1 != $password_2) {
    array_push($errors, "The two passwords do not match");




}

// register user if there are no errors in the form
if (count($errors) == 0) {
    $password = md5($password_1);//encrypt the password before saving in the database

    if (isset($_POST['user_type'])) {
        $user_type = e($_POST['user_type']);
        $query = "INSERT INTO users (username, email, user_type, password) 
                  VALUES('$username', '$email', '$user_type', '$password')";
        mysqli_query($db, $query);
        $_SESSION['success']  = "New user successfully created!!";
        header('location: home.php');
    }else{
        $query = "INSERT INTO users (username, email, user_type, password) 
                  VALUES('$username', '$email', 'user', '$password')";
        mysqli_query($db, $query);

        // get id of the created user
        $logged_in_user_id = mysqli_insert_id($db);

        $_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
        $_SESSION['success']  = "You are now logged in";
        header('location: index.php');              
    }

}

}

function display_error() {
    global $errors;

if (count($errors) > 0){
    echo '<div class="error">';
        foreach ($errors as $error){
            echo $error .'<br>';
        }
    echo '</div>';
}

}

mrmiaki
  • 21
  • 3
  • 1
    Try changing `type="submit"` to `type="button"`. I know `return false` should be stopping the form submission, but this should at least help narrow down the problem further. – imvain2 Aug 06 '20 at 18:06
  • If you're amalgamating the `input`s yourself in your JavaScript anyway, why even wrap them in a `form`? – esqew Aug 06 '20 at 18:34
  • **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Aug 06 '20 at 20:05
  • **Never store passwords in clear text or using MD5/SHA1!** Only store password hashes created using PHP's [`password_hash()`](https://php.net/manual/en/function.password-hash.php), which you can then verify using [`password_verify()`](https://php.net/manual/en/function.password-verify.php). Take a look at this post: [How to use password_hash](https://stackoverflow.com/q/30279321/1839439) and learn more about [bcrypt & password hashing in PHP](https://stackoverflow.com/a/6337021/1839439) – Dharman Aug 06 '20 at 20:05

1 Answers1

0

The JQuery selector you are using is using an ID, change the button from name="register_btn" to id="register_btn".

EDIT: Further looking at your code, you are missing the prevent default on the button, I would change the listener to the form instead and prevent default. The form is submitting to the current page which is the default behavior, which is why it looks like the page is just reloading.

See the below link for my code I use for form posts via AJAX: http://aspintech.ca/journal/?entry_id=77

Zachucks
  • 158
  • 14