0

I have a html form with select boxes and I want to display different data depending on what the users select.

All I really need to do is change 1 variable in php based on the selection.

I make an external API call that returns data and displays it in an html table. I want to to change 1 small part of the api call (an id in the get uri) depending on the users choice.

Is there a simple way to do this?

I've got as far as making the jquery and enqueuing it with wordpress, and I'm getting a 200 response when changing the select box value. But I just can't seem to be able to change the PHP.

To avoid bombarding with code, I've changed the callback function to give an examlple of what I'd like to happen. Greatly appreciate any feedback. Thanks.

HTML

    <form class="choose-site" action="" method="post">
      <select id="choose-site" name="site-choice">
        <option value="site1"><?php echo $primary_site ?></option>
        <option value="site2"><?php echo $site_2 ?></option>
      </select>
    </form>

<div id="test123">
    <p><?php echo $msg; ?></p>
    </div>

JQUERY

(function($) {
    $(document).ready(function() {
        
        $("#choose-site").on("change",function() {
            const val = this.value;
             if (val) {
                 $.ajax({
                    type : "post",
                    dataType : "JSON",
                    url: my_ajax_object.ajax_url,
                    data : { 
                        action: "my_ajax_action"
                },
                success: function(data) {
        $("#test123").html(data);
      }
            });
        }});
    });
})(jQuery);

PHP in Functions.php

<?php

add_action( 'wp_ajax_my_ajax_action', 'users_details_callback' );
add_action( 'wp_ajax_nopriv_my_ajax_action', 'users_details_callback' );

function users_details_callback() {

 if (isset($_POST['site-choice']) && $_POST['site-choice'] == 'site1') {

$msg = "hi";
    
}

if (isset($_POST['site-choice']) && $_POST['site-choice'] == 'site2') {
$msg = "bye";
}

wp_die();
return $msg;

}
?>

Is there a way to change the value of $msg and send it back to the HTML?

3
  • Your AJAX PHP callback should return the response before calling wp_die(), but by "return", I mean echo the response, so echo $msg; wp_die();. Then your JS success callback would receive the $msg value in the data variable. However, if you set the dataType to json, then you should echo a valid JSON string.
    – Sally CJ
    Commented Aug 22, 2020 at 9:59
  • But actually, I suggest you to create a custom REST API endpoint which by default always returns a JSON response, and then make your AJAX request to that endpoint. "the REST API provides a more predictable and structured way to interact with your site’s content than admin-ajax" - by the REST API handbook.
    – Sally CJ
    Commented Aug 22, 2020 at 10:32
  • Thanks, Sally. Very helpful stuff in here. I think I'll definitely explore the REST API suggestion. Taking your recommendations regarding the current code, still not having any luck :(
    – dylzee
    Commented Aug 22, 2020 at 10:45

1 Answer 1

0

Is there a way to change the value of $msg and send it back to the HTML?

Your code is basically already doing that, but there are a few issues:

  1. Your AJAX JS (jQuery.ajax()) is not sending the POST data named site-choice to your AJAX PHP callback (users_details_callback()) which reads the data via $_POST['site-choice'].

  2. Your AJAX PHP callback would result in WordPress echoing a zero (0) because you're calling wp_die() before returning any output and even if you returned it before wp_die() is called, you should actually echo the output and not return it.

  3. Your AJAX JS is expecting a JSON data back from the server (because you set dataType to JSONdataType : "JSON"), so your AJAX PHP callback should return a valid JSON response.

So to fix the issues:

  • In your PHP function (users_details_callback()), you can use wp_send_json_success() to send a JSON response without having to call wp_die(): (note that I also optimized the if condition)

    function users_details_callback() {
        if ( isset( $_POST['site-choice'] ) ) {
            $msg = '';
    
            if ( $_POST['site-choice'] == 'site1' ) {
                $msg = 'hi';
            } elseif ( $_POST['site-choice'] == 'site2' ) {
                $msg = 'bye';
            }
    
            wp_send_json_success( $msg );
        }
    
        // Send an error if we receive an invalid data.
        wp_send_json_error( 'your error' );
    }
    
  • In your jQuery.ajax() (or $.ajax()) call:

    $.ajax( {
        ...
        data: {
            action: 'my_ajax_action',
            // Send the site-choice data.
            'site-choice': $( '#choose-site' ).val(),
        },
        success: function( data ) {
            // 'data' is now an object and the $msg value from the server is put in
            // data.data, so use that instead of just 'data'.
            $( '#test123' ).html( data.data );
        },
    } );
    
2
  • 1
    Thank you so much. Not only have you got it working, but the way you've explained it is very clear and I've learned something valuable. I appreciate your time and I also hope this benefits someone else who might be struggling with this :)
    – dylzee
    Commented Aug 22, 2020 at 12:57
  • I'm glad my answer helped you. Happy coding! :)
    – Sally CJ
    Commented Aug 22, 2020 at 14:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.