Read encoded data in ajax request

Viewed 65

My ajax retrieves the following response in the console:

PHP

$checkout_session_data = json_encode(['id' => $checkout_session->id]);
wp_send_json_success( $checkout_session_data );

// this is then retuend to the JS ajax function.
data: "{\"id\":\"cs_test_a1SOgBGIPsRrECu5pP8TDCW16JYMMHnGnmfh7Lp6qf8bvwTk3hK97sI7e7\"}"
success: true

I'm unclear how to get the ID value from the response from within the .done part of my ajax function.

.done( function(response) {
  if( response.success == true ) {
    console.log(response);
  }

Attempts:
console.log(response.data.id);
console.log(response[0].id);

2 Answers

Your data is double encoded, wp_send_json_success encodes the data passed to it to JSON so do not json_encode your data before you pass it to wp_send_json_success,

$checkout_session_data = ['id' => $checkout_session->id];
wp_send_json_success( $checkout_session_data );
.done( function(response) {
  if( response.success == true ) {
    console.log(response.data.id);
  }
}

Instead of using the ajax request, you would be better served by using the getJSON function here. A sample of the code is shown below.

$.getJSON( "ajax/test.json", function( data ) {
  var items = [];
  $.each( data, function( key, val ) {
    items.push( "<li id='" + key + "'>" + val + "</li>" );
  });
 
});

You can find further details from this link https://api.jquery.com/jquery.getJSON/

Related