简体   繁体   中英

Submitting AJAX form, redirects instead of processing on page

So when a user accesses my page I have an ajax function that gets the number of rows in a database and spits out the number (works fine). I also have a form where the user can submit a word. What im trying to do is when the user submits a word to the database AJAX will take care of the submit and then run a function to get the new number of rows in the database.

This code redirects to the submit.php page instead of handling it all on the main page

AJAX

$(document).ready(function() {
   display();

   $('.add').on('submit', function (e) {
       e.preventDefault();
       $.ajax({
            type: 'post',
        url: 'submit.php',
        data: $('this').serialize(),
        success: function () {
            display();
        }
        });
    });


});

function display() {
    $(".container").load("ajax.php").hide().delay(500).fadeIn(1500);
}

HTML

<div class="container"></div>
    <form  action="submit.php" method="post">
        <input type="text" name="word">
        <input type="submit" class="add" name="add" value="add">
    </form>

ajax.php

<?php
        $conn = mysqli_connect('localhost', 'root', '', 'test') or die('error could not connect');
        $query = "SELECT * FROM test";
        $result = mysqli_query($conn, $query) or die ('error could not query');

        $num = mysqli_num_rows($result);

        echo '<h1>'.$num.'</h1>';

?>

Submit.php

<?php
    if(isset($_POST['add'])) {
        //Connect
        $word = $_POST['word'];

        $conn = mysqli_connect('localhost', 'root', '', 'test') or die('error could not connect');
        $query  = "INSERT INTO test VALUES(0, '$word')";
        mysqli_query($conn, $query) or die('error could not query');

    }
?>

You should hook the submit event up to the form , not the submit button .

Buttons don't have a submit event, which is why yours isn't being hooked up.

$('this').serialize();

应该:

$(this).serialize();

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