简体   繁体   中英

Using AJAX to post checkbox list without submit button

I have a list of checkboxes, and want to submit the value of the checkbox when it is checked to PHP. I would prefer not to have a submit button, and rather post the value each time a checkbox is checked, so that the form does not refresh and clear the checked checkbox. However, each time I click one of the checkboxes, nothing happens.

Here is the HTML:

<form method="post" action="this.form.submit();" name="form1">
        <input type="checkbox" name="checkboxList[]" onclick="function1();" value="1">value1</input>
        <input type="checkbox" name="checkboxList[]" onclick="function1();" value="2">value2</input>
        <input type="checkbox" name="checkboxList[]" onclick="function1();" value="3">value3</input>
</form>

Here is the JQuery:

function function1() {
    var data = $("form1").serialize();
    $.ajax({
        url: "test.php", 
        type: "POST",
        async: true,
        cache: false,
        data: data, 
        success: function(data){ 
            alert(data) 
        }
    });
}

Edit: Sorry, forgot to mention that I have included the JQuery library.

And "test.php":

print_r($_POST);

Instead of var data = $("form1").serialize(); you should use var data = $("[name='form1']").serialize() . Using a plain string like that won't find you anything. You must specify that you want the element with the name, 'form1'

您需要使用onchange事件而不是onclick事件https://api.jquery.com/change/

Try this:

<form method="post" name="form1">
        <input type="checkbox" name="checkboxList[]" value="1">value1</input>
        <input type="checkbox" name="checkboxList[]" value="2">value2</input>
        <input type="checkbox" name="checkboxList[]" value="3">value3</input>
</form>

JQuery:

$("input[type=checkbox]").on("change", function() {
    var data = $("form1").serialize();
    $.ajax({
        url: "test.php", 
        type: "POST",
        async: true,
        cache: false,
        data: ({data: data}),
        dataType: "text", 
        success: function(data){ 
            alert(data) 
        }
    });
});

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