weixin_33704234 2018-03-27 13:14 采纳率: 0%
浏览 11

Ajax发布到PHP是空的

I am trying to make an AJAX post to php but for some reason my PHP says that the post is empty. I don't get an error message from PHP or in my console. The alert(data) at the end returns all the HTML in index.php and the var_dump(post) returns empty. console.log first is the console.log(aantal) the second is console.log(data) enter image description hereEnd of the console.log

script.js

$(document).ready(function () {

    var date = "date";
    var begin = "begin";
    var eind = "eind";
    var aantal = "aantal";


    $('#datum').change(function () {
        date = $("#datum").val();
        console.log(date);
    });
    $('#beginTijd').change(function () {
        begin = ($(this).val());
        console.log(begin);
    });
    $('#Tijdsduur').change(function () {
        eind = ($(this).val());
        console.log(eind);
    });
    $('#aantalSloepen').change(function () {
        aantal = ($(this).val());
        console.log(aantal);
        $.ajax({
            type: "POST",
            url: "index.php",
            data: {
                date: begin,
                quantity: aantal
            },
            success: function (data) {
                alert(data);
                console.log(data);
            }
        });
    });
});

index.php

<?php
var_dump($_POST);
$value1 = "";
$value2 = "";
if (isset($_POST['date'])) {
    echo "Yes, mail is set";
    $value1 = $_POST['date'];
    $value2 = $_POST['quantity'];
} else {
    echo "No, mail is not set";
}
echo $value1;
echo $value2;
  • 写回答

1条回答 默认 最新

  • weixin_33690367 2018-03-27 13:40
    关注

    You are calling index.php file from the ajax and the index.php file is loaded on page load. So when you call the ajax it will return whole html code of index.php to prevent that you have to add exit() function to prevent execute further. See code below.

    <?php
    
    $value1 = "";
    $value2 = "";
    if (isset($_POST['date']) && isset($_POST['quantity'])) {
        if (isset($_POST['date'])) {
            echo "Yes, mail is set";
            $value1 = $_POST['date'];
            $value2 = $_POST['quantity'];
        } else {
            echo "No, mail is not set";
        }
        exit;
    }
    
    <html>
        <!-- Your Code goes here -->
    </html>
    
    评论

报告相同问题?