Javascript: Show element in a form when something is valid - php

How can I display an element when something in a form is validated?
Here's some of my code:
signup.php
<div class="wrapper">
<div class="error-div" id="zipcode-error" ></div>
<label>Zip code:</label>
<input type="text" class="input" name="zipcode" id="zipcode" />
</div>
<!-- this div is hidden, it can only be seen when zip code is validated -->
<div class="wrapper" id="city-wrapper" >
<div class="error-div" id="city-error" ></div>
<label>City:</label>
<input type="text" class="input" name="city" id="city" >
</div>
<!-- this div is hidden, it can only be seen when zip code is validated -->
signup_validation.js
$('#zipcode').keyup(function() {
$.post('action/validate_signup.php?key=zipcode', { zipcode: $(this).val() },
function(result){
$('#zipcode-error').html(result).show("slow");
});
});
validate_signup.php
if(isset($_POST['zipcode'])){
$zip = $_POST['zipcode'];
if(empty($zip)){
echo "*Zipcode required!";
}elseif( (strlen($zip)<5) OR (strlen($zip)>5)){
echo "*Must be 5 digit!";
}elseif(!is_numeric($zip)){
echo "Must be numeric!";
}else{
$query = mysql_query("SELECT * FROM zip_codes WHERE zip = '{$zip}'");
$found_zip = mysql_num_rows($query);
if($found_zip =1){
echo "<img src='images/check.jpg' /><input type = 'hidden' name='show-city' id='show-city' />";
} else{
echo "Zip not found";
}
}
}
When zipcode is validated i want to display the City div, but i don't know how.
The situation goes like this: a user must input his/her valid zipcode, once it's validated, the hidden div will come up and display it's corresponding City on the text field provided.

if($found_zip =1){
echo "found||<img src='images/check.jpg' /><input type = 'hidden' name='show-city' id='show-city' />";
} else{
echo "error||error";
}
//then ur js
$('#zipcode').blur(function() {
var zip = $(this).val();
$.post('action/validate_signup.php?key=zipcode', { zipcode: zip },
function(result){
var respArr = result.split("||");
if("error" ==respArr[0]) {
$('#zipcode-error').html(result).show("slow");
}
else {
//show your hidden div here
$("#urHidden").show("slow");
}
});
});

When the return of the post is empty you will show the div
echo "<div id='city_holder'>No City</div>";
if(isset($_POST['zipcode'])){
$zip = $_POST['zipcode'];
if(empty($zip)){
echo "*Zipcode required!";
}elseif( (strlen($zip)<5) OR (strlen($zip)>5)){
echo "*Must be 5 digit!";
}elseif(!is_numeric($zip)){
echo "Must be numeric!";
}else{
$query = mysql_query("SELECT * FROM zip_codes WHERE zip = '{$zip}'");
$found_zip = mysql_num_rows($query);
if($found_zip =1){
$row = mysql_fetch_array($query);
echo "<div id='city_holder'>".$row['city_name']."</div>";
echo "<img src='images/check.jpg' /><input type = 'hidden' name='show-city' id='show-city' />";
} else{
echo "Zip not found";
}
}
}
$('#zipcode').keyup(function() {
$.post('action/validate_signup.php?key=zipcode', { zipcode: $(this).val() },
function(result){
if($('#city_holder').html() != 'No City')
{
$('#city').val($('#city_holder').html()); //to fill up the input
$('#city-wrapper').show("slow");//to show the div
}
else{
$('#city').val(" "); //to empty the input
$('#city-wrapper').hide("slow");//to hide the div
$('#zipcode-error').html(result).show("slow");
}
});
});
Hope it helps you
Don't forget to set the city_holder to hidden with your CSS
If you want any other help comment it

Related

Submit form twice display error of blank input

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">

File submission worked until I added jQuery, whats the issue?

I am having a strange issue where I was able to submit files and successfully upload them, now that I have added this bit of jQuery within the head of the webpage, it doesn't seem to work anymore:
I tested once again without the jQuery and it works perfectly fine, my jQuery is messing with it somewhere. Anyway I can accomplish the same objective, differently?
Jquery:
$(document).ready(function() {
var options = $('select[name=itemType]');
var optionVal = options.val();
var filer = $('input[name=itemFile');
var filerVal = $('input[name=itemFile]').val();
options.change(function() {
optionVal = $(this).val();
if(optionVal == 1 || optionVal == 3) {
$('input[name=itemContact]').removeAttr('disabled');
$('input[name=itemContact]').attr('required','true');
} else {
$('input[name=itemContact]').attr('disabled','true');
$('input[name=itemContact]').removeAttr('required');
};
if(optionVal != 5) {
$('input[name=itemFile]').removeAttr('disabled');
$('span.inputFile').css("display","block");
} else {
$('input[name=itemFile]').attr('disabled','true');
$('span.inputFile').css("display","none");
};
});
filer.change(function() {
filerVal = $(this).val();
$(this).parent().text(filerVal);
});
});
HTML Form:
Note: $sectionName is defined earlier throughout the webpage, and does work.
<form class="col-12" method="post" action="./action.php?upload" enctype="multipart/form-data">
<p class="head">Upload to <i><?php echo $sectionName; ?></i></p>
<div class="con">
<input name="sectionID" type="hidden" value="<?php echo $section; ?>" required />
<select name="itemType" required>
<option selected disabled>Select an Item Type</option>
<option value="1">Downloadable, Contact</option>
<option value="2">Downloadable</option>
<option value="3">Installable, Contact</option>
<option value="4">Installable</option>
<option value="5">Browsable</option>
</select>
<span class="inputFile" style="display:none;">
Select a File
<input name="itemFile" type="file" required />
</span>
<input name="itemName" type="text" placeholder="Enter Item Name" required />
<input name="itemContact" type="email" placeholder="Enter Contact Email Address" disabled />
<button type="submit">Submit</button>
</div>
</form>
action.php?upload:
$fileDir = "./uploads/";
$fileName = preg_replace("/[^A-Z0-9._-]/i", "_", $_FILES['itemFile']["name"]);
$itemDir = $fileDir. $fileName;
$sectionID = $_POST['sectionID'];
$itemName = $_POST['itemName'];
$itemType = $_POST['itemType'];
$itemContact = $_POST['itemContact'];
if (file_exists($itemDir)) {
echo '<p class="alert">Sorry, file already exists</p>';
} else {
if (move_uploaded_file($_FILES["itemFile"]["tmp_name"], $itemDir)) {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if($createItem = $con->prepare("INSERT INTO items(sectionID,itemName,itemType,itemDir) VALUES(?,?,?,?)")) {
$createItem->bind_param("isis", $sectionID,$itemName,$itemType,$itemDir);
if($createItem->execute()) {
$itemID = $createItem->insert_id;
if($itemType == 1 || $itemType == 3) {
if($createContact = $con->prepare("INSERT INTO contacts(itemID,itemContact) VALUES(?,?)")) {
$createContact->bind_param("is", $itemID,$itemContact);
if($createContact->execute()) {
echo '<p class="alert">Item Created</p>';
} else {
echo "<p class=alert'>Execute failed: [createContact] (" . $createContact->errno . ") " . $createContact->error. '</p>';
};
} else {
echo '<p class="alert">Item Created</p>';
};
$createContact->close();
};
};
};
$createItem->close();
};
};
Rather than uploading the file, or storing it in $_FILES it doesn't even get passed to action.php. I have checked $_POST and $_FILES, it doesn't show up in either, whereas before it did.
Note: This is an internal website on one of my web servers, so it doesn't matter if it is vulnerable to SQL Injection.
Selector is not valid at this line
var filer = $('input[name=itemFile');
var filer = $('input[name=itemFile ] ');

Submiting form, it opens the PHP file?

I will be on the point. But anyways, THANKS IN ADVACE.
So basically When I submit the form I made, it submits and stuff, but it redirects the page to the PHP file, and shows this on the browser (not as an alert) :
{"status":"success","message":"Yer message was sent."}
when the data is successfully validated, and shows this
{"status":"fail","message":"Invalid name provided."}
when the form doesn't validate. What I want, is that when the form submits, it stays on the same page and if status is true or false, it should alert the message in the array.
I'll write down the scripts and the file names are: index.html, script.js and post.php
INDEX.HTML
<form action='post.php' id='post_message' name='post_message' method="post">
<p>
<input id='email' type="email" class='post' placeholder="Email goes in here.(Required) " class="width" name="email">
<br>
<input id='fname' type="text" class='post' placeholder="First Name (Required) " name="FirstName"><br>
<input id='lname' type="text" class='post' placeholder="Last Name (Required) " name="LastName"><br>
<input id='website' type="url" class='post' placeholder="Website? (Optional!)" class="width" name="website"><br>
<textarea id='message_text' placeholder="Your Message goes here. (Required, DUH!) " name='message'></textarea>
</p>
<button type="submit" class="submit" id='btnPost'></button>
<input type="hidden" name="action" value="post_message" id="action">
</form>
SCRIPT.JS
function clearInputs(){
$("#fname").val('');
$("#lname").val('');
$("#email").val('');
$("#website").val('');
$("#message_text").val('');
}
$('#btnPost').click(function() {
var data = $("#post_message").children().serializeArray();
$.post($("#post_message").attr('action'), data, function(json){
if (json.status == "fail") {
alert(json.message);
}
if (json.status == "success") {
alert(json.message);
clearInputs();
}
}, "json");
});
POST.PHP
<?php
if($_POST){
if ($_POST['action'] == 'post_message') {
$fname = htmlspecialchars($_POST['FirstName']);
$lname = htmlspecialchars($_POST['LastName']);
$email = htmlspecialchars($_POST['email']);
$website = htmlspecialchars($_POST['website']);
$message = htmlspecialchars($_POST['message']);
$date = date('F j, Y, g:i a');
if(preg_match('/[^\w\s]/i', $fname) || preg_match('/[^\w\s]/i', $lname)) {
fail('Invalid name provided.');
}
if( empty($fname) || empty($lname) ) {
fail('Please enter a first and last name.');
}
if( empty($message) ) {
fail('Please select a message.');
}
if( empty($email)) {
fail('Please enter an email');
}
$query = "INSERT INTO portmessage SET first_name='$fname', last_name='$lname', email = '$email', website = '$website', message = '$message', date = '$date'";
$result = db_connection($query);
if ($result) {
$msg = "Yer message was sent.";
success($msg);
} else {
fail('Message failed, Please try again.');
}
exit;
}
}
function db_connection($query) {
mysql_connect('127.0.0.1', '######', '####')
OR die(fail('Could not connect to database.'));
mysql_select_db('####');
return mysql_query($query);
}
function fail($message) {
die(json_encode(array('status' => 'fail', 'message' => $message)));
}
function success($message) {
die(json_encode(array('status' => 'success', 'message' => $message)));
}
?>
And yes, it DOES submit the form to the database, but I can't overcome the alert and redirecting problem.
Thanks, again!
You can validate your form client side(using javascript)
HTML
<form action='post.php' id='post_message' name='post_message' method="post" onsubmit="return validate_form();">
Javascript
function validate_form()
{
var success = true;
if($("[name=FirstName]").val() == "")
{
success = false;
}
// your test case goes here
// you can alert here if you find any error
return success;
}

Checking if a PHP array is empty in JavaScript

Hi I have a form where a user can enter one or more books into a DB. Whenever a user enters one book and forgets to enter the title, a JavaScript alert comes and alerts him to enter a title. Now if he has two or more books and he forgets to enter the title, the alert doesn't show up.
This is my JavaScript function.
function validateForm()
{
var a=document.forms["submit_books"]["title"].value;
if (a==null || a=="")
{
alert("Please enter a Title");
return false;
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.submit_books.email.value.search(emailRegEx) == -1) {
alert("Please enter a valid email address.");
return false;
}
}
And Here is my PHP code
<form method="post" name="submit_books" onsubmit="return validateForm()" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php for ($i=1; $i<$num_of_books + 1; $i++){
echo "<strong>Book # $i</strong><br><br>";
?>
<label for="title">*Title</label>: <input type="text" id="title" size="60" name="title[]" autocomplete="off"/><br><br>
<?php }?>
<input type="submit" name="submit" value="Submit Books">
</form>
I even tried putting the PHP array into a JavaScript one.
<?
$js_array = json_encode($title);
echo "var title = ". $js_array . ";\n";
?>
var index = 1;
if( index < title.length)
{
alert("Please enter a Title");
return false;
}
There must be an easier way doing this
You should be doing
var index = 1;
if( index > title.length )
{
alert("Please enter a Title");
return false;
}
Since there is no record if title.length = 0, that is, if 1 > 0 then there is no title.
You can also check
if( title.length === 0 )
Try to use inside html form
<label>
<span>Book Title: (required)</span>
<input name="book" type="text" placeholder="Please enter your books title" required autofocus>
</label>
Then use javascript to validate
(function() {
// Create input element for testing
var inputs = document.createElement('input');
// Create the supports object
var supports = {};
supports.autofocus = 'autofocus' in inputs;
supports.required = 'required' in inputs;
supports.placeholder = 'placeholder' in inputs;
// Fallback for autofocus attribute
if(!supports.autofocus) {
}
// Fallback for required attribute
if(!supports.required) {
}
// Fallback for placeholder attribute
if(!supports.placeholder) {
}
// Change text inside send button on submit
var send = document.getElementById('submit');
if(send) {
send.onclick = function () {
this.innerHTML = '...Processing';
}
}
})();
You can do this like:
<?
echo "var title_length = ". count($title) . ";\n";
?>
var index = 1;
if( index > title_length)
{
alert("Please enter a Title");
return false;
}

How to add AJAX Submit to PHP validation and return message?

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
});
});

Categories