AJAX within a foreach loop

♀尐吖头ヾ 提交于 2019-12-11 16:10:52

问题


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 fire even if i don't use the onclick event. What im basically doing is writing out a list from the DB and adding a remove button to the row. when the remove link is clicked, it will fire a query to update a field in the DB for item.

My index.php file

<?php foreach ($items as $item) : ?>
<tr>
    <td><?php echo $item['item_name']; ?></td>
    <td><a href="#" onclick="ajax call(arguments)" ></a></td>
</tr>
<?php endforeach; ?>

My PHP code: (note: I am using wordpress's $wpdb to query the WP database. query is valid. There is no user input, and its on an admin page so dont worry about prepare() or other injection defenses. )

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

($remove_option is populated earlier in the index.php page, and $item_id comes from $items array)

I need to pass 2 variables through the ajax call, populate $remove_option and $item_id. fire the query, return to index.php page.

How do I use ajax to achieve this? I'm completely unfamiliar with ajax, and i am not using a plugin for WP, only php scripts.


回答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');
function update_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

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



回答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.



来源:https://stackoverflow.com/questions/25705398/ajax-within-a-foreach-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!