Ajax call to PHP action/function with array as data (in wordpress)

Solution:1

Use following code

JQuery

var jsonIDs = JSON.stringify(userIDs);

$.ajax({
    type: 'POST',
    url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
    data: {
        'action':'built_ranking', // This is our PHP function below
        'data' : jsonIDs,
    },
    dataType:"json",
    success:function(data){ 
        // This outputs the result of the ajax request (The Callback)
        //$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
        //$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
        console.log(data);
    },  
    error: function(errorThrown){
        window.alert(errorThrown);
    }
}); 

PHP

function built_ranking(){
    
    if ( isset($_POST) ) {
        $data = json_decode(stripslashes($_POST['data']));

        print json_encode($data);
                
        //$testResult = array("points"=>"test", "afstand"=>"test");
        //print json_encode($testResult);
    }
    
    
    // Always die in functions echoing AJAX content
   die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );

Solution:2

Let’s get started on making your first WordPress AJAX call…

Step 1:
Use the button below to download the full PDF Guide & Example Files:

Or you can use the two code sections below.

Javascript (The Call)
// This would normally be enqueued as a file, but for the sake of ease we will just print to the footer
function add_this_script_footer(){ ?>

<script>
jQuery(document).ready(function($) {

// This is the variable we are passing via AJAX
var fruit = ‘Banana’;

// This does the ajax request (The Call).
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
‘action’:’example_ajax_request’, // This is our PHP function below
‘fruit’ : fruit // This is the variable we are sending via AJAX
},
success:function(data) {
// This outputs the result of the ajax request (The Callback)
window.alert(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});

});
</script>
<?php }

add_action(‘in_admin_footer’, ‘add_this_script_footer’);
PHP (The Callback)
function example_ajax_request() {

// The $_REQUEST contains all the data sent via AJAX from the Javascript call
if ( isset($_REQUEST) ) {

$fruit = $_REQUEST[‘fruit’];

// This bit is going to process our fruit variable into an Apple
if ( $fruit == ‘Banana’ ) {
$fruit = ‘Apple’;
}

// Now let’s return the result to the Javascript function (The Callback)
echo $fruit;
}

// Always die in functions echoing AJAX content
die();
}

// This bit is a special action hook that works with the WordPress AJAX functionality.
add_action( ‘wp_ajax_example_ajax_request’, ‘example_ajax_request’ );
Step 2:

Copy and paste the downloaded file contents or the code sections above to your WordPress theme functions.php file.

Step 3:

Login to WordPress and you will see a popup that says “Apple”.