0

I'm making a register form for my website and i don't want it to submit before all fields are correct.

Html.

<div id="register-error"></div>
<form action="" method="POST" id="register-form">
    <input type="text" id="fn" placeholder="Full Name">
    <input type="text" id="un" placeholder="Username">
    <input type="text" id="em" placeholder="Email">
    <input type="password" id="pswd" placeholder="Password">
    <input type="password" id="pswd2" placeholder="Repeat Password">
    <input type="submit" id="register" class="login loginmodal-submit" value="Register">
</form>

Php.

$("#register-form").submit(function(){
    var name = $("#fn").val();
    var username = $("#un").val();
    var email = $("#em").val();
    var password = $("#pswd").val();
    var password2 = $("#pswd2").val();
    if(fn&&un&&em&&pswd&&pswd2){

        // check if the username exist

    }
    else
    {
        $("#register-error").html("Please fill in all fields");
        return false;
    }
});

Now I need to check if the username exist in my database.
And if the username does exist, than return false again and print error message.

Sql.

`id` int(11) NOT NULL AUTO_INCREMENT,

`name` varchar(255) NOT NULL,

`username` varchar(255) NOT NULL,

`email` varchar(255) NOT NULL,

`password` varchar(255) NOT NULL,

Can i include php in javascript function?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Toni Isotalo
  • 25
  • 1
  • 6
  • nope, you have to send filled username via ajax to a php page where checking will happen and true or false will return. based on that you have to stop the form submission or post the form – Alive to die - Anant Apr 23 '16 at 19:56

2 Answers2

1

There's no need to include PHP.

In your if statement:

if(fn&&un&&em&&pswd&&pswd2){
    // check if the username exist
}

you need to add a AJAX request to your PHP server to check if the username exists. Since you're already using jQuery, you can read more about their AJAX function here - http://api.jquery.com/jquery.ajax/

smaili
  • 1,245
  • 9
  • 18
0

You can't directly get data from mysql on the browser with JavaScript, but there's a few methods you can use to get SQL data up on a web page.

Dump data to tags.

You could use json_encode() to pass data to JavaScript from PHP to later use in a script. This won't change based on your SQL data without a reload, however, and you'll maybe want to have some checks to see if this is safe. In some cases it might not be.

<script type="text/javascript">
    var data = <?php json_encode($data); ?>;
</script>

Use XHR/AJAX

You could call a PHP file which generates JSON like the above statement with json_encode(), and then use JS/jQuery to load this data. This could be changed to dynamically change without a reload, though you'd need to make requests before the data may update.

PHP

[...]
echo json_encode($data);

JS (with jQuery)

$.get('/file.php', function (data) {
    // TODO: Update the data.
});
megubyte
  • 1,549
  • 9
  • 15