admin管理员组

文章数量:1200424

I created my first ajax script which is an add-to-favorites option on my real estate site. On the single property page the setup works great...I check if the property is already saved, display a filled in heart if yes or a heart outline if not, then if the heart is clicked it toggles and adds a new entry into the user meta fields without reloading the page.

I then created a favorite's page which uses a foreach loop to display each saved property. I can check if the listing exists and display the correct heart icon but I'm unsure how to tell the jQuery code which foreach result to get variables from. If I click on the icon it'll toggle but nothing is added or removed from the database.

My code:

HTML:

<?php 
$user_id = get_current_user_id();
$parameters = array (
    'URL' => ,
    'Address1' => 123 Main St,
    'Address2' => Roselle, IL 60172,
);
$testpara = $parameters['URL'];
$string = serialize($parameters);

$meta = get_user_meta($user_id, 'pluginlink'); 
if(array_search($testpara, array_column($meta, 'URL')) !== false) {
    $icon = "fa fa-heart";
} else {
    $icon = "fa fa-heart-o";
    }
?> 
<form>
<div class = "buttons"><i onClick="myFunction(this)" class="<?php echo $icon; ?>" id="call" value="call"></i> </div>
 </form>

jQuery:

<script>       
jQuery(document).ready(function($) {
            var user_id = '<?php echo $user_id; ?>';
            var parameters = '<?php echo $string; ?>';
            var testpara = '<?php echo $testpara; ?>';
            $('#call').click(function(e) {
                    e.preventDefault(); // prevent form from reloading page
    
            $.ajax({
                url: '/wp-admin/admin-ajax.php',
                data: {
                    'action': 'save_listing',
                    'user_id': user_id,
                    'parameters': parameters,
                    'testpara': testpara,
                    },
                }); 
                });
            });
    function myFunction(x) {
      x.classList.toggle("fa-heart-o");
      x.classList.toggle("fa-heart");
    }
</script>

functions.php

function save_user_listing() {
if(!userid) {
    die();
} else {
    if(isset($_REQUEST)){
        $userid = $_REQUEST['user_id'];
        $testparameter = $_REQUEST['testpara'];
        $para = $_REQUEST['parameters'];        
        $unser = unserialize(stripslashes($para));
    
        $meta = get_user_meta($userid, 'pluginlink'); 
        if(array_search($testparameter, array_column($meta, 'URL')) !== false) {
            delete_user_meta($userid, 'pluginlink', $unser);
            } else {
            add_user_meta($userid, 'pluginlink', $unser);
            };
        }//end if isset
}//close if userID
        die();
    }//end function
add_action('wp_ajax_save_listing', 'save_user_listing');

本文标签: jqueryAjax Favorite from foreach (how to specify which result result is processed)