javascript - How to pass aa JS variable to PHP?

admin2025-01-07  5

I am fetching data from an API using JS. How can I use this data with PHP. More specifically, assign this data to a $_SESSION variable in PHP so that I can use it in other pages(templates files)?

I am fetching data from an API using JS. How can I use this data with PHP. More specifically, assign this data to a $_SESSION variable in PHP so that I can use it in other pages(templates files)?

Share Improve this question asked Sep 21, 2020 at 16:53 stemonstemon 1551 silver badge8 bronze badges 3
  • Can you be more specific/provide more details? There isn't enough information to understand what you want to do and devise an answer. Also keep in mind that PHP sessions don't scale, have security issues, and don't work on a lot of WP hosts – Tom J Nowell Commented Sep 21, 2020 at 17:16
  • @TomJNowell this other question is a bigger picture to what I am trying to achieve. Let me know if it makes it more clear. wordpress.stackexchange.com/questions/375090/… – stemon Commented Sep 21, 2020 at 17:50
  • I'll be honest, that's really confusing and hard to follow, too many steps. I understand you've made your questions generic to try and hide details about the specific site and in hopes of making them easier to implement, but it's just made the question very confusing and too abstract to make concrete reasoning possible. Nobody is quite sure what it is you're wanting to do – Tom J Nowell Commented Sep 21, 2020 at 18:01
Add a comment  | 

2 Answers 2

Reset to default 0

Step 1: Run wp_localize_script, add below function in function.php


 add_action( 'wp_enqueue_scripts', 'jsto_php_enqueue_scripts', 5 );
 public function jsto_php_enqueue_scripts() {
          wp_register_script( 'file_handle', plugin_dir_url( __FILE__ ) . 'js/js-file-name.js', array( 'jquery' ), '0.0.1', false );  
          wp_enqueue_script('file_handle');
          // Set Nonce Values so that the ajax calls are secure
          $add_something_nonce = wp_create_nonce( "add_something" );
          $ajax_url = admin_url( 'admin-ajax.php' );
          $user_id = 20; //PHP variable
          // pass ajax object to this javascript file
          // Add nonce values to this object so that we can access them in the plugin-name-admin.js javascript file
          wp_localize_script( 'file_handle', 'ajax_object', 
            array( 
                'ajax_url' => $ajax_url,
                'add_something_nonce'=> $add_something_nonce,
                'user_id' => $user_id
            ) 
          );


 }


Step 2: Access Localized Variables in your JavaScript File (in our example js-file-name.js)



(function( $ ) {

    'use strict';
     console.log(ajax_object);
     console.log(ajax_object.ajax_url);
     console.log(ajax_object.user_id);
     console.log(ajax_object.add_something_nonce);

})( jQuery );

I have been fighting the same problem myself for the last couple of days.

I am fairly new to Wordpress, so this might NOT be a 100% correct way to do this. I will try to correct it if anyone spots any errors (please comment if you find any).

Here's the code that finally worked for me:

Plugin's main php file:

<?php
/*
Plugin Name: My plugin
Description:
Version: 1.0
Author: Pirate
*/
class MyPlugin
{
    public function __construct()
    {
        // Adding an action for both logged and not logged users
        add_action('wp_ajax_myplugin_action', array($this, 'myplugin_handle_ajax'));
        add_action('wp_ajax_nopriv_myplugin_action', array($this, 'myplugin_handle_ajax'));

        // Adding action to wp_enqueue_scripts allows you to create nonces in the callback function
        add_action('wp_enqueue_scripts', array($this, 'myplugin_load_scripts_styles'));
    }

    public function myplugin_load_scripts()
    {
        wp_enqueue_script('myplugin_scripts', plugins_url('myplugin_scripts.js'), null, '1.0', true);

        $nonce = wp_create_nonce( 'ajax_validation' );
        wp_localize_script('myplugin_scripts', 'myplugin_data',
            array(
                'url' => admin_url('admin-ajax.php'),
                'security' =>  $nonce,
                'additional_data' = 'Anything else you need to send to JS'
            )
        );
    }

    public function myplugin_handle_ajax()
    {
        check_ajax_referer( 'ajax_validation', 'security' );

        // All the data you sent from JS is in the $_REQUEST
        $dataFromJS = $_REQUEST['dataFromJS'];
        
        // Here you can do whatever you want with it - process it, send it to other methods etc.

        $dataToSendBack = 'Data I might want to send back to JS';
        wp_send_json_success($dataToSendBack);  //parameter is optional
    }

//Instantiate the class
$my_plugin = new MyPlugin();

myplugin_scripts.js

// I did not have to wrap this in $(document).ready(),
// but it might be necessary depending on the execution order of your particular script
$('#ajax_button').on('click', function () {
    let ajax_data = {
        action: 'myplugin_handle_ajax',
        security: myplugin_data.secuirty,
        dataFromJS: 'Whatever I want to send to PHP'
    };

    $.ajax({
        url: myplugin_data.url,
        method: 'POST',
        data: ajax_data,
        success: function (response) {
            //optional handling of the response
        }
    })
});
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736252670a63.html

最新回复(0)