Wednesday, August 17, 2022
HomeWordPress Developmentphp - Learn how to set variables with AJAX request to make...

php – Learn how to set variables with AJAX request to make use of in one other perform in WordPress


$.ajax( {
                technique : 'POST',
                dataType : 'json',
                url : my_var.ajaxurl,
                information : {
                    foo : foobar,
                    _wpnonce : my_var.nonce,
                    motion : 'my_php_ajax_function'
                }
            } )
            .achieved(
                perform( information ){
                    console.log(information);              
                }
            );

wordpress php half:

    add_action( 'wp_ajax_nopriv_my_php_ajax_function', 'my_php_ajax_function' );
    add_action( 'wp_ajax_my_php_ajax_function', 'my_php_ajax_function' );
    add_action('wp_enqueue_scripts', 'my_enqueue2');
    perform my_enqueue2($hook) {
        wp_enqueue_script( 'ajax-script',
            plugins_url( '/js/my-jquery.js', __FILE__ ),
            array('jquery'),
            false,
            true
        );
        $rest_nonce = wp_create_nonce( 'wp_rest' );
        wp_localize_script( 'ajax-script', 'my_var', array(
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
            'nonce' => $rest_nonce,
        ));
    }
    
    perform my_php_ajax_function(){
        if ( wp_verify_nonce( $_POST['_wpnonce'], 'wp_rest' ) ){
                echo json_encode(
                    array(
                        'youSent' => $_POST['foo']
                    )
                );
                $this->yousent = $_POST['foo'];
                exit;
    
        } else {
            echo 'nonce verify failed';
            exit;
        }
    }

not working:

   $yousent = ""; //information from ajax request
   perform my_another_function(){
      echo $this->yousent;
    }

learn how to set $_POST['foo'] variable into php class variable to make use of in one other perform;
$this->foo = $_POST['foo']; establishing variable to be used in one other perform appears to be not working

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments