I made a form for my website using php, Ajax & jquery. When i submit the form with some inputs 1st time it works fine and but the second time without reloading the page it shows errors. The html input tags are simple with using class id and type attr.
What i want here is the code also runs for the second time if user submit form.
php and jquery:
if(isset($_POST['submit'])){
$name = $_POST['name'];
$website = $_POST['website'];
// $category = $_POST['category'];
$toscheckbox = $_POST['toscheckbox'];
$errorEmpty = false;
$website_error = false;
$name_error = false;
$toscheckbox_error = false;
if(empty($name) || empty($website) || empty($toscheckbox)){
echo "<span class='alert alert-danger' role='alert'>Please fill in all fields!</span>";
$errorEmpty = true;
}
elseif (!filter_var($website, FILTER_VALIDATE_URL)){
echo "<span class='alert alert-danger' role='alert'>Write a valid URL!</span>";
$website_error = true;
}
elseif (!preg_match("/^[a-zA-Z0-9][a-zA-Z0-9 \t]*$/", $name)) {
echo "<span class='alert alert-danger' role='alert'>Please check your Website Name</span>";
$name_error = true;
}
else {
echo "<span class='alert alert-success'>Thanks your submission listed in our Database!</span>";
}
}
else {
echo "<span class='alert alert-danger'>There was something wrong with your form</span>";
}
<script>
// $("#name, #website, #toscheckbox").removeClass("border border-danger");
var errorEmpty = "<?php echo $errorEmpty; ?>";
var website_error = "<?php echo $website_error; ?>";
var name_error = "<?php echo $name_error; ?>";
var toscheckbox_error = "<?php echo $toscheckbox_error; ?>";
if(errorEmpty == true){
$("#name, #website, #toscheckbox").addClass("border border-danger");
}
if(website_error == true) {
$("#website").addClass("border border-danger");
}
if(name_error == true) {
$("#name").addClass("border border-danger");
}
if (errorEmpty == false && name_error == false && website_error == false && toscheckbox_error == false) {
$("#name, #website, #toscheckbox").val("");
}
</script>
<script>
$(document).ready(function() {
$("form").submit(function(event){
event.preventDefault();
var name = $("#name").val();
var website = $("#website").val();
var toscheckbox = $("#toscheckbox").val();
var submit = $("#submit").val();
$(".text-danger").load("ajaxreturn.php", {
name: name,
website: website,
toscheckbox: toscheckbox,
submit: submit
});
});
});
</script>
EDIT html:
<input class="form-control" id="name" type="text" name="name">
<input name="toscheckbox" class="form-check-input" id="toscheckbox" type="checkbox" value="ToS">
<input class="form-control form-control" id="website" type="text" name="website">
Related
I'm trying to display a box shadow on the email input if the email address doesn't have an # , but instead i get the error displayed on the screen like this :
Instead i want to display a red border on the input box like i did for the rest of the form.
If it helps i followed this tutorial on youtube : https://www.youtube.com/watch?v=L7Sn-f36TGM&list=PLRIuc7tqh1lv8Vb0FvXqDpWAhYU83NkCX&index=13&t=924s .
Here is the relevant code :
JQuery Code Here / All good besides the errorEmail which works but not as it should :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
var errorEmpty = "<?php echo $errorEmpty; ?>";
var errorEmail = "<?php echo $errorEmail; ?>";
var errorName = "<?php echo $errorName; ?>";
var errorPhone = "<?php echo $errorPhone; ?>";
if (errorEmpty == true) {
$("#mail-name, #mail-phone, #mail-email, #mail-message").addClass("input-error");
}
if (errorEmail == true) {
$("#mail-email").addClass("input-error");
}
if (errorName == true) {
$("#mail-name").addClass("input-error");
}
if (errorPhone == true) {
$("#mail-phone").addClass("input-error");
}
if (errorEmpty == false && errorName == false && errorEmail == false && errorPhone == false) {
$("#mail-name, #mail-phone, #mail-email, #mail-message").val("");
}
</script>
HTML code here :
<div class="contact-form">
<h2>TRIMITE-NE UN MESAJ</h2>
<form id="contact-form" method="post" action="php/contact.php">
<input id="mail-name" name="name" type="text" class="edit-form" placeholder="Numele*" /><br>
<input id="mail-phone" name="phone" type="tel" class="edit-form" placeholder="Telefon*" /><br>
<input id="mail-email" name="email" type="email" class="edit-form" placeholder="Email*" /><br>
<textarea id="mail-message" name="message" type="text" class="edit-message" placeholder="Mesaj*" row="4" ></textarea><br>
<button id="mail-submit" type="submit" name="submit" class="submit-button">TRIMITE</button>
<p class="form-message"></p>
</form>
</div>
</div>
PHP code here :
<?php
if(isset($_POST['submit'])){
$name = $_POST["name"];
$phone = $_POST["phone"];
$email = $_POST['email'];
$message = $_POST['message'];
$errorEmpty = false;
$errorEmail = false;
$errorName = false;
$errorPhone = false;
if (empty($message) || empty($email) || empty($name) || empty($phone)) {
$errorEmpty = true;
}
elseif (!preg_match("/^[a-zA-Z0-9]*$/", $name)) {
$errorName = true;
}
elseif (!preg_match("/^[0-9]*$/", $phone)) {
$errorPhone = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errorEmail = true;
}
}
?>
There was also a bit of Ajax code which i didn't include here because i don't think is relevant , it all works fine there .
so i have an issue with a form made in php. I am echoing an error message in a span tag and i want to clear that message once clicking "clear form" button
This is my php for determining error message when the field hasnt been filled in
<script>
function clearForm(){
document.getElementById("firstName").value = '';
document.getElementById("email").value = '';
document.getElementById("lastName").value = '';
document.getElementById("subject").value = '';
document.getElementById("message").value = '';
document.getElementsByTagName("span").value = "";
}
</script>
<?php
$confirm= "";
$firstName = $lastName = $Email = $Subject = $Message = '';
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (isset($_POST["firstName"]) && $_POST["firstName"]!=null) {$firstName = $_POST['firstName'];} else {
$confirm ="Please fill it in";
}
if (isset($_POST["lastName"]) && $_POST["lastName"]!=null) {$lastName = $_POST['lastName'];} else {
$confirm ="Please fill it in";
}
if (isset($_POST["Email"]) && $_POST["Email"]!=null) {$Email = $_POST['Email'];} else {
$confirm ="Please fill it in";
}
if (isset($_POST["Subject"]) && $_POST["Subject"]!=null) {$Subject = $_POST['Subject'];} else {
$confirm ="Please fill it in";
}
if (isset($_POST["Message"])&& $_POST["Message"]!=null) {$Message = $_POST['Message'];} else {
$confirm ="Please fill it in";
}
}
if (isset($_POST["Clearform"])) {
$confirm= "";
}
?>
And this is how it looks in body
<form name="contact" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="POST">
<p>Your Name: <br>
<input type="text" name="firstName" id="firstName" value="<?php echo $firstName;?>"><span id="confirm"><?php echo $confirm; ?></span></p>
</form>
And the code for the button "Clear form"
<input class="button" type="button" name="Clearform" value="Clear Form" onclick="clearForm();"/>
So i have made this little function that sets the variable $confirm to no content but it doesn't work.
Please help
The problem is in your clearForm() you shouldn't use .value instead, you can use innerHTML, innerText or textContent. To see the difference between them check this link
function clearSpan() {
let mySpan = document.getElementById('errorSpan');
mySpan.innerText = '';
}
<span id="errorSpan">This is text to be cleared on button click</span>
<button onclick="clearSpan();">Clear</button>
This should do the trick. Use JQUERY .hide() to hide the error.
$("#btn").on("click", function(){
$("#errmsg").fadeOut("slow");
});
#errmsg{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Click to remove error.</button><br>
<span id="errmsg">Your error</span>
i need to pass a get variable via jquery, one of the form fields is a multiple check box. so i want to be able to pass it so that from php i can use GET and collect it then use IMPLODE to get such a value but its not working
JQUERY CODE HERE
$(document).ready(function(){
$.get('actionfilter.php', function(data){
$('.disFilter').html(data).fadeIn("2000");
});
$("#FilterForm :input").change(function() {
$(this).closest('form').data('changed', true);
var FilterByOrder = $("#FilterByOrder").val();
var location = $("#location").val();
var sortFilter = $("#sortFilter").val();
var Highlights = $("#Highlights").val();
if (FilterByOrder == '' || location == '' || sortFilter == '' || Highlights == '')
{
$.get('actionfilter.php', function(data){
$('.disFilter').html(data).fadeIn("2000");
});
}
else
{
$.get('actionfilter.php', {FilterByOrder: FilterByOrder, location: location, sortFilter: sortFilter, Highlights: Highlights}, function(data){
$('.disFilter').html(data).fadeIn("2000");
});
}
});
});
THE PHP VERSON
<?php
if(isset($_GET['FilterByOrder'])){
echo 'filter '. $FilterByOrder=$_GET['FilterByOrder'].'<br>';
echo 'location '.$location=$_GET['location'].'<br>';
echo 'sort '.$sortFilter=$_GET['sortFilter'].'<br>';
echo 'highlits '.$Highlights=$_GET['Highlights'].'<br>';
echo 'here is the one!';
}else
{
echo'lets run it';
}
?>
THE HTML FORM FIELD
<input type="checkbox" name="Highlights[]" value="<?php echo $DisplayedHighlightID; ?>" id="Highlights">
$(document).ready(function(){
var searchValue = $("#searchValue").val();
$.get('actionfilter.php', {searchValue: searchValue}function(data){
$('.disFilter').html(data).fadeIn("2000");
});
$("#FilterForm :input").change(function() {
$(this).closest('form').data('changed', true);
if($("#FilterByOrder").prop("checked") == true){
var FilterByOrder = 'on';
}
else
{
var FilterByOrder = 'of';
}
var location = $("#location").val();
var sortFilter = $("#sortFilter").val();
/* declare an checkbox array */
var HighlightsArrays = [];
/* look for all checkboes that have a class 'chk' attached to it and check if it was checked */
$(".Highlights:checked").each(function() {
HighlightsArrays.push($(this).val());
});
/* we join the array separated by the comma */
var selectedHighlights;
selectedHighlights = HighlightsArrays.join(',') + ",";
if (FilterByOrder == '' || location == '' || sortFilter == '' || Highlights == '')
{
$.get('actionfilter.php', function(data){
$('.disFilter').html(data).fadeIn("2000");
});
}
else
{
$.get('actionfilter.php', {FilterByOrder: FilterByOrder, location: location, sortFilter: sortFilter, selectedHighlights: selectedHighlights}, function(data){
$('.disFilter').html(data).fadeIn("2000");
});
}
});
});
<script language="JavaScript">
function toggle() {
if($("#check-buton").prop("checked") == true){
$('.chkall').prop('checked', true);
}else{
$('.chkall').prop('checked', false);
}
}
$('#industry').click(function(){
if($('#s').val().trim())
{
window.location.href= '<?php echo base_url();?>search?industry_id='+$('#industry_id').val().trim()
}else{
$('#alert_error').text('Please Select Industry').show();
return false;
}
});
</script>
<div class="loginAccount">
<form method="post" name="search" action="<?php echo base_url();?>search">
<h3>Search by Industry :</h3>
Select All: <input type="checkbox" name="industry_id[]" id="check-buton" value="" onclick="toggle()">
<ul class="searchbyindustry">
<?php
if($Industries)
{?>
<?php
foreach($Industries as $Industry)
{
?>
<li> <input type="checkbox" name="industry_id[]" class="chkall" value="<?php echo $Industry['id'];?>"> <?php echo $Industry['industry_name'];?>
</li> <?php
} }
?>
<br/>
<br/>
<!-- <button type="button" id="industry">Search</button>-->
<input type="submit" name="submit" value="Search">
</ul>
</form>
<?php
if(_inputPost('industry_id'))
{
$ind=implode(',', _inputPost('industry_id'));
//print($ind);die;
$ind=ltrim($ind,',');
$industry_id = $ind;
$flag = true;
$condition = ' and sector in ('.$ind.')';
$extraparams = '?industry_id='.$industry_id;
}else if(_inputGet('industry_id'))
{
$ind= _inputGet('industry_id');
//print($ind);die;
$ind=ltrim($ind,',');
$industry_id = $ind;
$flag = true;
$condition = ' and sector in ('.$ind.')';
$extraparams = '?industry_id='.$industry_id;
}
else if(trim(_inputGet('s')))
{
$s = trim(_inputGet('s'));
$flag = true;
$condition = ' and (name LIKE '.$this->db->escape('%'.$s.'%').' or mobile_office LIKE '.$this->db->escape('%'.$s.'%').' or mobile2 LIKE '.$this->db->escape('%'.$s.'%').' or email2 LIKE '.$this->db->escape('%'.$s.'%').")";
$extraparams = '?s='.$s;
}
I've been working my way up on validating a form and got the JS and PHP validation to work but I am still having a hard time adding ajax(with or without JQUERY) to submit to the php file and return a success message.
My form with CSS and JS validation:
<html>
<head>
<style type="text/css">
#nameerror {
color:red;
}
#emailerror{
color:red;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
function Validate() {
var email = document.forms['form']['email'].value;
var atpos = email.indexOf('#');
var dotpos = email.lastIndexOf('.');
var name = document.forms['form']['name'].value;
if (name == null || name == ""){
document.getElementById('nameerror').innerHTML="Please enter your name";
return false;
} else if (atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.length) {
document.getElementById('emailerror').innerHTML="Please enter a valid email";
return false;
} else {
}
}
</script>
</head>
<body>
<div>Sign Up</div>
<form name="form" action="form_validation.php" id="form" onsubmit="return Validate();" method = 'post'>
<label>Name:</label><br/>
<input id='name' type="text" name='name' /><br/>
<span id="nameerror"></span><br/>
<label>Email:</label><br/>
<input type='text' name='email' id = 'email'/> <br/>
<span id= "emailerror"></span><br/>
<label>Comments:</label><br/>
<textarea name='comments' id ='comments'></textarea><br/>
<span id="comerror"></span>
<input type="submit" name="submit" value="Submit"/>
<span id="success" style="display:none">Your message has been sent successfully.</span>
</form>
</body>
</html>
And this is form_validation.php:
<?php
if(isset($_POST['submit'])){
if($_POST['name']){
$name = $_POST['name'];
}
if(!preg_match('/^[a-zA-Z\s]+$/', $name)){
echo "Name can only contain letters.";
return false;
} else {
echo "Name accepted";
}
if($_POST['email']){
$email = $_POST['email'];
}
$pattern = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if(!preg_match($pattern, $email)){
echo "Please enter a valid email address.";
return false;
} else {
echo "Email Valid";
}
if($_POST['comments']){
$comments = $_POST['comments'];
}
if (strlen($comments) > 100){
echo "please enter less than 100 characters.";
return false;
}
}
?>
thanks for the help!
$('form').on('submit',function() {
$.ajax({
url: 'form_validation.php',
data: $(this).serialize(),
type: 'POST'
}).done(function(data){
// you can append a success message to your document here
});
});
I want to check if a user exists in DB, and if exist display some error without reload the page (modify a div). Any idea what is wrong in this code? Or any other idea how to do it? Thank you
HTML:
<div style="width:510px; height:500px;">
<div class="message">
<div id="alert"></div>
</div>
<form id="signup_form" method="post" action="register.php">
<label class="label">username</label>
<p><input class="signup_form" type="text" name="username"></p>
<label class="label">parola</label>
<p><input class="signup_form" type="text" name="password"></p>
<label class="label">name</label>
<p><input class="signup_form" type="text" name="name"></p>
<label class="label">telefon</label>
<p><input class="signup_form" type="text" name="phone"></p>
<label class="label">email</label>
<p><input class="signup_form" type="text" name="email"></p>
<p><input class="signup_button" type="submit" value="inregistrare">
</form>
<div class="clear"></div>
</div>
register.php
<?php
include "base.php";
$usertaken = '<li class="error">username used</li><br />';
$alert = '';
$pass = 0;
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$name = mysql_real_escape_string($_POST['username']);
$phone = mysql_real_escape_string($_POST['phone']);
$email = mysql_real_escape_string($_POST['email']);
$checkusername = mysql_query("SELECT * FROM details WHERE user = '".$username."'");
if(mysql_num_rows($checkusername) == 1)
{
$pass = 1;
$alert .="<li>" . $usertaken . "</li>";
}
else
{
$registerquery = mysql_query("INSERT INTO details (user, pass, name, phone, email) VALUES('".$username."', '".$password."','".$name."','".$phone."', '".$email."')");
if($registerquery)
{
echo "<h1>Success</h1>";
echo "<p>Your account was successfully created. Please click here to login.</p>";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your registration failed. Please go back and try again.</p>";
}
}
if($pass == 1) {
echo '<script>$(".message").hide("").show(""); </script>';
echo "<ul>";
echo $alert;
echo "</ul>";
}
}
?>
SOLUTION (add this in head and hide .message div)
<script type="text/javascript" src="jquery-latest.pack.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#alert',
beforeSubmit: showRequest,
success: showResponse
};
$('#signup_form').ajaxForm(options);
});
function showRequest(formData, jqForm, options) {
var queryString = $.param(formData);
return true;
}
function showResponse(responseText, statusText) {
}
$.fn.clearForm = function() {
return this.each(function() {
var type = this.type, tag = this.tagName.toLowerCase();
if (tag == 'form')
return $(':input',this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
</script>
You need to use AJAX to do a dynamic page update.
Take a look here: http://api.jquery.com/jQuery.ajax/ for how to do it with jQuery.
Your current code uses a form submit, which always reloads the page.
You need to use ajax. Write something like this as a JavaScript:
var xmlHttp;
function checkUser(user) {
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
alert ("Browser does not support HTTP Request.");
return;
}
var url = "check.php"; //This is where your dynamic PHP file goes
url = url + "?u=" + user;
url = url + "&sid=" + Math.random();
xmlHttp.onreadystatechange = getData;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function getData () {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
if (xmlHttp.responseText == 1) {
alert('Username free'); //action if username free
} else {
alert('This username is taken'); //action if its not
}
}
}
function GetXmlHttpObject() {
var xmlHttp=null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) {
//Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
And in your check.php file, just check against your database if the username is taken or not, if not and simply echo('1') if its free, else echo('0') o whatever you want. that single number will be handled as the xmlHttp.responseText. you can also do something fancy instead of the alerts, like an image. also you need to run the check() fumction either when the user is typing, or when the form is submitted, with the username form field as a parameter. Hope this helps.
EDIT: Oh, also I forgot that in the check.php file, the $_GET['u'] variable contains the the entered username. Check that against the database.
If that's all in a single page, you'll have to structure it like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... do form retrieval/database stuff here ...
if (error) {
$message = 'Something dun gone boom';
}
}
if ($message != '') {
echo $message;
}
?>
form stuff goes here