Skip to content Skip to sidebar Skip to footer

Ajax Within A Foreach Loop

I am unfamiliar with AJAX and am having a difficult time trying to learn it for what I need. I need to write ajax calls within a foreach loop. if i just use PHP calls they will all

Solution 1:

PHP part

http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

add_action('wp_ajax_update_this', 'update_this_func');
add_action('wp_ajax_nopriv_update_this', 'update_this_func');
functionupdate_this_func(){

    $remove_option = $_POST['remove_option'];
    $item_id       = $_POST['item_id'];

    global$wpdb;

    $wpdb->query("UPDATE " . $wpdb->prefix."item
                  SET is_removed =" . $remove_option . "
                  WHERE item_id =" . $item_id );

    return json_encode(['status' => 'Updated!']); // return status as json

}

Ajax call

http://codex.wordpress.org/AJAX_in_Plugins

functiononClickingThis(rem_opt,itemid){
  $.ajax({
      url: ajax_url, // You can get this from admin_url('admin-ajax.php') functiontype: 'POST',
      data: {action: 'update_this', remove_option: rem_opt, item_id: itemid },
      dataType: 'json',
      success: function(response){
        console.log(response);
      }
  });
}

Solution 2:

can I achieve this with AJAX?

Yes

is there a better approach to what I'm trying to achieve?

If you want to send data from the client to the server then ajax is the best way to do so.

Post a Comment for "Ajax Within A Foreach Loop"