weixin_33701294 2017-11-18 18:05 采纳率: 0%
浏览 108

Ajax将值传递给PHP

I would like to pass multiple values to php via ajax (on same page), here's my code:

HTML (user_list.php):

<button type="submit" class="button button-block savebutton" name="save_changes"/>
        Save changes</button>

Javascript (user_list.php):

$(".savebutton").on("click", function (event) {
    event.preventDefault();
    var js = [];
    var i = 0;
    $('select').each(function () {
        var a = {"id": "", "permission": ""}
        a.id = $(this).val();
        a.permission = $(this).children(":selected").text();
        js.push(a);
        alert(js[i].permission + " - "+js[i].id);
        i++;
    });
    $.ajax({
        type: "POST",
        url: "user_list.php",
        data: {result: JSON.stringify(js)}
    });
    return false;
});

PHP (user_list.php):

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

if (isset($_POST['delete_selected'])) { // Button to delete selected user(s)

    if (!empty($_POST['check_list'])) {
        foreach ($_POST['check_list'] as $id) {
            $sql = "DELETE FROM users WHERE id=$id";
            $mysqli->query($sql);
            header("Refresh:0"); //Refresh page
        }
    }

}

// Other if above works fine
elseif (isset($_POST['result'])){
    // I want to get the js array with the values here after ajax
}

else {
    // But I get here, and I don't get the js array
}
}

So I have 2 problems, the first is that I pass the elseif, and the second is that I dont get the array. I think the problem is with ajax, since filling the array works properly

EDIT: I moved the php to a different page, now it's working.

  • 写回答

4条回答 默认 最新

  • weixin_33676492 2017-11-18 18:09
    关注

    Try with this

    <button type="submit" class="button button-block savebutton" name="save_changes[]"/>Save changes</button>
    
    评论

报告相同问题?