Site icon Hip-Hop Website Design and Development

Retrieving JSON data in ajax request from media uploader

I’m having some problems getting my JSON data that’s being passed via an ajax request.

I’m trying to implement the media uploader into a plugins settings page. I’ve got it functioning properly using this method as far as the media uploader functionality is concerned. I’d like to be able to retrieve the ‘attachment’ data in PHP, decode it and then process it once the media uploader is closed and the images have been selected. The ajax request is working because I can echo back a response and it receives it, but when I try and decode the JSON string and perform a vardump it returns null, and if I try and access an array key it is empty. Here is the js code…

jQuery(document).ready(function($){

  var file_frame;

  jQuery('.upload_image_button').live('click', function( event ){

    event.preventDefault();

    if ( file_frame ) {
      file_frame.open();
      return;
    }

    file_frame = wp.media.frames.file_frame = wp.media({
      title: jQuery( this ).data( 'uploader_title' ),
      button: {
        text: jQuery( this ).data( 'uploader_button_text' ),
      },
      multiple: true 
    });

    file_frame.on( 'select', function() {

      var selection = file_frame.state().get('selection');
      selection.map( function( attachment ) {
        attachment = attachment.toJSON();
        $.post(ajax_object.ajaxurl, {
           action: 'ajax_action',
           data: attachment
        }, function(data) {
           console.log(data);  
        });
      });
    }); 

    file_frame.open();
  });

});

And here is the php function that is located in the main plugin file that receives the ajax request…

function ajax_action_stuff() {
    $image_data = $_POST['data'];
    $data = json_decode( $image_data, true );
    var_dump( $data );
    // echo $data[url];
    die(); 
}
add_action( 'wp_ajax_ajax_action', 'ajax_action_stuff' );

And the enqueued scripts that are located in the main plugin file…

function gzmu_load_scripts() {
    wp_enqueue_media();
    wp_enqueue_script( 'gzmu-media-upload', plugin_dir_url(__FILE__) . 'gzmu-media-upload.js' );
    wp_localize_script( 'gzmu-media-upload', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
    wp_enqueue_style( 'admin-styles', plugin_dir_url(__FILE__) . '/css/admin.css' );
}
add_action( 'admin_enqueue_scripts', 'gzmu_load_scripts' );

I’ve never worked with JSON before so I’m a bit confused on how to handle the data. Any advice on what I could be doing wrong would be greatly appreciated. Thanks…