ajax表单转到另一页而不是保留在同一页面上

问题描述:

I have this popup ajax form that, instead of sending the data and remain on the same page, it sends data but takes me to the file send.php from my form. Why is that? I implemented almost the same form correctly on another site. I don't know what I am doing wrong here...

form:

<form id="form" action="send.php"  name="form" method="post" >

    <input type="text"  id="name" name="name" value="" /><br />

    <input type="text"  id="email" name="email" value=""  /><br />

    <textarea name="message" cols="4" rows="4"  id="message" ></textarea><br />

    <input type="submit" value="" id="submit" title="Send!"/>

</form>

ajax:

<script type="text/javascript">

$(document).ready(function () {
    $('#form').ajaxForm({
        beforeSubmit: validate
    });

    function validate(formData, jqForm, options) {
        var name = $('input[name=name]').fieldValue();
        var email = $('input[name=email]').fieldValue();
        var message = $('textarea[name=message]').fieldValue();

        if (!name[0]) {
            alert('Please enter a value for name');
            return false;
        }
        if (!email[0]) {
            alert('Please enter a value for email');
            return false;
        }
        if (!message[0]) {
            alert('Please enter a value for message');
            return false;
        }

        else {

        $("#prima_form").fadeOut(1000, function () {
            $(this).html("<img src='images/de_multumire.png'/>").fadeIn(2000);
        });

        var message = $('textarea[name=message]').val('');
        var name = $('input[name=name]').val('');
        var email = $('input[name=email]').val('');

} 
}

});

</script>

send.php:

<?php
        if($_POST){
                $email = $_POST['email'];
                $name = $_POST ['name'];
                $message = $_POST ['message'];
                // response hash
                $ajaxresponse = array('type'=>'', 'message'=>'');

                try {
                        // do some sort of data validations, very simple example below
                        $all_fields = array('name', 'email', 'message');

                        foreach($all_fields as $field){
                                if(empty($_POST[$field])){
                                        throw new Exception('Required field "'.ucfirst($field).'" missing input.');
                                }
                        }

                        // ok, if field validations are ok
                        // now Send Email, ect.

                        // let's assume everything is ok, setup successful response
                        $subject = "New Contact";
                        //get todays date
                        $todayis = date("l, F j, Y, g:i a") ;

                        $message = " $todayis 

                        Attention: 


                        Please see the message below: 


                        Email Address: $email 


                        Message: $message 



                        ";

                        $from = "From: $email
";


                        //put your email address here
                        mail("contact@xxx.ro", $subject, $message, $from);

                        //prep json response
                        $ajaxresponse['type'] = 'success';
                        $ajaxresponse['message'] = 'Thank You! Will be in touch soon';  
                } catch(Exception $e){
                        $ajaxresponse['type'] = 'error';
                        $ajaxresponse['message'] = $e->getMessage();
                }
                // now we are ready to turn this hash into JSON
                print json_encode($ajaxresponse);
                exit;
        }
?>  

my js console gives this:

[17:38:03.840] [cycle] terminating; zero elements found by selector @ http://sociallab.ro/js/jquery_003.js:10
--
[17:38:16.012] POST http://sociallab.ro/send.php [HTTP/1.1 200 OK 218ms]

[17:38:16.204] The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must to be declared in the document or in the transfer protocol. @ http://sociallab.ro/send.php

Thanks!

In pure Javascript you need to do something like:

function sendWithAjax() {
    var ajax = new XMLHttpRequest();
    ajax.open("POST", "send.php", true);

Then read the values from the input elements:

    var email = document.getElementById('email').value;
    var name = document.getElementById('name').value;
    var message = document.getElementById('message').value;

You can validate the form here before calling .send()

(You might need to escape the contents of the form elements with the escape() function)

And put them into the send method:

    ajax.send("email="+ email +"&name="+ name +"&message="+ message);

And also remove the complete form tag from your form code. Therefore you wont need a submit button, so change it to a simple button:

<input type="text"  id="name" name="name" value="" /><br />
<input type="text"  id="email" name="email" value=""  /><br />
<textarea name="message" cols="4" rows="4"  id="message" ></textarea><br />
<input type="submit" value="" id="submit" title="Send!" onclick="javascript:sendWithAjax()"/>

To get the ajax response use:

    var response = ajax.responseText;
}

Try adding this:

$('#submit').click(function(){ return false; /* stop html form from submitting*/ })

I believe what is happening is jquery is sending the form data via ajax, but you are not stopping the default "submit" button from submitting the html form like normal. Adding the code above should stop the submit buttons default action (submitting form to send.php), thus leaving you on the current page.

Something like:

   $(document).ready(function(event){
        event.preventDefault();
        $('#FORMID').ajaxForm({
            type: 'POST',
            dataType: 'json',
            beforeSubmit: function(){
            },
            success: function(resp){

            },
            error: function(resp){

            }
        });
    });

Hope this will help.