-3

I'm trying to push an array from jquery to a php function and I'm out of options to make it work. I've tried multiple options; $_request, $_post, with JSON.stringify, without JSON.stringify, ...

But I keep getting 'null'; can't figure out the right combination. Someone who's willing to explain me why it's not working and how to fix?

JQuery code:

    var userIDs = [];
    
    $( "tr.user-row" ).each(function() {
        var userID = $(this).attr("data-userid");
        userIDs.push(userID);
        
    });
    
    var jsonIDs = JSON.stringify(userIDs);
    
    $.ajax({
        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' : {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 code:

function built_ranking(){
    
    if ( isset($_REQUEST) ) {
        
        $data = json_decode(stripslashes($_REQUEST['data']));
        foreach($data as $d){
             echo $d;
        }
        
        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' );

If I print the $testResult it returns the array and I can use the data back in jquery, so the function is called. I've based the code on Send array with Ajax to PHP script I've multiple ajax calls with $_request instead of $_post and they are working fine. But maybe they can't handle arrays? I've no idea... ^^

user3346696
  • 169
  • 1
  • 4
  • 17
  • 1
    Why `stripslashes`? And have you first of all confirmed, what `$_REQUEST['data']` actually contains? – CBroe Mar 02 '22 at 11:02
  • 1
    You're guessing what you're sending and receiving and trying out "combinations" without trying to understand what's happening. You have access to browser dev console - press F12, go to network and you can inspect **what** it is you're sending (what the payload's keys are). Don't guess, assert. – N.B. Mar 02 '22 at 11:03
  • 2
    `$_POST` only works for POST requests. You're ajax is making a GET request (the default method if nothing else is defined). If you want your Ajax to POST data, you need to add: `type: 'POST'` to your Ajax function. – M. Eriksson Mar 02 '22 at 11:03
  • "But I keep getting 'null'" - what does that mean? Did you check whether the browser sends the request as expected, to distinguish whether this is a JS problem or a PHP problem? – Nico Haase Mar 02 '22 at 11:06
  • All valid comments. The combination of them got me out the guessing phase. I checked in the console what was sent and adapted the the call to post with just data:jsonIDs. Then I checked what was in $_POST and saw I needed the stripslashes so added that line again. Thanks to all. i've learned a good lesson today. – user3346696 Mar 02 '22 at 11:16

1 Answers1

0

What I learned from this question and the help I got: don't guess, debug. try to find ways to see what is posted, what is received, ...

You can read how to 'debug' in the comments of the original question. Useful for starters as me ;)

Working 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' );
user3346696
  • 169
  • 1
  • 4
  • 17