Stay on page after submitting form

纵然是瞬间 提交于 2019-12-08 14:14:41

问题


I'm trying to stay on the current page from where a form gets submitted. But somehow it's not working. I found some peaces of code on the internet and put it together.

This is the process.php file:

<?php
// Get Data    
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$phone = strip_tags($_POST['phone']);
$subject = strip_tags($_POST['subject']);
$message = strip_tags($_POST['message']);

// Send Message
mail( "email@domain.com", "Contact Form testttt",
"Name: $name\nEmail: $email\nPhone: $phone\nWebsite: $url\nMessage: $message\n",
"From: Forms testtttttttt" );
?>

And the rest of the code, the html and javascripts can be found on jsfiddle: jsfiddled code

    $(function(){
        $('#contact').validate({
        submitHandler: function(form) {
                $(form).ajaxSubmit({
                url: 'process.php',
                success: function() {
                    $('#contact').hide();
                    $('#contact-form').append("<p class='thanks'>thanks test.</p>")
                    }
                });
            }
        });         
    });

Forgot to mention what happens now. I get redirected to process.php page.


回答1:


Use jQuery.ajax() function to submit a form without refreshing a page. You need to do something like this:

test.php:

<script type="text/javascript" src="jquery-version.js"></script>
<script type="text/javascript" src="ajaxform.js"></script>

<form action='process.php' method='post' class='ajaxform'>
 <input type='text' name='txt' value='Test Text'>
 <input type='submit' value='submit'>
</form>

process.php:

<?php
      // Get your form data here in $_POST
?>

ajaxform.js

jQuery(document).ready(function(){

    jQuery('.ajaxform').submit( function() {

        $.ajax({
            url     : $(this).attr('action'),
            type    : $(this).attr('method'),
            data    : $(this).serialize(),
            success : function( data ) {
                         alert('Form is successfully submitted');       
                      },
            error   : function(){
                         alert('Something wrong');
                      }
        });

        return false;
    });

});



回答2:


You need to either return a 204 HTTP status or make the request using JavaScript instead of by submitting the form (this is known as Ajax and there are numerous tutorials on the subject linked from the jQuery tutorials page).




回答3:


This is a link to get you started :

http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/



来源:https://stackoverflow.com/questions/10570825/stay-on-page-after-submitting-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!