So I'm running into an issue and I can't seem to figure it out, so I'm reaching out to see if anyone can help me.
I have a method called show_instagram_table()
which has the following:
private function show_instagram_table(): string
{
$table = '';
if ($authenticated_users = get_option('instagram_authenticated_users')) {
foreach ($authenticated_users as $authenticated_user) {
$table .= '<table ><tbody>';
// ----------- Remove other items non-needed ---------------
if (Instagram::get_items()) {
$table .= $this->show_authenticated_buttons($authenticated_user);
}
$table .= '</tbody></table>';
}
}
return $table;
}
Which calls on show_authenticated_buttons()
:
private function show_authenticated_buttons($user): string
{
$buttons = '<tr>';
$buttons .= $this->show_deauthorize_instagram_button($user);
$buttons .= '</tr>';
return $buttons;
}
This calls on show_deauthorize_instagram_button()
:
private function show_deauthorize_instagram_button($user): string
{
return '<td><button style="margin-right: 5px">Deauthorize</button>';
}
Using AJAX, when the button is clicked, is will target that method and send the response back to PHP:
So..
jQuery('.instagram-deauthorize').click(function(e) {
e.preventDefault();
const data = {
'action': 'deauthorize_instagram_via_button',
};
jQuery.post(instagram_object.ajax_url, data, function() {
window.location = url;
});
});
Will trigger this method (I've tested it, it deletes the option):
public function deauthorize_instagram_via_button($user)
{
if (!get_option('instagram_authenticated_users')) {
return;
}
$users = get_option('instagram_authenticated_users');
if (count($users) === 1) {
delete_option('instagram_authenticated_users');
$this->instagram->delete_cache();
}
exit;
}
Here is where I am stuck:
I am wanting to send authenticated_user
data inside the foreach from show_instagram_table
all the way to my deauthorize_instagram_via_button()
method, but it's impossible for me to target it.
Does anyone know what I can change/improve? I've already tried passing it down using $user
params and no luck.
(Sorry for the lack of pictures, I am not allowed to post them).
Thanks all!
CodePudding user response:
You can add one more attribute for each row.
You can use something like data-id
or else.
For example :
private function show_authenticated_buttons($user): string
{
$buttons = '<tr data-id="'.$user->id.'">';
$buttons .= $this->show_deauthorize_instagram_button($user);
$buttons .= '</tr>';
return $buttons;
}
Then, you can get each user id (by using $(this).attr("data-id")
).
jQuery('.instagram-deauthorize').click(function(e) {
e.preventDefault();
const data = {
'action': 'deauthorize_instagram_via_button',
'user_id': $(this).attr("data-id")
};
jQuery.post(instagram_object.ajax_url, data, function() {
window.location = url;
});
});
Finally your deauthorize_instagram_via_button
will get the user_id.