Created
January 13, 2017 22:13
-
-
Save fotan/0b01df88822a6c666164aea04f9b328a to your computer and use it in GitHub Desktop.
AJAX - Form Validation with PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form action="process.php" method="post"> | |
<label>First Name</label> | |
<input name="first_name" type="text" /> | |
<label>Email</label> | |
<input name="email" type="text" /> | |
<input type="submit" value="Submit" /> | |
</form> | |
<script> | |
var data = {}; | |
$(document).ready(function() { | |
$('input[type="submit"]').on('click', function() { | |
resetErrors(); | |
var url = 'process.php'; | |
$.each($('form input, form select'), function(i, v) { | |
if (v.type !== 'submit') { | |
data[v.name] = v.value; | |
} | |
}); //end each | |
$.ajax({ | |
dataType: 'json', | |
type: 'POST', | |
url: url, | |
data: data, | |
success: function(resp) { | |
if (resp === true) { | |
//successful validation | |
$('form').submit(); | |
return false; | |
} else { | |
$.each(resp, function(i, v) { | |
console.log(i + " => " + v); // view in console for error messages | |
var msg = '<label class="error" for="'+i+'">'+v+'</label>'; | |
$('input[name="' + i + '"], select[name="' + i + '"]').addClass('inputTxtError').after(msg); | |
}); | |
var keys = Object.keys(resp); | |
$('input[name="'+keys[0]+'"]').focus(); | |
} | |
return false; | |
}, | |
error: function() { | |
console.log('there was a problem checking the fields'); | |
} | |
}); | |
return false; | |
}); | |
}); | |
function resetErrors() { | |
$('form input, form select').removeClass('inputTxtError'); | |
$('label.error').remove(); | |
} | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
session_start(); | |
if(isset($_POST)){ | |
if (empty($_POST['first_name'])) { | |
$_SESSION['errors'][‘first_name'] = ‘First name is missing’; | |
} | |
if (empty($_POST[‘email’])) { | |
$_SESSION['errors'][‘email'] = ‘email is missing’; | |
} | |
if(count($_SESSION['errors']) > 0){ | |
//This is for ajax requests: | |
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { | |
echo json_encode($_SESSION['errors']); | |
exit; | |
} | |
//This is when Javascript is turned off: | |
echo “<ul>”; | |
foreach($_SESSION['errors'] as $key => $value){ | |
echo “<li>” . $value . “</li>”; | |
} | |
echo “</ul>”;exit; | |
}else{ | |
//form validation successful - process data here!!!! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment