admin管理员组

文章数量:1194126

$.ajax( {
                method : 'POST',
                dataType : 'json',
                url : my_var.ajaxurl,
                data : {
                    foo : foobar,
                    _wpnonce : my_var.nonce,
                    action : 'my_php_ajax_function'
                }
            } )
            .done(
                function( data ){
                    console.log(data);              
                }
            );

wordpress php part:

<?php class my_class {
    $yousent = '';
    public function __construct() {
        $this->init_setup();
    }
    function init_setup{     
        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');
    }
    function 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,
        ));
    }

    function 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 check failed';
            exit;
        }
    }

    function my_another_function (){
//do stuff $this->yousent;
    }
}
?>

not working:

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

how to set $_POST['foo'] variable into php class variable to use in another function; $this->foo = $_POST['foo']; setting up variable for use in another function seems to be not working

$.ajax( {
                method : 'POST',
                dataType : 'json',
                url : my_var.ajaxurl,
                data : {
                    foo : foobar,
                    _wpnonce : my_var.nonce,
                    action : 'my_php_ajax_function'
                }
            } )
            .done(
                function( data ){
                    console.log(data);              
                }
            );

wordpress php part:

<?php class my_class {
    $yousent = '';
    public function __construct() {
        $this->init_setup();
    }
    function init_setup{     
        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');
    }
    function 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,
        ));
    }

    function 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 check failed';
            exit;
        }
    }

    function my_another_function (){
//do stuff $this->yousent;
    }
}
?>

not working:

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

how to set $_POST['foo'] variable into php class variable to use in another function; $this->foo = $_POST['foo']; setting up variable for use in another function seems to be not working

Share Improve this question edited Aug 17, 2022 at 13:08 Muhammad Hossain asked Aug 16, 2022 at 23:33 Muhammad HossainMuhammad Hossain 32 bronze badges 14
  • can you reword what you've written? It doesn't make a lot of sense, and there are no classes in your question so it's unclear what you mean by class variable. Remember that every new request to the server loads WordPress from a blank slate, so you can't set a variable in one request, then use it in another – Tom J Nowell Commented Aug 16, 2022 at 23:53
  • i want to set ajax send data add_action( 'wp_ajax_my_php_ajax_function', 'my_php_ajax_function' ); from this function, into a variable which is in the class scope, then i want to use it into another function my_another_function(){ echo $this->yousent; } which is in the same class scope is it possible? its give me null value, – Muhammad Hossain Commented Aug 17, 2022 at 0:17
  • @MuhammadHossain, so my_php_ajax_function() and my_another_function() are both class methods, i.e. functions in the same class? If so, you should call the latter method inside of the main AJAX callback, i.e. do $this->yousent = $_POST['foo']; $this->my_another_function(); before exiting. Or just pass the POST value to that another function, or just access $_POST['foo'] from that function.. But all these are actually general PHP/programming which requires no WordPress-specific knowledge. – Sally CJ Commented Aug 17, 2022 at 1:59
  • $_POST['foo'] is only working on add_action( 'wp_ajax_my_php_ajax_function', 'my_php_ajax_function' ); registered function my_php_ajax_function, $_POST value only setting up within that function, if i assign that like $this->foo = $_POST['foo'] value it is setting up null value , neither i can access $_POST value to any other function only in that registered function, i need to use that value outside of that wordpress registered function.. – Muhammad Hossain Commented Aug 17, 2022 at 2:21
  • if i echo $_POST['foo'] variable within that registered function my_php_ajax_function ajax is giving me success response that means everything is working, it is just not letting me take that $_post['foo'] variable outside of this function, i need to store it in that class variable so that i can access it whenever i needed – Muhammad Hossain Commented Aug 17, 2022 at 2:32
 |  Show 9 more comments

1 Answer 1

Reset to default 0

There are two issues

Broken Callbacks

You've used:

add_action('wp_ajax_nopriv_my_php_ajax_function','my_php_ajax_function' );

This is equivalent to:

When `wp_ajax_nopriv_my_php_ajax_function` happens
    do: `my_php_ajax_function()`

Which is not what you wanted, because that is not a function, and there is no my_php_ajax_function function.

You also don't just want it on that class, you want it on that specific instance of that class, afterall how will it know what $this is?

add_action expects parameter 2 to be a callable, so lets look up the callable that matches a class function:

https://www.php.net/manual/en/language.types.callable.php

// Type 3: Object method call
$obj = new MyClass();
call_user_func(array($obj, 'myCallbackMethod'));

So instead of "function name" you need to pass [ $this, "class function name" ]

Sharing Data Across Requests

Unlike webapps built with Java and other languages, PHP apps are loaded from scratch each time a request is handled and have a limited lifespan. There is no shared persistent program running in the background.

Everytime your browser talks to your server, be it to load a page, or via javascript, WordPress is loaded from a blank slate. When WordPress has responded, it is destroyed and nothing is preserved.

This means all variables are wiped at the end of every request.

If you want to persist/save those values, you have several options:

  • store it in a cookie
  • store it in user meta if the user is logged in
  • store it in the browser and send it with every request
  • store it on a post or page ( best for data specific to a post that affects all users )
  • store it in an option or transient ( best for global site level data that affects all users )

本文标签: phpHow to set variables with AJAX request to use in another function in WordPress