简体   繁体   中英

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:

<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. 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:

<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. Then the next time I try, it will work. 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:

<?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. That's the whole point using ajax (that you don't have to reload the page). 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.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. 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."

and when done() is reached in your code then ajax is "finished" for your specfic call, so there's no need for ajaxStop() there. 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:

die(json_encode($result)); says to end the application, but what you really want is to return the data:

echo json_encode($result);
return;

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