PHP: Pass an Array to Javascript using AJAX (jquery ) and PHP’s json_encode

PHP Code to build an Array of Arrays

    
    ....
    $container_arr = array();
    $arr = array(
        'src' =>  get_stylesheet_directory().'/images/track1/i3.jpg',
          'log'  => 'Array1:: '.$PHPBufferX,
        'warn'  => $PHPwarnX,
        'error' => $PHPerrorX
          );
  array_push(  $container_arr, (array)$arr );
  
  $arr = array(
        'src' =>  get_stylesheet_directory().'/images/track1/i4.jpg',
          'log'  => 'Array2:: '.$PHPBufferX,
        'warn'  => $PHPwarnX,
        'error' => $PHPerrorX
          ); 
  array_push(  $container_arr,  (array)$arr );
          
  echo json_encode($container_arr);
  error_log('JSON ENCODE ok ...');  
  die();

JavaScript / JQuery Code to read Arrays

jQuery(document).ready(function()
{
var greeting = jQuery("#greeting3").val();
var trackids = jQuery("#trackids").val();
jQuery("#ajax3-button").click(function()
{
console.log('ajax3-button pressed') ;
jQuery.ajax({
type: 'POST',
url :  'http://localhost/wordpress/wp-admin/admin-ajax.php',
data: { action: 'myAjax2', greeting3: greeting, trackids: trackids   },
// dataType: 'html',  /* used for JSON Debugging */
dataType: 'json',
success: function(data, textStatus, XMLHttpRequest)
{
console.log("Returing from AJAX request - Adding greetings to Div:  #divp4 ");

   $.each(data, function(index, obj)
    {
    jQuery("#divp4").append('<p><b>Array Index: '+ (index+1) + '</p>');
    jQuery("#divp4").append('<p><b>Image SRC  : </b>' + obj.src +'</p>');
    jQuery("#divp4").append('<p><b>PHP LOG    : </b>' + obj.log +'</p>');
    jQuery("#divp4").append('<p><b>Warnings   : </b>' + obj.warn +'</p>');
    jQuery("#divp4").append('<p><b>Errors     : </b>' + data.error +'</p>');
    });
   //      jQuery("#divp4").append('<p>'+ data + '</p>');   /* used for JSON Debugging */
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{ alert(errorThrown); }
});
var ih = '<p>AJAX3 button presesed : AJAX request in progress ! - Trackids: ' + trackids +' </p>' ;
document.getElementById("divp3").innerHTML = ih;
console.log('Leaving ajax3-button Ajax action');
});
});

Output:

 
Array Index: 1
Image SRC : D:\xampp\htdocs\wordpress/wp-content/themes/twentyfifteen-child/images/track1/i3.jpg
PHP LOG : Array1:: Greeting from AJAX request 3:: - CWD: : D:\xampp\htdocs\wordpress\wp-admin
Warnings : null
Errors : undefined

Array Index: 2
Image SRC : D:\xampp\htdocs\wordpress/wp-content/themes/twentyfifteen-child/images/track1/i4.jpg
PHP LOG : Array2:: Greeting from AJAX request 3:: - CWD: : D:\xampp\htdocs\wordpress\wp-admin
Warnings : null
Errors : undefined

 PHP Error Log

  • The array output was triggered by a print_r  PHP comand
  • The Output was deleted by running ob_end_clean() before running:  echo json_encode($container_arr);
[04-Dec-2015 16:09:39 UTC] myAjax2()
[04-Dec-2015 16:09:39 UTC] ajaxWrapper():: ob_start with CallBack Function
[04-Dec-2015 16:09:39 UTC] PHP Parse DUMP::
[04-Dec-2015 16:09:39 UTC] JSON ENCODE  ...
[04-Dec-2015 16:09:39 UTC] myObCallback() active ::  Cleaning Current PHP Buffer:: 
Array
(
    [0] => Array
        (
            [src] => D:\xampp\htdocs\wordpress/wp-content/themes/twentyfifteen-child/images/track1/i3.jpg
            [log] => Array1:: Greeting from AJAX request 3::  - CWD: D:\xampp\htdocs\wordpress\wp-admin</
            [warn] =>
            [error] =>
        )
    [1] => Array
        (
            [src] => D:\xampp\htdocs\wordpress/wp-content/themes/twentyfifteen-child/images/track1/i4.jpg
            [log] => Array2:: Greeting from AJAX request 3::  - CWD: : D:\xampp\htdocs\wordpress\wp-admin</
            [warn] =>
            [error] =>
        )

)
[04-Dec-2015 16:09:39 UTC] JSON ENCODE ok - Now Dying ...
[04-Dec-2015 16:09:39 UTC]  -------------- [SHUTDOWNHANDLER]:: Start  -----------------------
[04-Dec-2015 16:09:39 UTC] [logLastError]:: No errors/Warnings found in this PHP Page
[04-Dec-2015 16:09:39 UTC]  -------------- [xx SHUTDOWNHANDLER]:: Leaving:  -----------------------

Reference

 

Leave a Reply

Your email address will not be published. Required fields are marked *