• Hy, I am trying to run an ajax call and getting data from server.

    I have 3 options on frontend

    1: price high to low

    2: price low to high

    3: under 20000

    I have set an attribute of ‘data-value’ to each of the value so i can identify the data in backend.

    When the button is clicked it will pick their data-value attribute value and will check which button is clicked and will set variable values according to that

    I have this code in my custom.js

    let x = $('.listing-offer-optionn-link')
        $(x).click(function() {
            alert('loading');
            let valu = '';
            let priceVal = null;
            let priceKey = null ;
            let x = $(this).attr('data-value')
            switch (x) {
                case 'low-to-high':
                    valu = 'ASC';
                    break;
                case 'high-to-low':
                    valu = 'DESC';
                    break;
                default:
                    valu = 'ASC';
                    priceVal = '20000';
                    priceKey = 'price';
            }
            $.ajax({
                type : 'POST',
                datatype : 'html',
                url : 'https://localhost/valueautos/wp-admin/admin-ajax.php',
                data : {
                    'filter' : valu,
                    'priceFilter': priceVal,
                    'priceKey' : priceKey,
                    'action' : 'Get_Filters'
                },
                success : function(result) {
                    console.log(result)
                    $('.related-listing-listings-wrapper').html(result)
                },
                error : function(error) {
                    alert('error in getting record')
                }
            })
        })
    

    and I have this code in my functions.php

    add_action( 'wp_ajax_Get_Filters', 'Get_Filters_callback' );
    add_action( 'wp_ajax_nopriv_Get_Filters', 'Get_Filters_callback' );
    function Get_Filters_callback() {
        $to = $_POST['filter'];
       // The Query
       $args = array(
        'post_type' => 'listings',
        'posts_per_page' => 50,
        'meta_key' => 'price',
        'order' => $_POST['filter'] ,
        'orderby' => 'meta_value_num',
        'meta_query' => array(
            array(
                'key' => $_POST['priceKey'],
                'value' => $_POST['priceFilter'] ,
                'compare' => '<=',
            ),
        )
        );
    $the_query = new WP_Query( $args );
     
    // The Loop
    if ( $the_query->have_posts() ) {
            echo '<ul>';
        while ( $the_query->have_posts() ) {
    // post content
    }
    }

    now the problem is I am getting correct posts when i click on button (under 20000) but i get nothing when i click on ‘price low to high’ or ‘price high to low’

    Any suggestions what I am doing wrong?

    • This topic was modified 1 year, 11 months ago by jasghar.
Viewing 4 replies - 1 through 4 (of 4 total)
  • Hi @jasghar

    A few things could be causing the issue with your code. First, I recommend adding some debugging statements to help narrow down the problem. You can try adding some console.log statements to print out the values of $_POST['filter'], $_POST['priceFilter'], and $_POST['priceKey'] in the Get_Filters_callback function. This will help you determine whether the correct values are being passed to the function.

    Next, I noticed that in the switch statement in your JavaScript code, you are assigning valu the value ‘ASC’ or ‘DESC’, but in your $args array in the Get_Filters_callback function, you are using $_POST['filter'] as the value for the ‘order’ key. This means that the ‘order’ value will always be ‘ASC’ or ‘DESC’, regardless of the value of x. You may want to update the $args array to use valu as the value for the ‘order’ key instead of $_POST['filter'].

    Another potential issue could be the meta_query argument in your $args array. If the ‘priceKey’ and ‘priceFilter’ values are null, then the meta_query argument will not be included in the $args array, which could be causing the query to return no results. To fix this, you can add a check to see if priceKey and priceVal are null and only include the meta_query argument if they are not.

    I hope this helps! Let me know if you have any questions or need further assistance.

    Thread Starter jasghar

    (@jasghar)

    Thankyou so much for your response.

    The issue was with the ‘ASC’ and ‘DESC’ values and the null values for meta query arguments. I created a variable to check if the price field is coming or not if yes then take this $args as wp_query argument

    if not then take a seperate $args as wp_query argument.

    But I have another issue.

    I have a view more button below posts.

    I am showing 5 posts at a time with these three filters (under $20,000, price low to high, price high to low) and I have a view more button below it.

    What I want is when I click on view more button it will show me the next 5 posts. This is quite easy but the thing is

    if the user already clicked on ‘price high to low’ and click on view more button it should show the next 5 posts in ‘price high to low’ order means in DESC order.

    if the user already clicked on price under $20,000 and then click on view more button then it should show me the next 5 posts with price under $20,000

    if the user already clicked on price high to low and the click on view more then it should show me the next 5 posts with price high to low order

    Any ideas how I can achieve this?

    should I make separate arguments with if else statement for each of these filters along with view more button?

    I am kind of stuck at this one. kindly give me any suggestions.

    Regards

    Junaid

    Hi @jasghar

    To ensure the desired behavior of the ‘View More’ button, it is necessary to keep track of the current filter and order settings between requests. To do this, you can include the current filter and order values in the data sent to the server when clicking the ‘View More’ button. This can be done by adding a new property to the data object in the AJAX call that stores the current filter and order values.

    On the server side, these values can be used to determine which query arguments to use in the WP_Query object. This can be done either by using a series of if statements to check the values of the filter and order variables or by using an array of predefined query arguments and selecting the appropriate one based on the values of the filter and order variables. This approach can be implemented as follows:

    // JavaScript code to handle the "view more" button click
    $('#view-more-button').click(function() {
      // Get the current filter and order values
      let filter = $('#current-filter').val();
      let order = $('#current-order').val();
    
      // Make the AJAX request
      $.ajax({
        type: 'POST',
        datatype: 'html',
        url: 'https://localhost/valueautos/wp-admin/admin-ajax.php',
        data: {
          'filter': filter,
          'order': order,
          'action': 'Get_Filters',
        },
        success: function(result) {
          console.log(result);
          $('.related-listing-listings-wrapper').html(result);
        },
        error: function(error) {
          alert('error in getting record');
        },
      });
    });
    
    // PHP code to handle the AJAX request
    add_action('wp_ajax_Get_Filters', 'Get_Filters_callback');
    add_action('wp_ajax_nopriv_Get_Filters', 'Get_Filters_callback');
    function Get_Filters_callback() {
      // Get the filter and order values from the request
      $filter = $_POST['filter'];
      $order = $_POST['order'];
    
      // Define the query arguments based on the filter and order values
      switch ($filter) {
        case 'under-20000':
          $args = array(
            'post_type' => 'listings',
            'posts_per_page' => 5,
            'meta_query' => array(
              array(
                'key' => 'price',
                'value' => '20000',
                'compare' => '<=',
              ),
            ),
          );
          break;
        case 'price':
          $args = array(
            'post_type' => 'listings',
            'posts_per_page' => 5,
            'meta_key' => 'price',
            'orderby' => 'meta_value_num',
          );
          if ($order === 'high-to-low') {
            $args['order'] = 'DESC';
          } else {
            $args['order'] = 'ASC';
          }
    break;
        default:
          $args = array(
            'post_type' => 'listings',
            'posts_per_page' => 5,
          );
      }
    
      // Run the query
      $the_query = new WP_Query($args);
    
      // The Loop
      if ($the_query->have_posts()) {
        echo '<ul>';
        while ($the_query->have_posts()) {
          // post content
        }
      }
    }

    This code defines the $args array based on the values of the $filter and $order variables and then creates a new WP_Query object using these arguments. The loop then iterates through the posts returned by the query and displays them.

    I hope this helps! Let me know if you have any other questions or need further assistance.

    Moderator bcworkz

    (@bcworkz)

    It seems Faisal overlooked one thing in an otherwise excellent answer. Besides keeping track of the user’s ordering preference, you need to also keep track of which page the user is on ?? Even in a single page, infinite scroll situation, there needs to be some kind of internal “page” reference to indicate which group of data to retrieve next. You’d keep track of which page the user is on in a manner similar to the other factors, sending it along with the other data in the request. Your PHP code then sets the “paged” arg of WP_Query accordingly.

    There is typically a line of PHP that checks for the presence of a paged value in the request. If there is none, assume page 1 is what is needed.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘How to run wp query with multiple values’ is closed to new replies.