Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

jquery - AJAX - form submit, same page, PHP

EDIT: I have changed the AJAX code to what I am now using and I have also included JQuery in my code

I've read up on as much AJAX as I can and I am flat out failing!

My HTML form looks like this:

<form action="match_details.php" method="post" id="match_details">
....
<button type="submit" form="match_details" name="match_details" class="w3-button w3-block w3-mam w3-section" title="Update Match Postcode">Update</button>
            </form>

From Stack I've managed to get this AJAX:

<script type="text/javascript">
$(function(){
    $('button[type=submit]').click(function(e){

    e.preventDefault();

        $.ajax({
            type: "POST",
            url: "match_details.php",
            data: $("#match_details").serialize(),
            beforeSend: function(){
                $('#result');
            },
            success: function(data){
                $('#result').html(data);
            }
        });
    });
});
</script>

I've tried changing it from button to input and back again but nothing seems to change. The form still submits but it ignores the AJAX and the page refreshes.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to prevent the JS from submitting the form, and you're using the wrong form ID. Also, judging by the comments, you need to include jquery.

In the head of your HTML file, between <head> and </head> or just before the closing </body> tag, you can use the following:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

The following code may help you (though it's advised to not query the same page as your ajax request emits from):

<script type="text/javascript">
$(function(){
    $('button[type=submit]').click(function(e){

    e.preventDefault();

        $.ajax({
            type: "POST",
            url: "match_details.php",
            data: $("#match_details").serialize(),
            beforeSend: function(){
                $('#result');
            },
            success: function(data){
                $('#result').html(data);
            }
        });
    });
});
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...