I have a simple HTML file with a form.
<form action="register.php" method="get" id="submitform">
First Name:
<input type="text" class="fb-input" name="fname" id="firstname" />
<br>
<div class="fb-error">
</div>
<input type="button" name="signupBtn" id ="sub" value="Sign upw">
</form>
When I press the submit button, this will be checked at the jquery if the field is empty.
$(document).ready(function(){
$("#sub").click(function(){
register();
});
});
function register(){
var firstname=$("#firstname").val();
if(firstname==""){
$(".fb-error").show().html("You must fill the fields.");
}else{
$(".fb-error").hide();
$("#submitform").submit();
}
}
Then after being checked, it will be submitted to the php file to further check the characters inputted in the form, then will it will echo if an invalid character was found.
What I want is, the checking that i am doing after page submission in the php file will be transferred inside the jquery. Example:
function register(){
var firstname=$("#firstname").val();
if(...){
<?php
if(preg_match(....)){....}
?>
}else{
.....
}
}
I tried this and it didn’t work. I guess i cant put php inside the jquery. The reason i want to put the php inside the jquery is for me to be able to show an error message in the div part of the HTML because once I submit the page, It goes to another blank page where the error message of the php shows up.
What im doing is like the regisration of facebook that once you submit it and you input wrong characters, an error message will show up at the bottom. We are required to use php, jquery is just optional.
Could anyone help me with this? Or could suggest a better way to do this?
Updated:
Html code:
<html>
<head>
<title>Facebook Registration</title>
</head>
<body>
<form action="register.php" method="get" id="submitform">
First Name:
<?php $fname = isset($_POST['fname']) ? $_POST['fname'] : ''; ?>
<input type="text" class="fb-input" name="fname" value="<?php echo $fname; ?>">
<br>
<div class="fb-error">
</div>
<input type="submit" name="signupBtn" id ="sub" value="Sign upw">
</form>
Php file:
<?php
$fname=$_GET['fname'];
if((preg_match("/^[a-zA-z]{1,}$/",$fname))){
echo "registered";
}
else{
var_dump($_POST);
echo "<form id='retForm' method='post' action='index.php'>";
echo "<input type='hidden' name='fname' value='$_POST[fname]'>";
echo "<script>$(document).ready(function() { $('#retForm').submit() });</script>";
}
?>
What you can do in PHP, is simple. You can validate the form on the PHP script on the other page, and if you find any errors, you can redirect the form back with the $_POST variable.
Something like this on your form
Now, in your register.php, you can write this snippet
This will send the
fnameback as part of the$_GETvariable and will be displayed in the form input. You can use AJAX calls to validate as well, but since you wanted to minimize the jQuery code, this would be one of the few ways you can achieve it.