Yamona Yamona - 4 months ago 19
Ajax Question

Multiple buttons in the same page submit to Ajax

I have multiple button in the same page like 50 maybe more to submit a single value to Ajax wordpress way. They look like this:

<input id="1-57977357564a7" class="button-primary" type="submit" value="Done"/>
<input id="2-57977357564a7" class="button-primary" type="submit" value="Done"/>
<input id="3-57977357564a9" class="button-primary" type="submit" value="Done"/>
// And so on, more buttons


Each button should update on row in some database table.
It should call
update_completed_todos()
using Ajax

add_action('wp_ajax_update_completed_todos', 'update_completed_todos');
add_action( 'wp_ajax_nopriv_update_completed_todos', 'update_completed_todos' );
function update_completed_todos() {
global $wpdb;
$table_name = $wpdb->prefix . 'todos';
$id = '';// Need to pass the id here some how
$result = $wpdb->get_results("SELECT id FROM " . $table_name . " WHERE id = '" .$id."'");
if (count ($result) > 0) {
$wpdb->update(
$table_name,
array(
'complete' => '10',
),
array( 'id' => $id )
);
}
}


I need to pass the
id
some how to this function.

What should I write in Ajax to pass the
id
?

And how I can make each button target this Ajax?

As Ajax may not pass
id
instead of a value, what should I do to pass any value to Ajax here?

The Ajax should be something like:

$.ajax({
url: "<?php echo esc_js( admin_url( 'admin-ajax.php' ) ) ?>",
type: "POST",// I am not sure
data: // Something I don't know here
//may be more here
});

Answer

Try:

HTML:

<input id="1-57977357564a7" class="button-primary" type="submit" value="Done" onclick="ajax($(this));return false;"/>
<input id="2-57977357564a7" class="button-primary" type="submit" value="Done" onclick="ajax($(this));return false;"/>
<input id="3-57977357564a9" class="button-primary" type="submit" value="Done" onclick="ajax($(this));return false;"/>

Javascript:

function ajax($this) {
    var id = $this.attr("id");


    $.ajax({
        method: "POST",
        url: "your address",
        dataType: "your response type",
        data: {
            id: id
        },
        success: function (response) {
            console.log(response);
        }
    });
}

PHP:

if (isset($_POST["id"])) {
    var_dump($_POST["id"]);
    exit;
}

of course you must change dataType and url to your data.