I am using PHP to process a form and handle errors. The errors work fine, but the issue is that I am wanting to add it to the page with my form on (if an error is found) without refreshing the page. This is because the user can add rows dynamically to my form, and I don’t want these extra rows to be lost (which happens when the page is refreshed).
At the moment then, I simply have the following line on my form (PHP) page:
<?=$errorString?>
And then I define $errorString in booking-engine.php, and add include 'workshops.php'; which refreshes the page to add the error.
Is it possible to add the error without refreshing the page, and if so, how would I go about this?
Thanks,
Nick
FULL PHP SCRIPT:
$row_count = count($_POST['name']);
if ($row_count > 0) {
mysql_select_db($database, $connection);
$name = array();
$workshop = array();
$not_found = array();
for($i = 0; $i < $row_count; $i++) {
// variable sanitation...
$name[$i] = mysql_real_escape_string(ucwords($_POST['name'][$i]));
$workshop[$i] = mysql_real_escape_string($_POST['workshop'][$i]);
}
$names = "('".implode("','",$name)."')";
$not_in = Array();
// lets say all names doesn't exist in `conference`
foreach($name as $value) {
// names in array are keys, not values
$not_in[$value] = true;
}
$query = mysql_query("SELECT Name FROM conference WHERE Name IN $names");
while(list($dbname) = @mysql_fetch_row($query)) {
// delete those name from $not_in who exists
unset($not_in[$dbname]);
}
// names in $not_in array are keys, not values
$not_in = array_keys($not_in);
if(empty($not_in)) {
// its ok, all names have been found. do the magic.
for($i = 0; $i < $row_count; $i++) {
$sql = "UPDATE conference SET Workshop = '$workshop[$i]' WHERE Name LIKE '$name[$i]'";
mysql_query($sql);
$body .= "Name: " . $name[$i] . " Workshop: " . $workshop[$i] . "\n\n";
}
// send email
$success = mail($emailTo, $subject, $body, "From: <$emailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=thanks-workshop.html\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
}else{
$errorString = "<div id=\"error\">".'<strong>The following name(s) have not been found on our database of bookings</strong>:<div id=\"names\">'.join(', ',$not_in)."</div><div id=\"error-sub\">Please check the name(s) and try submitting your booking again. Each name needs to be identical to the name you first booked on to the conference, as described above.</div></div>";
include 'workshops.php';
}
}
PHP is server-side and what you want to do is on the client. So you’ll need to use (client-side) Javascript to submit the data to your server-side PHP validation and then update the page with the results. See AJAX for background and jQuery.post() for some practical examples.