skip to Main Content

I have a WordPress website page where I want to enter two values- gender and manufacturer, then display a list which shows which items match the gender and manufacturer selected.

So that the whole page is not refreshed I want to do this with an AJAX request which has to follow a particular route in WordPress which has got me completely lost. At the moment I am having trouble even passing my two variables from the HTML page through to the JS and PHP.

For some reason the code always thinks that the user has selected Men even where Women or Junior is chosen.

My HTML

    <form>
     <br>
     
      <select id="gen" name="gen">
        <option value="Men">Men</option>
        <option value="Women">Women</option>
        <option value="Junior">Junior</option>
      </select>
</form>



<div><a class="chartsearch">Search</a></div>

   
<div id="results">
    
    Results go here if it works
    <br>
    <br>
    
</div>

Then my JS and PHP which is currently all contained in the functions.php file in my public_html/wp-content/themes/inspiro folder.

//Load jQuery
wp_enqueue_script('jquery');

//Define AJAX URL
function myplugin_ajaxurl() {

   echo '<script type="text/javascript">
           var ajaxurl = "' . admin_url('admin-ajax.php') . '";
         </script>';
}
add_action('wp_head', 'myplugin_ajaxurl');



//The Javascript
function add_this_script_footer(){ ?>



<script>
jQuery(document).ready(function($) {
    // This is the variable we are passing via AJAX
    let str = document.getElementById('gen').value;

  
    // This does the ajax request (The Call).

    $( ".chartsearch" ).click(function() {
      $.ajax({
          url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
          data: {
              'action':'example_ajax_request', // This is our PHP function below
              'str' : str // This is the variable we are sending via AJAX
          },
          success:function(data) {
      // This outputs the result of the ajax request (The Callback)
              $("#results").text(data);
          },
          error: function(errorThrown){
              window.alert(errorThrown);
          }
      });
    });
});
</script>


<?php }
add_action('wp_footer', 'add_this_script_footer');

//The PHP
function example_ajax_request() {
    // The $_REQUEST contains all the data sent via AJAX from the Javascript call
    if ( isset($_REQUEST) ) {
        $str = $_REQUEST['str'];
        // This bit is going to process the gender variable and display results 
        if ( $str = 'Men' ) {
            $results = 'Mens results';
        } else {
            
            $results = 'Other results';
        
        }
        // Now let's return the result to the Javascript function (The Callback)
        echo $str;
        echo $results;
        
    }
    // Always die in functions echoing AJAX content
   die();
}
// This bit is a special action hook that works with the WordPress AJAX functionality.
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' ); 

If you select Men and click Search it displays Men Mens Results but the same happens if you select Women. This tells me that it is getting the initial value for $str as Men but not ever changing it. So there is no point going any further with my code until it does. Once it does I can get the AJAX request to search my SQL database and show real Mens Results, Women Results, Junior Results rather than just the text.

Can anyone see what I have done wrong? I know I am a clown and a complete novice but any help would be appreciated.

2

Answers


  1. It’s because you st your variable at the documentReady event callback. So the var has the default value (the value at the documentReady moment).

    move it in the submit event:

    // This does the ajax request (The Call).
    
    $( ".chartsearch" ).click(function() {
      let str = document.getElementById('gen').value;
      $.ajax({
          url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
          data: {
              'action':'example_ajax_request', // This is our PHP function below
              'str' : str // This is the variable we are sending via AJAX
          },
          success:function(data) {
      // This outputs the result of the ajax request (The Callback)
              $("#results").text(data);
          },
          error: function(errorThrown){
              window.alert(errorThrown);
          }
      });
    });
    
    Login or Signup to reply.
  2. $str = ‘Men’ is always true, because assigning the value Men to $str won’t fail.
    To compare them, you should write: $str == ‘Men’

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search