简体   繁体   English

AJAX请求仅发生一次(PHP表单请求)

[英]AJAX request only happens once (PHP form request)

Here's roughly what I have for the main.php file.. A form, followed by where the data shows up and then the javascript: 这大致是我对main.php文件所拥有的。一种形式,然后是显示数据的位置,然后是javascript:

<form>
    <center><h3>Add new person:</h3></center>
    <div class="errors"></div>
    <input id="nameOfFruit" class="form-control" type="text" placeholder="Name" />
    <select id="typeOfFruit" class="selectpicker"  data-width="100%">
        <option data-name="99">Select Fruit...</option>
        <option data-name="1">Tomato</option>
        <option data-name="2">Banana</option>
        <option data-name="3">Grape</option>
    </select>
    <select id="nOfFruit" class="selectpicker"  data-width="100%">
        <option data-name="99"># of Fruit...</option>
        <option data-name="1">1</option>
        <option data-name="2">2</option>
        <option data-name="3">3</option>
    </select>
    <a href="#" class="btn" id="addFruit">ADD</a>
</form>

This select-picker is the bootstrap add on Silvio Moreto's site. 该选择器是Silvio Moreto网站上的引导程序添加。 Next I have some code where the tables for this data appear and are being read from the database. 接下来,我有一些代码,这些数据的表将出现在这些表中,并正在从数据库中读取。 And finally, I have the javascript: 最后,我有JavaScript:

<script>
    $(document).ready(function () {
        $('#wlFloorplans').selectpicker();
        $('#wlBedrooms').selectpicker();
    });

    jQuery('#addFruit').click(function () {

        var $opt = $("#typeOfFruit option:selected");
        var fruitString = $opt.attr("data-name");

        var str = "name=" + jQuery("#nameOfFruit").val()
            + "&type=" + fruitString
            + "&number=" + jQuery("#nOfFruit").val();

        jQuery.ajax({
            type: "post",
            url: "/adding_fruit.php",
            data: str,
            dataType: "json",
            success: function(result) {
                if (result.success == 1) {
                    $(document).ajaxStop(function () { location.reload(true); });
                    $('#typeOfFruit').selectpicker();
                    $('#nOfFruit').selectpicker();
                }
                else {
                    jQuery(".errors").html(result.errors);
                }
            }
        });
    });
</script>

The problem is that everytime I fill out the form, one of two things happen: 问题是,每次我填写表格时,都会发生以下两种情况之一:

a. 一种。 The first time I fill it through, it will go through the ajax call and not put any data in the database. 第一次填充它时,它将通过ajax调用,并且不会在数据库中放入任何数据。 Then the next time I try, it will work. 然后,下次我尝试时,它将起作用。 b. b。 The first time I try to fill out the form, it'll work (all the data enters the database, outputs on the table), but then the second time through, all the fields delete themselves when I press the add button and nothing gets placed into the DB. 第一次尝试填写表单,它将起作用(所有数据进入数据库,在表中输出),但是第二次,当我按下添加按钮时,所有字段都将自身删除,但没有任何结果放入数据库。

Edit: my adding_fruit.php file: 编辑:我的adding_fruit.php文件:

<?php
try {
    //DB SETUP
}
catch(PDOException $ex) {
}

$name = trim(isset($_POST['name']) ? $_POST['name'] : '');
$type = trim(isset($_POST['type']) ? $_POST['type'] : '');
$number = trim(isset($_POST['number']) ? $_POST['number'] : '');

$errors = Array();
if (sizeof($_POST) > 0) {
    if ($name === '') {
        $errors[] = '<div class="alert" role="alert">NEED A NAME</div>';
    }
}

if (sizeof($errors) > 0 || sizeof($_POST) == 0) {
    $result = array(
        "errors" => implode("", $errors),
        "success" => 0);
    die(json_encode($result));
}

$randID = md5(uniqid(rand(), true));

$sql = "INSERT INTO waitlist (id, name, type, number)
        VALUES ('".$randID."', '".$name."', '".$type."', '".$number."')";

$sth = $db->prepare($sql);
$sth->execute();

$result = array(
    "success" => 1);
die(json_encode($result));
?>

Do you see a problem with my code? 您看到我的代码有问题吗?

When using ajax you should not reload the entire page. 使用ajax时,您不应重新加载整个页面。 That's the whole point using ajax (that you don't have to reload the page). 这就是使用ajax的全部要点(不必重新加载页面)。 What I think you are looking for is to clear the form (resetting to its original state) after user has submitted and the server responded. 我认为您正在寻找的是在用户提交并服务器响应后清除表单(重置为原始状态)。

Try this: 尝试这个:

jQuery jQuery的

jQuery.ajax({
            type: "post",
            url: "/adding_fruit.php",
            data: str,
            dataType: "json",
            success: function(result) {
                if (result.success == 1) {
                    $('form').trigger("reset"); //Reset to the original state of the form
                    $('#typeOfFruit').selectpicker();
                    $('#nOfFruit').selectpicker();
                }
                else {
                    jQuery(".errors").html(result.errors);
                }
            }
        });

The

$(document).ajaxStop(function () { location.reload(true); });

is not needed, because ajaxStop is executed when ajax is finished undependently which ajax-call is made, not for a specific call like this. 不需要,因为ajaxStop是在ajax ajaxStop完成哪个ajax调用时执行的,而不是针对像这样的特定调用执行的。 From the documentation: 从文档中:

"Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event." “只要Ajax请求完成,jQuery就会检查是否还有其他未完成的Ajax请求。如果没有其他请求,jQuery会触发ajaxStop事件。”

and when done() is reached in your code then ajax is "finished" for your specfic call, so there's no need for ajaxStop() there. 当在代码中到达done()时,ajax将被“完成”以进行特定的调用,因此那里不需要ajaxStop() Therefore, if you want to reload the whole page after the call just do: 因此,如果您想在调用后重新加载整个页面,请执行以下操作:

//This would reload the whole page 
//(just as you were hitting the reload-button in the browser)
location.reload(true); 

php: 的PHP:

die(json_encode($result)); says to end the application, but what you really want is to return the data: 说结束应用程序,但是您真正想要的是返回数据:

echo json_encode($result);
return;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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