JSFiddle - React, Tailwind, and code Playground
by SeasonEnds
HTML
<?php
include ("../../inc/config.inc.php");
// CLIENT INFORMATION (but now in a function for the jSON)
function addQuery($fname, $lname, $email, $business)
{
// CLIENT INFORMATION
$firstname = htmlspecialchars(trim($_POST['firstname']));
$lastname = htmlspecialchars(trim($_POST['lastname']));
$email = htmlspecialchars(trim($_POST['email']));
$business = htmlspecialchars(trim($_POST['business']));
$addClient = "INSERT INTO databasenamehere (firstname,lastname,email,business) VALUES ('$fname','$lname','$email','$business')";
$query = mysql_query($addClient);
if(!$query)
{
$response = array(
'error' => true,
'msg' => "An error occured");
}
else
{
$response = array(
'error' => false,
'msg' => "Client has been added successful!");
}
return $response;
}
// now we've got to jSON encode the $response array
if (@$_REQUEST['action'] == 'addClient' && isset($_SERVER['HTTP_X_REQUESTED_WITH']))
{
echo json_encode(addQuery($_POST['firstname'], $_POST['lastname'], $_POST['email'], $_POST['business']));
exit;
}
?>
JavaScript
$(document).ready(function() {
jQuery.validator.messages.required = "";
$("#userinfo").validate({
invalidHandler: function(e, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1 ? 'You missed 1 field. It has been highlighted below' : 'You missed ' + errors + ' fields. They have been highlighted below';
$("div.error span").html(message);
$("div.error").show();
} else {
$("div.error").hide();
}
},
onkeyup: false,
submitHandler: function() {
// we want to store the values from the form input box, then send via ajax below
var firstname = $('#firstname').attr('value');
var lastname = $('#lastname').attr('value');
var email = $('#email').attr('value');
var business = $('#business').attr('value');
$.ajax({
type: "POST",
dataType: 'json',
url: "ajax.php",
data: "action=addClient& firstname=" + firstname + "& lastname=" + lastname + "& email=" + email + "&business=" + business,
success: function(j) {
if (j.error) {
$('div.success').fadeIn().html(j.msg);
}
else {
$('form#userinfo').hide(function() {
$('div.success').fadeIn().html(j.msg);
});
}
}
});
},
debug: true
});
});