Jump to content

how to turn this PHP form into AJAX? (dont refresh page when submit is pressed?)


foevah

Recommended Posts

Hi I was wondering how I can turn a PHP form I am using into an AJAX form so the page doesn't refresh when the submit button has been pressed? Right now the form successfully posts data into a MySql db and once submitted a valid email it says thank you!

 

Below is the code I am using, if someone can help me make it work without refresh but keep all the validation and thank you message would be great!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="js/jquery.1.2.6.js"></script>
<script>
$(document).ready(function() {
$("#thankyou").hide(8000);

});
</script>
</head>
<body>
<?php

/* keep functions at the top of the page and together - keeps it tidy 
   NOTE: merged the two functions together */

function clean_data($string) {
    if (get_magic_quotes_gpc()) {
        $string = stripslashes($string);
    }
        $string = htmlentities($string);
    
    $headers = array(
        "/to\:/i",
        "/from\:/i",
        "/bcc\:/i",
        "/cc\:/i",
        "/Content\-Transfer\-Encoding\:/i",
        "/Content\-Type\:/i",
        "/Mime\-Version\:/i" 
      );     
          
    $string = preg_replace($headers, '', $string);
    
    return mysql_real_escape_string($string);
}

/* Open database connection */
$conn = mysql_connect('localhost', 'root', 'password');
mysql_select_db('submissions');

/* empty error message that will be filled later on */
$errorMsg = '';

/* if the form has been sent....
    ** only process if the hidden field 'formSend' is present in the POST Array 
    ** Using hidden fields means the user can hit enter or click the submit button */
    
if(isset($_POST['formSend'])) {

/* assign simple variables to the POST array add in you data cleansing functions here */

$email = clean_data($_POST['email']);

/* start doing checks for data authenticity and values */

    /* check the email is valid */
    if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
        $errorMsg .= '<span>Please enter a Valid email address</span>';
    }
        
    /* if the $errorMsg variable is still empty then carry on with the processing */
    if($errorMsg == '') {

    /* start constructing the email message */
    $to = 'myemail@address.com';
    $subject = "New message: $topic";
    $message = "$name said: $comments";
    $headers = 'From: '. $email . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
    
    mail($to, $subject, $message, $headers);
    
if(mail($to,$subject,$message, $headers))
{ echo ("<span id='thankyou'>Thank you</span>"); }    

    /* Insert data into the database table after it has been cleaned */
        
$query = " INSERT INTO submissions (email) VALUES
	('$email')";
	mysql_query($query) or die(mysql_error());
    
    // Close connection
    mysql_close($conn);
    
    } else {
        /* could do something else here
            ** */
    }
} /* end if isset SUBMIT */

/* if the errorMsg variable isn't empty  echo it */
if($errorMsg != '') { echo $errorMsg; } 

?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"><fieldset><legend></legend>
<table border="0" cellspacing="0" cellpadding="0" style="margin:0 0 0 50px;">
  <tr>
    <th><label for="email">Email address:</label></th>
    <td><input type="text" id="email" name="email" value="<?php echo $_POST['email']; ?>" /></td>
  </tr>
   <tr>
    <td><?php echo($errorMsg); ?> </td>
    <td align="right">
    <input type="hidden" name="formSend" value="1" />
  <input type="submit" name="formSend" value="submit" /> </td>
  </tr>
</table> </fieldset>
</form>
</body>
</html>

Link to comment
Share on other sites

function processAjax()
{
    var ajax = new XMLHttpRequest();
    ..validation calls..
    ..something..
    ajax.call('form-process.php', 'get');
    ..again something..
    return false; // cancel submission as ajax already deals with it
}

<form onsubmit="return processAjax()" ..

 

I would however strongly advice using a framework as you do not want to write out all the solutions to all the browser difference problems with javascript. Use jQuery for example.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.