3

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...

1
  • Have you considered using a REST API endpoint instead? Securing and implementing a REST API endpoint is a lot easier/more straight forward
    – Tom J Nowell
    Commented May 21, 2017 at 17:32

3 Answers 3

0

you are doing some wrong things, 1st $_POST['data']; not contain any post data use json array's keys to get post data like.

$data_key1 = $_POST['key1'];
$data_key2 = $_POST['key2'];
// and so on ...

replace key1 key2 etc with json data keys which your ajax request sent.

7
  • Thanks for your comment. I've updated as you suggested and when I send it back to the js it still returns NULL to the console. This is what's got me so confused because if I eliminate the ajax request in my js and just console.log the 'attachment' I see the JSON respresentation and the key/value pairs, but when I send it to PHP I can't get at it.
    – gregz
    Commented Sep 24, 2013 at 18:59
  • post your console log here, before converting to json and after to json.
    – Anjum
    Commented Sep 24, 2013 at 19:03
  • replace 'data' with response in function(data) { console.log(data); }
    – Anjum
    Commented Sep 24, 2013 at 19:16
  • this is before JSON... r {cid: "c32", attributes: Object, collection: r, _changing: false, _previousAttributes: Object…} _changing: false _events: Object _pending: false _previousAttributes: Object attributes: Object --- and this is after... Object {id: 85, title: "145ce30c85", filename: "145ce30c1.jpg", url: "localhost:81/wordpress/wp-content/uploads/2013/09/…", link: "localhost:81/wordpress/?attachment_id=85"…} alt: "" author: "1" caption: "" compat: Object
    – gregz
    Commented Sep 24, 2013 at 19:19
  • 1
    If I send the attachment without the 'toJSON' it crashes the browser every time. Once you hit select on the media upload screen it locks up. I see what you're saying about it already being in JSON, but why is the representation so mixed up before converting to JSON and then when you do the conversion they are neatly arranged in value/key pairs? Excuse my ignorance on this matter...
    – gregz
    Commented Sep 25, 2013 at 3:06
0

after you var_dump in the function ajax_action_stuff, the JSON data is not JSON anymore. Just: echo $data;

0

In my AJAX calls, I find I do not need to encode/decode the data as JSON when POSTing the data. The data sent by jQuery.POST is already in key-value pairs, so IMO you don't need to make it JSON -- and you don't need to decode it in the .php function before working with it.

HOWEVER, I do use JSON before sending the data back to jQuery. After I get my gather my data in $content, I encode as JSON and return it in one line:

echo json_encode($content, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);

Then in jQuery, I decode the JSON:

function( content ) {
    var myContent = JSON.parse(content);
    // do what you want with the key-value pairs in myContent
}

I hope this will work for you as it does for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.