How would I Split my PHP table being displayed on a website using HTML into to different pages

Working on this for school and trying to split my PHP table being displayed on a website using HTML into to different pages. How do I do it?

Below is the code I’m working with. It would be preferable if there was a little page indicator at the bottom of the code that users could use to switch between table pages.

  <div class="container mt-4">
      <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h4>Current Active Orders
                  
                    </h4>
                </div>
                <div class="card-body">

                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Site Name</th>
                                <th>Unit Number</th>
                                <th>Street Number</th>
                                <th>Street Name</th>
                                <th>Street Type</th>
                                <th>Suburb</th> 
                                  <th>Post Code</th> 
                                <th>Nubmer of Pools</th>
                                <th>Local Goverment Authority</th>
                                <th>Shared Pool</th>
                              
                            </tr>
                        </thead>
                        <tbody>
                            <?php
    
                            require('conn.php');
                                $query = "SELECT * FROM norm_pool";
                                $result = mysqli_query($conn, $query);

                                if(mysqli_num_rows($result) > 1)
                                {
                                      while($row = $result->fetch_assoc()) 
                                    {
                                        ?>
                                        <tr>
                                              <td><?= $row['ID']; ?></td>
                                            <td><?= $row['sitename']; ?></td>
                                            <td><?= $row['unitno']; ?></td>
                                            <td><?= $row['streetno']; ?></td>
                                            <td><?= $row['streetname']; ?></td>
                                            <td><?= $row['streettype']; ?></td>
                                              <td><?= $row['suburb']; ?></td>
                                                <td><?= $row['postcode']; ?></td>
                                            <td><?= $row['noofpools']; ?></td>
                                            <td><?= $row['localgovauth']; ?></td>
                                            <td><?= $row['sharedpool']; ?></td>
                                    
                                            
                                        </tr>
                                        <?php
                                    }
                                }
                                else
                                {
                                    echo "<h5> No Users Found </h5>";
                                }
                              
                            ?>
                            
                            
                        </tbody>
                    </table>

                </div>
            </div>
        </div>
    </div>
</div>

How to change the amount & mobileid from the array of $result & $winnum by using the foreach()

<?php
include("include/connection.php");

function getwindata($con) {    
    $query = "SELECT userid,amount FROM tbl_walletsummery WHERE actiontype='win'";
    $results = mysqli_query($con, $query);
    if( $results === false ) {
        throw new Exception('Query failed: ' . $con->error);
    }
    $msg = '';
    $msg1 = '';
    $mobileid = '';
    foreach($results as $result) {
        $query1 = "SELECT id,mobile FROM tbl_user WHERE id={$result['userid']}";
        $getuser = mysqli_query($con, $query1);
        $msg1 .= " Wins {$result['amount']}</span1>";
        $mobileid = '';
        foreach($getuser as $winnum) {
        $mobileid .= substr_replace($winnum['mobile'], "******", 2, 6);
        $msg .= "<span1>Congratulations To $mobileid $msg1";
        }

    }
return $msg;
}
$mob = getwindata($con);
?>

I want to get the matched data as 9999999999 mobile number wins 1k and his user id 1 then tbl_walletsummery table has the winning amount and userid only and tbl_user has mobile and mail and idf the user so i want to match them to get the proper winner number & winning amount to be print in span tag

Can I make a Laravel Blade variable optional?

I have made a blogging application in Laravel 8.

The (single) article view displays a comments form and I am now working on adding a comments reply functionality.

I have moved the code for the comments form in comment-form.blade.php so that I can use both under the article and under every comment.

The form looks like so:

<form method="post" action="{{ route('comment.submit') }}" autocomplete="off">
@csrf
  <fieldset>

      <input type="hidden" name="article_id" value="{{ $article->id }}">
      <input type="hidden" name="parent_id" value="{{ $comment->id }}">

      <div class="form-field">
          <input type="text" name="name" id="name" class="h-full-width h-remove-bottom" value="{{ Auth::user()->first_name }} {{ Auth::user()->last_name }}">
      </div>

      <div class="message form-field">
          <textarea name="msg" id="message" class="h-full-width" placeholder="Your Message"></textarea>

          @error('msg')
          <p class="help-block text-danger">{{ $message }}</p>
          @enderror
      </div>
      <br>
      <input name="submit" id="submit" class="btn btn--primary btn-wide btn--large h-full-width" value="Add Comment" type="submit">
  </fieldset>
</form>

The problem

For the form that is not under a comment (because it is not intended for adding a reply), the line <input type="hidden" name="parent_id" value="{{ $comment->id }}"> throws the below error, because there is no $comment->id:

Undefined variable: comment

Questions

  1. What is the most reliable way to fix this bug?
  2. How can I make the $comment variable optional?

Authorize.net having the transactions within the users/customers payment history

When transactions get settled, however, they’re only recorded as unsettled transactions. What are the options for recording it per customer’s payment history rather than all transactions getting saved at the unsettled transactions?

When transactions occur in my system, is it possible to have the transactions recorded on every customer’s payment history (customer Information Manager) by entering their customer_profile_id?

How to control a payment plan period [closed]

Suppose a user create an account today the 22 of April on my website and I have set the period to 30days how can i get a code that will automatically block the user from the dashboard when they try to login after their 30days payment is expired. Instead, upon login they should be redirected to a update payment page till they renew their payment before they will have access to the dashboard again

I tried using php to count and compare the date of login with the sign up date stored in the DB but now I faced problems with the redirection because I didn’t know how to redirect the user automatically to the update payment page and also back to the dashboard after payment is been updated

How could I match submitted array fields with the MYSQL database fields to update them correctly in PHP

I have a database table with the following schema and would like to update it correctly when a booking form is submitted with the correct matching ticket type and ticket values:

listing_id regular_ticket _other_ticket[0][name] _other_ticket[1][name] regular_ticket_sold _other_ticket[0][sold] _other_ticket[1][sold]
149 regular-ticket solo-ticket group-ticket 5 2 1

The array being posted after submitting the form could look like this(when buying all the ticket types):

{"listing_id":"149","date_start":"2023-04-28","date_end":"2023-04-28","tickets":[{"ticket":"regular-ticket","value":"1"},{"ticket":"solo-ticket","value":"1"},{"ticket":"group-ticket","value":"1"}]}

And like this when a user selects only one ticket type:

{"listing_id":"149","date_start":"2023-04-28","date_end":"2023-04-28","tickets":[{"ticket":"solo-ticket","value":"1"}]}

What I have tried:

// update tickets sold
function update_ticket_sold( $tickets, $listing_id )
    {
        $countable = array_column($tickets,'value'); //get ticket count from array
        $other_tickets = get_post_meta( $listing_id, '_other_tickets', true);
        
        if (!empty($tickets[0]['ticket']) && $tickets[0]['ticket'] == 'regular-ticket') {
           //$tickets_count =  (float) $countable[0];
           $already_sold_tickets = (int) get_post_meta($listing_id,'regular_ticket_sold',true);
           $sold_now = $already_sold_tickets + (float) $countable[0];
           update_post_meta($listing_id,'regular_ticket_sold',$sold_now);
           }

        if(isset($other_tickets) && is_array(($other_tickets))){
            $i = 0;
            foreach ($other_tickets as $key => $ticket) {
               if(in_array(($ticket['sold']),array_column($tickets,'sold'))) {
                    $column = '_other_tickets[][sold]';
                    $already_sold_tickets = (int) get_post_meta($listing_id,$column,true);
                    $sold_now = $already_sold_tickets + (float) $countable[$i];
                    update_post_meta($listing_id,$column,$sold_now);
                            $i++;
                        }
                    }
                }
    }

What I would like to achieve:

  • regular_ticket ticket type to update values in regular_ticket_sold
  • _other_ticket[0][name] ticket type should update value in _other_ticket[0][sold] and
  • _other_ticket[1][name] to _other_ticket[1][sold]

When the regular ticket is selected, the functions updates the database correctly but when any of the other ticket types are selected they never get updated and I get Error: Warning: Undefined array key 1 and Warning: Undefined array key 2

I have been stuck for weeks with this problem. Kindly point me in the right way.

Magento 2 How to get td value using script and assign that value to php variable in same phml file?

I have php variable called itemId in same phtml file and i got td value using js. now i need to assign that var id value to $itemId variable.

<?php

$itemId = null;

?>



        <table class="item-table">
        
            <tr data-row="product-item" id="<?= $block->escapeHtmlAttr($item->getId()) ?>" onclick="getTableRowData(this)">
              
                <td class="item-id" id="item-id">
                    <span class="item-id-span">
                        <?php echo $item->getId(); ?>
                    </span>
                </td
            </tr>
    </table>


<script>

function getTableRowData(row) {
var cells = row.getElementsByTagName('td');
        var id = cells[1].innerHTML;
}

</script>

Strange issue with API data in WordPress

I’m experimenting with an API which returns acronym definitions. My site has 2 custom post types, ‘acronym’ and ‘definition’. I’m generating a random 2 – 3 letter string and feeding it to the API. The idea is that, if the API returns data, the randomly generated acronym is added as an ‘acronym’ post and the definitions are added as ‘definition’ posts. The definitions are then linked to the acronym via an ACF field. If the randomly generated acronym already exists as an ‘acronym’ post, then the definitions are simply created and assigned to that acronym post.

I’m running the code using the WP admin footer hook for testing purposes. Here’s a boiled down version of my code:

add_action('admin_footer', 'api_fetch');

function api_fetch(){

    $length = rand(2, 3);
    $randacro = '';
    for ($i = 0; $i < $length; $i++) {
        $randacro .= chr(rand(97, 122));
    }

    // Set the endpoint URL
    $url = 'https://apiurl.com/xxxxxxxxx/' . $randacro . '&format=json';

    // Initialize curl
    $curl = curl_init($url);

    // Set curl options
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json'
    ));

    // Send the request and get the response
    $response = curl_exec($curl);

    // Close curl
    curl_close($curl);

    // Handle the response
    if ($response) {
        
        $resarray = json_decode($response);

        echo '<div style="padding: 0 200px 50px;">Randomly generated acronym: ' . strtoupper($randacro) . '<br><br>';

        
        if ( isset($resarray->result) ) {

            if (post_exists(strtoupper($randacro))) {
                $args = array(
                    'post_type' => 'acronym',
                    'post_title' => strtoupper($randacro),
                    'posts_per_page' => 1,
                );
                $query = new WP_Query( $args );
                if ( $query->have_posts() ) {
                    $acro_id = $query->posts[0]->ID;
                    wp_reset_postdata();
                }
            } else {
                $new_acro = array(
                    'post_title'    => strtoupper(wp_strip_all_tags($randacro)),
                    'post_status'   => 'publish',
                    'post_author'   => 1,
                    'post_type'     => 'acronym',
                );
                $acro_id = wp_insert_post( $new_acro );
            }

            if ($acro_id) {

                echo 'Found/created acronym post: ID = ' . $acro_id . ' - Title = ' . get_the_title($acro_id) . '<br><br><pre>';

                foreach($resarray->result as $result) {
                    print_r($result);
                    echo '<br><br>';
                    
                    if (!is_string($result)) {
                        $def = $result->definition;
                        if ( get_post_status( $acro_id ) && !post_exists( $def ) ) {
                            $new_def = array(
                                'post_title'    => wp_strip_all_tags($def),
                                'post_status'   => 'publish',
                                'post_author'   => 1,
                                'post_type'     => 'definition',
                            );
                            $new_def_id = wp_insert_post( $new_def );
                            update_field('acronym', $acro_id, $new_def_id);
                            update_field('likes', '0', $new_def_id);
                            $defs_published++;
                        }
                    }
                    
                }
            }
            

        }

        echo '</pre></div>';
        
    } else {
        echo '<div style="padding: 0 200px;">No response</div>';
    } 

}

The issue I’m having is that, when I refresh the page to run the code again after the code has created a new acronym, and it then finds an existing acronym, it’s assigning the definitions to the previously created new acronym. For example, this time that the code was run, it created the acronym post “VC” as it didn’t already exist:

Output example 1

I refreshed the page to run the code again, and the randomly generated acronym already exists as an ‘acronym’ post, but the definitions are being assigned to the previously created acronym post (shown as “Found/created acronym post”):

Output example 2

I’ve tried adding wp_reset_postdata() and wp_reset_query() throughout my code. I’ve tried setting the $acro_id to null at the beginning and end of the code and I’ve tried unsetting all the variables at the end of my code, but none of this has worked. Any ideas where I might be going wrong here?

Update xml namespaces with data from a PHP form

In the example below, the PHP form updates the XML with the text entered in the fields.

XML file labela.xml:

<?xml version="1.0" encoding="UTF-8"?>
<inventors>
  <person>
    <name>change1</name>
    <comment>change2</comment>
  </person>
</inventors>

The PHP form used to update 2 texts in XML:

<script src="https://code.jquery.com/jquery-latest.min.js"></script>
 <?php
 $xml = new DOMDocument('1.0', 'utf-8');
 $xml->formatOutput = true; 
 $xml->preserveWhiteSpace = false;
 $xml->load('labela.xml');

//Get item Element
$element = $xml->getElementsByTagName('person')->item(0);  

//Load child elements
$name = $element->getElementsByTagName('name')->item(0);
$comment = $element->getElementsByTagName('comment')->item(0) ;

//Replace old elements with new
$element->replaceChild($name, $name);
$element->replaceChild($comment, $comment);
?>

<?php
if (isset($_POST['submit']))
{
$name->nodeValue = $_POST['namanya'];
$comment->nodeValue = $_POST['commentnya'];
htmlentities($xml->save('labela.xml'));
}
?>

<form method="POST" action=''>
name <input type="text-name" value="<?php echo $name->nodeValue  ?>" name="namanya" />
comment  <input type="text-comment" value="<?php echo $comment->nodeValue  ?>"  name="commentnya"/>
<input name="submit" type="submit" />
</form>

How to proceed so that you have the same result with the xml twith the following structure:

<pt:document xmlns:pt="http://schemas.brother.info/ptouch/2007/lbx/main"
xmlns:style="http://schemas.brother.info/ptouch/2007/lbx/style"
xmlns:text="http://schemas.brother.info/ptouch/2007/lbx/text"
xmlns:barcode="http://schemas.brother.info/ptouch/2007/lbx/barcode"
>

<pt:body currentSheet="Folha 1">
<style:sheet name="Folha 1">
<pt:objects>
<barcode:barcode><barcode:qrcodeStyle model="2" eccLevel="15%"/><pt:data>change1</pt:data></barcode:barcode>

<text:text>
<text:textStyle vertical="false"/>
<pt:data>change2</pt:data>
<text:stringItem charLen="7"><text:ptFontInfo><text:logFont name="Arial"/></text:ptFontInfo></text:stringItem>
</text:text>
    <text:text><text:textStyle vertical="false"/><pt:data>change3</pt:data></text:text>
</pt:objects>
</style:sheet>
</pt:body>
</pt:document>

thanks in advance to everyone who takes their time to help

Is there a way to save search results (i.e. allow user to re-enter/refresh url of search results) and still see results

Sorry if I explained it poorly. I’m very new to both Laravel and React and it would be best displayed through these examples. Essentially, I’m sending a search to Laravel from React:

    const { data, setData, post, processing, errors, reset } = useForm({
        searchTerm: "",
        searchBy: "",
    });

    const submit = (e) => {
        e.preventDefault();

        post(route("searchCompletion", [data.searchTerm, data.searchBy]));
    };

The search term is the search term and the search method is either category or caption. I have a post route which works, but I’m trying to implement get so that I can re-retrieve the posts that are displayed (i.e. not get an error from http://localhost:8000/search/i?Caption=):

Route::post('/search/{searchTerm}', [SearchController::class, 'index'])->name('searchCompletion');
Route::get('/search/{searchTerm}', [SearchController::class, 'index'])->name('getSearchCompletion');

Also, here is my SearchController for reference:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppModelsPost;
use InertiaInertia;

class SearchController extends Controller
{
    public function index(Request $request) {
        $postsFromSearch = Post::latest()->get();
        $posts = [];

        $userArr = [];

        if ($request->searchBy == "Caption") {
            foreach($postsFromSearch as &$post) {
                if(str_contains($post->caption, $request->searchTerm)) {
                    array_push($posts, $post);
                    
                    array_push($userArr, $post->user->load('profile'));
                }
            }
        }

        return Inertia::render('Posts/Index')->with(compact(['posts', 'userArr']));



    }
}

How to re-render posts with url info.

Doctrine OneToMany Relation with two joins

I have the following table schema:

A table where persons are stored

CREATE TABLE `cdb_person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(60) COLLATE utf8mb4_unicode_520_ci NOT NULL,
  `vorname` varchar(30) COLLATE utf8mb4_unicode_520_ci NOT NULL,
  PRIMARY KEY (`id`))
);

A table where groups are stored

CREATE TABLE `cdb_gruppe` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `bezeichnung` varchar(255) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
  PRIMARY KEY (`id`))

A table where the membership of a person in a group ins stored

CREATE TABLE `cdb_person_gruppe` (
  `person_id` int(11) NOT NULL,
  `gruppe_id` int(11) NOT NULL,
  `group_member_status` varchar(20) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT 'active',
  `comment` varchar(255) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
  PRIMARY KEY (`person_id`,`gruppe_id`),
  CONSTRAINT `cdb_person_gruppe_gruppe_id_cdb_gruppe_id` FOREIGN KEY (`gruppe_id`) REFERENCES `cdb_gruppe` (`id`),
  CONSTRAINT `cdb_person_gruppe_person_id_cdb_person_id` FOREIGN KEY (`person_id`) REFERENCES `cdb_person` (`id`)
)

For group memberships there can be fields defined per group.

CREATE TABLE `cdb_person_gruppe_field` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `gruppe_id` int(11) NOT NULL,
  `fieldname` varchar(255) COLLATE utf8mb4_unicode_520_ci NOT NULL,
  `note` varchar(1024) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
  `sortkey` int(11) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  CONSTRAINT `cdb_person_gruppe_field_gruppe_id_cdb_gruppe_id` FOREIGN KEY (`gruppe_id`) REFERENCES `cdb_gruppe` (`id`)
)

The value of the defined fields for the memberships can be saved in this table

CREATE TABLE `cdb_person_gruppe_fielddata` (
  `person_gruppe_field_id` int(11) NOT NULL,
  `person_id` int(11) NOT NULL,
  `value` varchar(512) COLLATE utf8mb4_unicode_520_ci NOT NULL,
  PRIMARY KEY (`gemeindeperson_gruppe_field_id`,`person_id`),
  CONSTRAINT `cdb_person_gruppe_fielddata_person_gruppe_field_id_cdb_person_gruppe_field_id` FOREIGN KEY (`person_gruppe_field_id`) REFERENCES `cdb_person_gruppe_field` (`id`),
`cdb_person_gruppe_fielddata_person_id_cdb_person_id` FOREIGN KEY (`person_id`) REFERENCES `cdb_person` (`id`)

);

I have a Entity GroupMember for the table cdb_person_gruppe.
There i want to add a relationship to the table cdb_person_gruppe_fielddata so that i have all the field data for the person in this group. But i need two joins to get only the necessary fields because the table cdb_person_gruppe_field holds the info for which group the field is defined.

So how can i make this OneToMany relationship?

To get all field values for a member in plain sql i would write this query:

select * from cdb_person_gruppe
JOIN cdb_person_gruppe_field ON cdb_person_gruppe.gruppe_id = cdb_person_gruppe_field.gruppe_id
JOIN cdb_person_gruppe_fielddata ON cdb_person_gruppe_fielddata.person_id = cdb_person_gruppe.person_id
WHERE cdb_person_gruppe.gruppe_id = 12 AND cdb_person_gruppe.person_id = 5;

How to update my jquery/PHP function to add/remove user as favorites in (WordPress) users list

I have a WordPress website in which I list down all the users (based on MemberPress subscription), and users can save other users as favorites. The function works well when saving a user as favorite, it stores and updates as it should, and it’s retreived when I check on a different place/browser.

But removing a user as favorite doesn’t work. Here is what happens:

  • One page load, when I click on ‘remove from favorites’, it acts like I clicked on ‘save to favorites’, the text ‘remove from favorites’ doesn’t change. On a second click on the same ‘remove from favorites’, the text changes, and the button is updated, it seems everything goes well accoding to the log, but on page reload, nothing is saved, and it’s back to ‘remove from favorites’.

  • A different situation, on page load, I click on ‘save to favorites’ of one user, and ‘save to favorites’ of another one afterwards, it seems to be fine. But on page reload, only the second one is actually saved, the first one is back to ‘save to favorites’. Same goes for when i click on 3 or more ‘save to favorites’, and reload the page, only the last one is saved.

This is my users list in PHP

function display_users($args = array(), $show_all_users = true)
{
    $default_args = array(
        'orderby' => 'name',
        'order' => 'ASC',
        'role' => 'subscriber',
        'search' => '',
    );
    $args = wp_parse_args($args, $default_args);

    $wp_user_query = new WP_User_Query($args);

    if (!empty($wp_user_query->results)) {
        $output = '<div class="user-grid">';
        foreach ($wp_user_query->results as $user) {
            $mepr_user = new MeprUser($user->ID);
            if (empty($mepr_user->active_product_subscriptions('ids'))) {
                continue;
            }
            // Check if only favorites should be displayed
            if (!$show_all_users) {
                $user_id = get_current_user_id();
                $favorites = get_user_meta($user_id, 'favorites', true);
                if (!in_array($user->ID, $favorites)) {
                    // If user is not in favorites list, skip to the next user
                    continue;
                }
            }
            $output .= '<div class="user">';
            $output .= '<a href="' . get_author_posts_url($user->ID) . '">';
            if (get_field('mepr_avatar_profile', 'user_' . $user->ID)) {
                $avatar = get_field('mepr_avatar_profile', 'user_' . $user->ID);
                $class = 'user-image-bw';
            } else {
                $avatar = '/wp-content/uploads/2023/04/new-color-community-1.png';
                $class = 'default-image-avatar';
            }

            $output .= '<div class="user-image">';
            $output .= '<img class="' . $class . '" src="' . esc_url($avatar) . '" alt="Author Avatar" />';
            $output .= '</div>';

            if (get_field('mepr_open_to_connect', 'user_' . $user->ID) == 'always-feel-free-to-reach-out') {
                $output .= '<p class="user-connect">Let's connect</p>';
            }

            $output .= '<div class="user-name">' . get_field('first_name', 'user_' . $user->ID) . '</div>';
            $output .= '<div class="user-info">';
            $current_work = get_field('mepr_current_work', 'user_' . $user->ID)[0];
            $current_work = str_replace('-', ' ', $current_work);
            $output .= '<p class="user-current-work">' . $current_work . '</p>';
            $output .= '</div>';
            $output .= '</a>';
            // Add favorite button
            if (is_user_logged_in()) {
                $user_id = get_current_user_id();
                $favorites = get_user_meta($user_id, 'favorites', true);
                if (!is_array($favorites)) {
                  $favorites = array(); // set $favorites to an empty array if it is not already an array
                }
                $nonce = wp_create_nonce('save_user_favorites');
                $output .= '<button class="favorite-button" data-user-id="' . $user->ID . '" data-favorites="' . esc_attr(json_encode($favorites)) . '" data-is-favorite="' . (in_array($user->ID, $favorites) ? 'true' : 'false') . '" data-nonce="' . $nonce . '">' . (in_array($user->ID, $favorites) ? 'Remove from favorites' : 'Add to favorites') . '</button>';
              }      

            $output .= '</div>';
        }
        $output .= '</div>';
    } else {
        $output = '<p>No users found.</p>';
    }

    return $output;
}

This is my PHP add to favorites function

// save favorites function
function save_user_favorites() {
    if (!isset($_POST['favorites'])) {
      wp_send_json_error('Favorites not provided');
    }
  
    // Verify nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'save_user_favorites')) {
      wp_send_json_error('Invalid nonce');
    }
  
    // Check if user is logged in
    if (!is_user_logged_in()) {
      wp_send_json_error('User not logged in');
    }
  
    // Get user ID
    $user_id = get_current_user_id();
  
    // Get favorites
    $favorites = isset($_POST['favorites']) ? $_POST['favorites'] : array();
  
    // Update user meta
    update_user_meta($user_id, 'favorites', $favorites);
  
    wp_send_json_success();
  }
  
  add_action( 'wp_ajax_nopriv_save_user_favorites', 'save_user_favorites' );
  add_action( 'wp_ajax_save_user_favorites', 'save_user_favorites');

This is my jQuery

$('.favorite-button').click(function(e) {
  e.preventDefault();

  var button = $(this);
  var userId = button.data('userId');
  var nonce = button.data('nonce');
  // get existing favorites from the data attribute of the button
  var favorites = button.data('favorites') || [];

  // Add or remove user from favorites
  if (userId !== "") { 
    const indexToRemove = favorites.indexOf(userId);

    if (!favorites.includes(userId)) { 
      favorites.push(userId);
      console.log(`User ${userId} added to favorites.`);
    } else {
      favorites.splice(indexToRemove, 1);
      console.log(`User ${userId} removed from favorites.`);
    }

    // Save favorites to the user metadata via AJAX 
    $.post(ajaxurl, {
      'action': 'save_user_favorites',
      'favorites': favorites,
      'nonce': nonce,
      'user_id': userId // add user ID to request parameters,
    })  
    .done(function(response) {
      console.log('Favorites saved:', response);
      // update the favorites attribute of the button
      button.data('favorites', favorites);
    })
    .fail(function(xhr, status, error) {
      console.log('Failed to save favorites:', error);
      console.log('Server response:', xhr.responseText);
    });
  } else {
    console.log(`Cannot add/remove user with empty ID`);
  }

  // Toggle button text and data attribute
  button.text(favorites.includes(userId) ? 'Remove from favorites' : 'Add to favorites');
});

Trying in a different way

I’ve also tried a different way for the ajax request, by first storing it as localstorage, and updating the list of favorites on page reload. This worked really well, and as it should (adding/removing users), but I get an error on page reload when it tries to store it in favorites (not localstorage).

What happens on reload is that it’s not actualy saved on the server side, only locally, and I get an ouput like this on the console:

from the update user Array []
from the update user Array []
from the update user Array []
from the update user Array(4) [ 420, 442, 449, 447 ]
from the update user Array []

And that keeps going, with only an array with values of the ones I saved.
Next to it, it says, also a lot of times in firefox:

Failed to save favorites: 
Server response: undefined
Failed to save favorites: 
Server response: undefined

In chrome:

Favorites saved: {success: false, data: 'Favorites not provided'} 
data: "Favorites not provided"
success: false
[[Prototype]]: Object

This is my other jQuery that could be used instead of the above, for first saving it locally

// get existing favorites from localStorage, or initialize to empty array
var favorites = JSON.parse(localStorage.getItem('favorites') || '[]');

$('.favorite-button').click(function(e) {
  e.preventDefault();

  var button = $(this);
  var userId = button.data('userId');

  // Add or remove user from favorites if userId is not empty
  if (userId !== "") {
    var isFavorite = button.data('isFavorite');
    var nonce = button.data('nonce');

    const userIdToRemove = userId; // Replace with the actual user ID you want to remove
    const indexToRemove = favorites.indexOf(userIdToRemove);

  // Add or remove user from favorites
  if (!favorites.includes(userId)) {
    favorites.push(userId);
    console.log('user added to favorites')
  } else {
    favorites.splice(indexToRemove, 1);
    console.log('user deleted from favorites')
  }

  // Save favorites to localStorage
  localStorage.setItem('favorites', JSON.stringify(favorites));

  // Save favorites to user metadata
  $.post(ajaxurl, {
    'action': 'save_user_favorites',
    'favorites': favorites,
    'nonce': nonce,
    'user_id': userId // add user ID to request parameters
  })  
  .done(function(response) {
    console.log('Favorites saved:', response);
  })
  .fail(function(xhr, status, error) {
    console.log('Failed to save favorites:', error);
    console.log('Server response:', xhr.responseText);
  });

  update_local_storage(userId, favorites)

  console.log('favorites saved to local storage', favorites)

  // Toggle button text and data attribute
  button.text(favorites.includes(userId) ? 'Remove from favorites' : 'Add to favorites');
  }
});

// on page load, update button text based on stored favorites
$('.favorite-button').each(function() {
  var button = $(this);
  var userId = button.data('userId');
  var isFavorite = button.data('isFavorite');

  // check if user is in favorites
  var favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
  var isUserFavorite = favorites.includes(userId);

  // set button text and data attribute based on result
  button.text(isUserFavorite ? 'Remove from favorites' : 'Add to favorites');
  button.data('isFavorite', isUserFavorite);
  button.data('favorites', favorites);
});

// function to store favorites in localStorage
function update_local_storage(user_id, favorites) {
  localStorage.setItem('favorites_' + user_id, JSON.stringify(favorites));
  // console.log('localstorage', favorites)
}

function update_user_favorites(user_id, favorites, nonce) {
  console.log('from the update user', favorites)

  $.post(ajaxurl, {
    'action': 'save_user_favorites',
    'favorites': favorites,
    'nonce': nonce,
    'user_id': user_id // Use the user_id parameter instead of userId
  })
  .done(function(response) {
    console.log('Favorites saved:', response);
  })
  .fail(function(xhr, status, error) {
    console.log('Failed to save favorites:', error);
    console.log('Server response:', xhr.responseText);
  });
}


// update user metadata when page is unloaded
$(window).on('beforeunload', function() {
  $('.favorite-button').each(function() {
    var user_id = $(this).data('userId');
    var nonce = $(this).data('nonce');
    var favorites = JSON.parse(localStorage.getItem('favorites_' + user_id) || '[]');
    // var favorites = [ 449, 487, 442, 474, 488, 457, 553, 559, 841]
    // console.log({favorites})
    update_user_favorites(user_id, favorites, nonce);
  });
});

I’ve tried logging each step, and everytime is seems like the data is passed correctly, and I can’t find out why it’s not working. Any suggestions?

lovata-shopaholic wintercms not saving the preview_image while create product

in lovata-shopaholic plugin when i go to create product and add preview image in the page it saved the image and show in the page.

  • when i save the product with submit it will redirect to the update page with latest ID.
  • but when i check the preview image on update page there is nothing.
  • if i update the image from update product page it works!

I have tried to check it with new added field but still its not working with new field too.

How can I check if json has a specific object? [closed]

I’m using a php code to download, change and upload a json file.

The json looks like this:

{"common": ["rtb.com"],"orgs": { "12345": { "domains": { "test.com": ["blabla.com"]} }}}
How can I ask the php to check if the ‘orgs’ object exists?

I tried using isset function which didn’t give me the result I expected.

‘if (array_key_exists(“orgs”,$data)){echo “orgs exist”;};
echo “orgs don’t exist”;