3

I spent a lot of time searching for a solution where I can pass the value of the JavaScript variable into PHP variable in the same file, same function (WordPress Widget, Form function). Is there a good way, as of 2017, to do so?

I have tried this method below. Although the Ajax part bring out the successful message, the php part failed.

repeat.php

<?php 
    echo $_POST['examplePHP']; //will cause undefined index here
?>
<script>
        jQuery(document).ready(function($){

          var exampleJS = "hi!";

          $.ajax({
                url: ajaxurl, //I have tried 'repeat.php' instead of ajaxurl, but not working.
                type: 'POST',
                data: {
                  examplePHP: exampleJS
                },
                success: function( response){
                  console.log("Successful!");
                },
                error: function(error){
                  console.log("error");
                }
          });

      });
</script>
1

2 Answers 2

2

I found an easy way to pass a JavaScript variable to PHP variable. Please note that this method works in WordPress version 4.7.2, and only specifically on Widget. I wrote a lot of comments to try to explain what each line did. If you have a better solution, please share with us!

Solution:

  • Create a hidden input field to store the value of the javascript you want to pass.
  • Access that hidden input field and assign its value to a PHP variable.

Demo Widget:

  • I create a demo widget that add "LOVE YOU" word according to how many time you press the "Add LOVE YOU" button.

  • Note that I left the hidden field shown for better understanding.

  • You can change type="text" totype="hidden" to hide it.

  • This demo only focuses on the form function of the widget.

  • Make sure the click Save button, else the value of the hidden input is not saved by the widget.

Demo Widget ScreenShot:

enter image description here

Source code:

wp-text-repeater.php

<?php
/**
*Plugin Name: WP Text Reapter
**/

class wp_text_repeater extends WP_Widget {

    /**
     * Sets up the widgets name etc
     */
    public function __construct() {
        $widget_ops = array(
            'classname' => 'wp_text_repeater',
            'description' => 'Widget that prints LOVE YOU repeatedly according to button press',
        );
        parent::__construct( 'wp_text_repeater', 'WP Text Repeater Widget', $widget_ops );
    }

    /**
     * Outputs the content of the widget
     *
     * @param array $args
     * @param array $instance
     */
    public function widget( $args, $instance ) {
        // outputs the content of the widget
    $wp_text_repeater_button = ! empty( $instance['wp_text_repeater_button'] ) ? $instance['wp_text_repeater_button'] : '';
    $wp_text_repeater_appendee = ! empty( $instance['wp_text_repeater_appendee'] ) ? $instance['wp_text_repeater_appendee'] : '';
    $wp_text_repeater_hidden = ! empty( $instance['wp_text_repeater_hidden'] ) ? $instance['wp_text_repeater_hidden'] : '';
    }

    /**
     * Outputs the options form on admin
     *
     * @param array $instance The widget options
     */
    public function form( $instance ) {
        // outputs the options form on admin
    $instance = wp_parse_args( (array) $instance, array( 'wp_text_repeater_button' => '', 'wp_text_repeater_appendee' => '', 'wp_text_repeater_hidden' => ''));

    $wp_text_repeater_button = $instance['wp_text_repeater_button'];
    $wp_text_repeater_appendee = $instance['wp_text_repeater_appendee'];
    $wp_text_repeater_hidden = $instance['wp_text_repeater_hidden'];

    $tempHidden = 'wp_text_repeater_hidden';

  ?>
    <!-- Hidden field that store number of time user press the button -->
    <input
          class="widefat"
          id="<?php echo $this->get_field_id($tempHidden); ?>"
          name="<?php echo $this->get_field_name($tempHidden); ?>"
          type="text"
          value="<?php echo esc_attr($$tempHidden);?>"/>
  <?php

    $max = 0; //Number of time user press the button

    //if JavaScript front-end hidden input has value, assign $max to it.
    //This If statement sync between the javascript and the php part.
    if(strlen($$tempHidden) > 0){
      $max = intval($$tempHidden);
    }

    $counter = 0;
    while($counter < $max){ //loop according to how many time user press the button
  ?>
      <p>LOVE YOU!</p>
  <?php
     $counter++;
    }

    $id_prefix = $this->get_field_id(''); //get the widget prefix id.
  ?>
    <!-- You can append all your content herev-->
    <span id="<?php echo $this->get_field_id('wp_text_repeater_appendee')?>"></span>

    <!-- Add button that call jQery function to add "LOVE YOU" word -->
    <input style="background-color: #08a538; color:white; height: 27px;"
          class="button widefat"
          type="button"
          id="<?php echo $this->get_field_id('wp_text_repeater_button'); ?>"
          value="Add LOVE YOU"
          onclick="text_repeater.addLove('<?php echo $this->id;?>', '<?php echo $id_prefix;?>'); return false;"
          />

    <script>

    jQuery(document).ready(function($){
      var preIndexID;
      var numberOfLove = <?php echo $max; ?>; //grab value from the php in order to sync between the front and back end.
      text_repeater = {
          addLove :function(widget_id, widget_id_string){
              preIndexID = widget_id_string; //get the correct pre-index of the widget.
              numberOfLove++;
              numberOfLove = numberOfLove.toString(); //convert int to string for the hidden input field.
              $("#" + preIndexID + "wp_text_repeater_hidden").val(numberOfLove); //change the value of the hidden input field.
              $("#" + preIndexID + "wp_text_repeater_appendee").append('<p>LOVE YOU!</p>'); //live update the front-end with "LOVE YOU".
          }
      }
    });

    </script>
  <?php
    }

    /**
     * Processing widget options on save
     *
     * @param array $new_instance The new options
     * @param array $old_instance The previous options
     */
    public function update( $new_instance, $old_instance ) {
        // processes widget options to be saved
    $instance = $old_instance;

    $instance['wp_text_repeater_button'] = sanitize_text_field($new_instance['wp_text_repeater_button']);
    $instance['wp_text_repeater_appendee'] = sanitize_text_field ($new_instance['wp_text_repeater_appendee']);
    $instance['wp_text_repeater_hidden'] = sanitize_text_field( $new_instance['wp_text_repeater_hidden'] );

    return $instance;

    }
}

// register wp_text_repeater widget
function register_wp_text_repeater_widget() {
    register_widget( 'wp_text_repeater' );
}
add_action( 'widgets_init', 'register_wp_text_repeater_widget' );
1

Please remember that the code fires from top to bottom.

This way you can not 'get' the POST variable before sending it over via ajax.

Something that would work with your setup:

<?php 
    if(isset($_POST['examplePHP'])){ //check if $_POST['examplePHP'] exists
        echo $_POST['examplePHP']; // echo the data
        die(); // stop execution of the script.
    }
?>

<script>
        jQuery(document).ready(function($){

          var exampleJS = "hi!";

          $.ajax({
                url: window.location, //window.location points to the current url. change is needed.
                type: 'POST',
                data: {
                  examplePHP: exampleJS
                },
                success: function( response){
                  console.log("Successful! My post data is: "+response);
                },
                error: function(error){
                  console.log("error");
                }
          });

      });
</script>

First we check if the POST variable exists with isset(). If this exists we echo the content of 'examplePHP' and then stop the execution of the script with die();.

If there is not POST variable available, this means somebody just loads the page. Then we don't echo but just continue with the rest of the page.

I've added window.location which is the current URL. And the response variable gives the echo.

Since this is the WordPress Stack Exchange I would recommend you to use WordPress Ajax. You can read more about on the Codex Page!

0

Your Answer

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

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