• Resolved brightkhan

    (@brightkhan)


    ajax part:

    $.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 part:

    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']
    				)
    			);
    			exit;
    
    	} else {
    		echo 'nonce check failed';
    		exit;
    	}
    }

    How can i set up ajax sending data as variable to the another function.. such as
    $this->yousend = $_POST[‘foo’] // ajax sending data

    $this->yousend not working or setting up as null value..

    • This topic was modified 2 years, 3 months ago by brightkhan.
    • This topic was modified 2 years, 3 months ago by brightkhan.
    • This topic was modified 2 years, 3 months ago by Jan Dembowski.
Viewing 15 replies - 1 through 15 (of 15 total)
  • Moderator bcworkz

    (@bcworkz)

    It’s not clear how you’re using a class object to handle Ajax requests. If your console log is showing null as the response, there’s an issue with your Ajax callback. The action callback should be added from the class constructor. The callback method needs to be passed in array form, for example:
    add_action( 'wp_ajax_my_php_ajax_function', array( $this, 'my_class_method' ) );

    Whatever the callback echoes out will be received client side as data, assuming the class object had been instantiated when WP was initialized as part of theme or plugin code.

    Note that ‘wp_ajax_my_php_ajax_function’ is only good for logged in users. For effective front end use by unregistered users, you also need to hook ‘wp_ajax_nopriv_my_php_ajax_function’.

    Thread Starter brightkhan

    (@brightkhan)

    yes i did everythink right:

    here is my code what i tried to do.
    ajax code

    $.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);              
                    }
                ); 
    <?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;
            }

    it is just not letting yousent value out of this wordpress registered ajax function my_php_ajax_function

    Moderator bcworkz

    (@bcworkz)

    You’re not passing your callback methods to add_action() correctly for class methods, what you have is correct for procedural, not class methods. For class methods you must pass your callback as an [object, method] array, as shown in my example in my earlier reply.

    The do_action() process not only needs your method name, it needs your class object as well in order to execute the callback.

    Thread Starter brightkhan

    (@brightkhan)

    sorry my bad, i forget to mention , i changed this to

    add_action( 'wp_ajax_my_php_ajax_function', 'my_php_ajax_function' );
    add_action( 'wp_ajax_my_php_ajax_function', array($this,'my_php_ajax_function') );

    but still not working, it is not letting me post variable outside of my_php_ajax_function it is giving me null value, my ajax is running fine,

    actually i needs to use that variable in html template which is calling from that class..

    so whenever post variable found my_php_ajax_function store it in that class isset($_POST['foo']) {$this->yousent = $_POST['foo']} then i m using it in template which is in that another function, based on that foo variable // do your stuff , but $this-yousent is not giving me ajax conducted value, it is just not letting me take post variable outside of that my_php_ajax_function function

    • This reply was modified 2 years, 3 months ago by brightkhan.
    • This reply was modified 2 years, 3 months ago by brightkhan.
    • This reply was modified 2 years, 3 months ago by brightkhan.
    • This reply was modified 2 years, 3 months ago by brightkhan.
    Dion

    (@diondesigns)

    It sounds like what you want is to have $_POST['foo'] available after the AJAX request has completed. That’s not possible. You should instead call my_another_function($_POST['foo']) from within my_php_ajax_function(), then echo whatever HTML should be added to the page, and finally have the JS modify the HTML on the page accordingly.

    Note that you should sanitize $_POST['foo'] to eliminate possible XSS issues.

    Thread Starter brightkhan

    (@brightkhan)

    i just want to set
    $this->yousent variable when my_php_ajax_function is called then i want to start my_another_function work based on that variable, $yousent variable in the same class my_php_ajax_function is in

    my_php_ajax_function(){
    isset($_POST['foo'])? $this->yousent = $_POST['foo'] : 'some or value';
    }

    before ajax giving seccess message in console.log, isn’t it possible in wordpress , normally it works in raw php. but in wordpress it gives me $this->yousent null value,

    • This reply was modified 2 years, 3 months ago by brightkhan.
    • This reply was modified 2 years, 3 months ago by brightkhan.
    Dion

    (@diondesigns)

    If your other function isn’t being called by your AJAX handler function, then it will NEVER execute. That’s why you must call the function in your AJAX handler, then return the HTML (or other information) to the javascript function that made the AJAX request. It will be the JS function’s responsibility to modify the page with the data returned from the AJAX request.

    Thread Starter brightkhan

    (@brightkhan)

    ‘That’s why you must call the function in your AJAX handler’

    plz can you show me in code how can i do this?

    • This reply was modified 2 years, 3 months ago by brightkhan.
    Dion

    (@diondesigns)

    This is your current code (modernized for brevity):

    echo json_encode([ 'youSent' => $_POST['foo'] ]);
    $this->yousent = $_POST['foo'];
    exit;

    Change it to this:

    my_another_function($_POST['foo']);
    exit;

    Your my_another_function() function would be responsible for sanitizing $_POST['foo'] and echoing data back to the JS function that made the AJAX request.

    Good luck!

    Moderator bcworkz

    (@bcworkz)

    That’s simple:

    function my_php_ajax_function(){
            if ( wp_verify_nonce( $_POST['_wpnonce'], 'wp_rest' ) ){
                echo json_encode(
                    array(
                        'youSent' => $_POST['foo']
                    )
                );
                $this->yousent = $_POST['foo'];
            // you must validate and sanitize "foo" here or soon after
                my_another_function ()
                exit;
            } else {
                echo 'nonce check failed';
                exit;
            }
        }

    You must realize that once exit; is processed, PHP is done. Unless you somehow save a value somewhere persistent (like the DB), all PHP values are gone on exit. If you write to the DB, you might also need to confirm that the current user has appropriate permission or capability to do so, on top of validating and sanitizing the value.

    In the mean time, back at the client side jQuery, the .done process should somehow alter page content. If nothing else, something indicating to the user that the submitted value was received server side. If you save the value to the DB, your PHP should confirm it was correctly saved before echoing out any sort confirmation back to the client.

    Thread Starter brightkhan

    (@brightkhan)

    what i’m seeing my_another_function() is extending the work of my_php_ajax_function() and giving back modified data as success response, but it is not giving that ajax send $_Post variable into class variable $this->yousent = $_POST['foo']; this is not working, $this->yousent variable in class not setting up by that ajax call or null
    i understand it may be the reason of this

    You must realize that once exit; is processed, PHP is done. Unless you somehow save a value somewhere persistent (like the DB), all PHP values are gone on exit.

    • This reply was modified 2 years, 3 months ago by brightkhan.
    Moderator bcworkz

    (@bcworkz)

    I goofed in my last example, sorry for any confusion. I neglected to include the $this-> reference in calling my_another_function() from within a different class method.

    I had copied your PHP into one of my plugins to try to replicate your experience to see why you’re still having difficulty. I did change $_POST['foo'] to a static string just to avoid needing to implement the client side code as well. I also commented out the nonce check for the same reason.

    My version of PHP doesn’t like the first line $yousent = '';, it wants a visibility modifier like public there. The lack of any modifier is supposed to make it public automatically. It’s good practice to explicitly declare visibility in all cases anyway. I recommend doing so to eliminate any chance of problems cropping up external to what we’re focused on.

    Because my_another_function() is called before exit;, $this->yousent value should be available in that function. As a demonstration, I placed echo $this->yousent; within that function. After instantiating the class, calling the object’s my_php_ajax_function() method does indeed result in the correct value being output, proving that the property’s value is available in my_another_function().

    Thread Starter brightkhan

    (@brightkhan)

    when i instantiate my class, my class calls a template function in its construct method, template function instantiates my ajax call on user interaction, then i check that ajax variable such as $_POST[‘foo’] my_php_ajax_function() and go for further evaluation on my_another_function and store that variable in class variable public $yousent = ”; but setting up class variable either of my_php_ajax_function(), my_another_function function , something like $this->yousent = $_POST['foo']; is not working for the class it is having null value, but variable is available both of that two function, within that two function you can do whatever you want to do with that variable, but when you call from your template `my_another_function(){
    echo yousent variable
    }` it is giving null value, or you check is that class $yousent variable have any value or set up by that ajax call, then based on that value go for the further templating system .. but you are having null within $ yousent variable

    Moderator bcworkz

    (@bcworkz)

    …when you call from your template my_another_function(){ echo yousent variable }

    A call from a template would be due to a separate request. Anything established as class properties from the Ajax request is now gone. Template code would need to get the saved value from the DB.

    If this template is for the same page which initiated the Ajax request, instead of reloading to execute template code, have your jQuery update the current HTML.

    Thread Starter brightkhan

    (@brightkhan)

    if this template is for the same page which initiated the Ajax request, instead of reloading to execute template code, have your jQuery update the current HTML.

    thanks i did exactly what you said

Viewing 15 replies - 1 through 15 (of 15 total)
  • The topic ‘setting up ajax data as php class variable in wordpress’ is closed to new replies.