简体   繁体   中英

HTML form post to PHP call using AJAX

I'm trying to POST and email address entry from a HTML form to a PHP script to store the result in a database. The script is also responsible for firing an error message should the user enter an invalid email address etc. I would like the whole process to involve an AJAX call so that the page doesn't have to be reloaded each time that the user hits the submit button on the form.

As of now, each time the user hits the form submit button the page is being refreshed and i'm getting a response from the ajax call but it is immediately being written over due to the refresh.

Here's my HTML and Javascript/ajax:

<div id="emailform">
<form method="post"><!--action="planethome.php"-->
<input class="emailinput" type="text" name="email" maxlength="80" placeholder="enter your email address"/>
<input class="submitemailbutton" name="send_button" type="submit" value="Send" onClick="ajaxFunction()/>
<input type="hidden" name="submitted" value="TRUE"/>
</form>
</div>

<div id="errororsuccess">
</div>


<!--ajax stuff:---------------------------------->


<script language="javascript" type="text/javascript">
//Browser Support Code"
function ajaxFunction(){
    var ajaxRequest;  // The variable that makes Ajax possible!

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Ajax is struggling in your browser.");
                return false;
            }
        }
    }

    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){

            document.getElementById('errororsuccess').innerHTML = ajaxRequest.responseText;     

            }
    }

    // Create a function that will receive data sent from the server
    ajaxRequest.open("POST", "addemailtodatabase.php", true);
    ajaxRequest.send(null); 
}

and here's my PHP:

<?php

    require_once ('planetconfig.php');

    if (isset($_POST['submitted'])) { /

        require_once (MYSQL);

        $email = FALSE;


        $trimmed = array_map('trim', $_POST);


        if (!empty($_POST['email'])) 
        {

            if (preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$_POST['email'])) {

                $email = mysqli_real_escape_string ($dbc, $trimmed['email']);

            } else {
                echo "Invalid";         
            }

        } else {
                echo "You need to enter an email address";

        }


        if ($email) { 

            $q = "INSERT INTO planetemail (email, time) VALUES (AES_ENCRYPT('$email', 'password'), NOW())";

            $r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));

            if (mysqli_affected_rows($dbc) == 1) { 

                echo "Thanks, we'll be in touch";

                exit();

            } else { 
                echo '<p class="error">We\'re sorry, something has gone wrong.</p>';
            }
        }

    mysqli_close($dbc);

} 
?>

I'm sure it's something to do with my POST method or how I have my ajax call set up.

I'm new to all this, can anyone tell me what I'm doing wrong or suggest a better implementation. I have a deadline of tomorrow morning to have this done.

You're problem is that you are using a submit button. The submit button will submit the form, change it from a type="submit" to type="button" and it will work and as @juzerali suggested, use jQuery, that code hurts my head.

1st, yes that is awful, use jquery. 2nd although you have bound ajax call with onclick of submit button, you have not prevented the default behaviour from executing. The form will still get submitted the usual way.

if (isset($_POST['submitted'])) { /

There is a stray / in your code.

Also, Change type="submit" to type="button"

The onClick event handler will pick up the submit becuase you are making an AJAX request, no need to POST.

return false; at the end of the script to keep it from submitting the normal way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM