I am trying to write a save search function, where the user can save their searches, but I need some help in checking if the search is already in the database for the current user making the search.
I started off sending the search variable to database as a serialized array, but after reading quite a bit on not doing so, I now sadd to database using a json variable.

So far I have thus:

        $url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $escaped_url = htmlspecialchars( $url, ENT_QUOTES, 'UTF-8' );
        $query_str = parse_url($url, PHP_URL_QUERY);
        parse_str($query_str, $query_params);
        $query_params[contract_type] = $term_id;
        $query_params[url] =$url;
     // $search_data = maybe_serialize($query_params );  USING PHP VARIABLES AND SERIALIZE
        $json = json_encode($query_params);

The above grabs the URL and parameters and encodes into the array.
On clicking an ajax click event, this is inserted into user_meta.

{"ptype":"2675","minprice":"0","maxprice":"180000","plocation":"0","pbtsstation":"0","pbeds":"1","pbaths":"0","pgarages":"0","sort-properties":"price-asc","contract_type":34,"url":"http:\/\/mywebsite\/en\/for\/rent\/?ptype=2675&minprice=0&maxprice=180000&plocation=0&pbtsstation=0&pbeds=1&pbaths=0&pgarages=0&sort-properties=price-asc"}

What I need help with is, in the php ajax function I need to grab all existing user_searches and compare the new submitted one to see if it already exists.

This is my PHP ajax function:

/*-----------------------------------------------------------------------------------*/
/*  Add to saved Search
/*-----------------------------------------------------------------------------------*/
add_action('wp_ajax_save_this_search', 'save_this_search');

if( !function_exists( 'save_this_search' ) ){
  function save_this_search(){

    if( isset($_POST['user_id']) ){
        $user_id = intval($_POST['user_id']);
        $search_params = $_POST['params'];

            if( add_user_meta( $user_id, '_saved_searches', $search_params ) ){

/* success */
            }else{
                _e('Failed!', 'framework');
            }

    }else{
        _e('Invalid Parameters!', 'framework');
    }
    die;
 }
}

and this is my ajax function:

   /*-----------------------------------------------------------------------------------*/
    /* Save this search
    /*-----------------------------------------------------------------------------------*/
    $('#save-this-search').click(function(e){
        e.preventDefault();
    var $this = $(this);
        var loader = $this.siblings('.ajax-loader');
        var save_this_search_options = {
            beforeSubmit:  function(){
            loader.show();
            },  // pre-submit callback
            success:       function(){
                $('#save-this-search').attr('id','noLink');
                $this.addClass("active");
                loader.hide();
            }

        };
        $('#save-this-search-form').ajaxSubmit( save_this_search_options );
    });

I’m not sure where or how to put this check in, whether to put it in the php function, or in the ajax function beforeSubmit: function(){

In the users dashboard page (frontend) this is what I use to grab the already saved searches, this all works great.

   $sql = " SELECT * FROM  `wp_usermeta` WHERE  `meta_key` =  '_saved_searches' AND  `user_id` =  $user_id ORDER BY `umeta_id` DESC  ";
   $mySavedSearches = $wpdb->get_results( $sql );

      foreach($mySavedSearches as $key=>$value){
       $mySavedSearchesOutput[] = json_decode($value->meta_value, TRUE);
     }

   foreach ($mySavedSearchesOutput as $SavedSearches){  // using json array
    $mySavedSearch = is_array($SavedSearches) ? $SavedSearches : array();

I really hope I have explained this in a not to long winded way and someone can advise where and how to do the check.

1 Answer
1

For anyone else, or for someone to maybe give a better, neater, more professional answer, this is what I have ended up doing:

First I added a function to compare the new search data ($newSearch):

function identical_values( $arrayA , $arrayB ) { 
   sort( $arrayA ); 
   sort( $arrayB ); 
 return $arrayA == $arrayB; 
}

Kept the same method for grabbing the variables from URL:

        $url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $escaped_url = htmlspecialchars( $url, ENT_QUOTES, 'UTF-8' );
        $query_str = parse_url($url, PHP_URL_QUERY);
        parse_str($query_str, $query_params);
        $query_params[contract_type] = $term_id;
        $query_params[url] =$url;

Then added the code to run through all saved searches stored in the database:

         $newSearch = (array) $query_params; 
         $sql = " SELECT * FROM  `wp_usermeta` WHERE  `meta_key` =  '_saved_searches' AND  `user_id` =  $user_id ORDER BY `umeta_id` DESC  ";
          $mySavedSearches = $wpdb->get_results( $sql );

             foreach($mySavedSearches as $key=>$value){
               $mySavedSearchesOutput = json_decode($value->meta_value, TRUE);
               $identical = identical_values( $newSearch , $mySavedSearchesOutput );
               if($identical) break;
             }

This part, prevent the double clicking of link if already saved:

       if($identical):
         echo '         <li class="save-search active"></li>';
       else:
         echo '         <li id="save-this-search" class="save-search" data-user-id="'. $user_id.'"><span class="ajax-loader hide"><i class="fa fa-spinner fa-spin"></i></span></li>';
       endif;

Its not pretty, maybe not even safe, but for now works good 🙂

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *