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>";
}
?>
<input name="fname" value="<?=$_GET["fname"]?>" />, and you can escape the form values if you like. However, you may wish to put that info in$_SESSIONsince you are dealing with redirects and may lose the info from$_GET.