Categories
Web Development WordPress

WordPress: How to send data and variables from js to PHP in an AJAX call

jQuery.ajax({
         type : "post",
         dataType : "json",
         url : myAjax.ajaxurl,
         data : {
            action: "my_user_vote",
            nonce: nonce
         },
         success: function(response) {
            if(response.type == "success") {
               jQuery("#vote_counter").html(response.vote_count)
            }
            else {
               alert("Your vote could not be added")
            }
         }
      })   

   })

I’m sure many of you recognize the javascript code block above, added to your code to call an AJAX function and run a PHP function from javascript. The above code will call the PHP function my_user_vote() when an action picked up by JQuery takes place if the function exists, the AJAX hooks were added correctly and the script was in fact localized with the ajaxurl.

If we want to pass data from the original JQuery function that calls the PHP function TO that PHP function, we can simply add more ‘data’ to the call and that data/those variables will be accessible in the PHP as $_POST variables in the function that is called with the names the data was given in the data part of the call.

data : {
            action: "my_user_vote",
            nonce: nonce,
            myVariable: "foobar"
         },

Now, in my PHP function I can get the value “foobar” simply by

public function my_user_vote() {
     $my_variable = wp_unslash( wp_kses_post( $_POST'myVariable'] ) );
...
}

Leave a Reply