Wordpress using AJAX to Pass JS Variables to PHP

Viewed 466

I am trying to pass AJAX JS Variable to PHP in WordPress to access the variable.

I want to use it on the Woocommerce thank-you page

Here is the main plugin file:

add_action( 'woocommerce_thankyou', 'my_custom_function' );

add_action( 'wp_ajax_myaction', 'so_wp_ajax_function' );
add_action( 'wp_ajax_nopriv_myaction', 'so_wp_ajax_function' );


add_action( 'wp_enqueue_scripts', 'so_enqueue_scripts' );
function so_enqueue_scripts(){
  wp_register_script( 
    'ajaxHandle', 
    plugins_url('ajax.js', __FILE__), 
    array(), 
    false, 
    true 
  );
  wp_enqueue_script( 'ajaxHandle' );
  wp_localize_script( 
    'ajaxHandle', 
    'ajax_object', 
    array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) 
  );
}

My second PHP file: my_custom_function.php

function so_wp_ajax_function(){
  //DO whatever you want with data posted
  //To send back a response you have to echo the result!
  echo $_POST['name'];
  echo $_POST['age'];
  wp_die(); // ajax call must die to avoid trailing 0 in your response
}

function my_custom_function(){

// how can I pass it here
}

I am able to echo the $_POST['name'] but it is in the console log

JS File: ajax.js

jQuery(document).ready(function($){
    alert('asd');
  //Some event will trigger the ajax call, you can push whatever data to the server, simply passing it to the "data" object in ajax call
  $.ajax({
    url: ajax_object.ajaxurl, // this is the object instantiated in wp_localize_script function
    type: 'POST',
    data:{
      action: 'my_custom_function.php', // this is the function in your functions.php that will be triggered
      name: 'John',
      age: '38'
    },
    success: function( data ){
      //Do something with the result from server
      console.log( data );
    }
  });
});

I want to pass the value to my_custom_function(), any ideas? tried many ways but can't seem to work

0 Answers
Related