ajax print

code test

test requirements » license »

the input:

     
Enter your JSON here - it must be valid JSON on a single line - the "json=" parameter in the URL will also load here:

the output:

ajax response will load here
ajax response will load here

the code:

download the all-in-one: tfredrikson_com_1_0_0.zip
<?php
 /**
 * @author Tamara Jean (TJ) Fredrikson http://www.tfredrikson.com
 * @copyright Copyright (C) 2013 TJ Fredrikson
 * @license http://creativecommons.org/licenses/by-sa/3.0/ Attribution-ShareAlike 3.0
 */ 

/**
 * This is the simple controller for the Ajax Print code test
 * 
 * It performs the following functions:
 *   1) reads the $_REQUEST parameter to get the JSON data
 *   2) loads the model with the array to print
 * 
 */ 

$debug=0;
$ajax_debug=0;
$print_r_debug=0;

if($ajax_debug)
{
	print "\n[BEGIN PHP print_r of _REQUEST params]\n";
	print_r($_REQUEST);
	print "[END PHP print_r of _REQUEST params]\n\n";
}

if( !empty($_REQUEST) && isset( $_REQUEST['json'] ) )
{
	$php_array = Array();
	$php_array = json_decode($_REQUEST['json'], true);
}
if( !empty($php_array) )
{
	if($ajax_debug)
	{
		print "\n[BEGIN var_dump( php_array ) after json_decode]\n";
		var_dump( $php_array );
		print "\n[END var_dump( php_array ) after json_decode]\n\n";
	}

	if($print_r_debug)
	{
		print "\n[BEGIN PHP print_r]\n";
		print_r($php_array);
		print "\n[END PHP print_r]\n\n";
	}

	require_once('../models/ajax_print_model.php');
	$ajax_print_r = new Ajax_Print_Model;
	print $ajax_print_r->ajax_print_for_test($php_array);
}	

exit;                                    
<?php
 /**
 * @author Tamara Jean (TJ) Fredrikson http://www.tfredrikson.com
 * @copyright Copyright (C) 2013 TJ Fredrikson
 * @license http://creativecommons.org/licenses/by-sa/3.0/ Attribution-ShareAlike 3.0
 */ 

/**
 * This is the simple model for the Ajax Print code test
 * 
 * It has one method:
 *   @param the array to print
 *   @param the depth (used for resursion on multi-dimensional arrays)
 *   @return the text string formatted like print_r with 
 		every AJAX_PRINT_NUM_ITEM_TO_BOLD item bold
 */ 

$debug=0;

if(!defined(AJAX_PRINT_NUM_ITEM_TO_BOLD)) define('AJAX_PRINT_NUM_ITEM_TO_BOLD', 8);

class Ajax_Print_Model {

	public $debug=0;
	
	function __construct()
	{
		// do nothing	
	}
	
	public function ajax_print_for_test( $array_to_print, $depth = 0 )
	{
		$ajax_debug=0;
		$text_to_return = ''; //initialized

		if($ajax_debug)
		{
			$text_to_return .= "[BEGIN print_r_for_test at depth $depth]";
		}

		if(is_array( $array_to_print ))
		{
			$text_to_return .= "Array\n";
			for($i = 0; $i < $depth; $i++ ) $text_to_return .= "\t";
			$text_to_return .= "(\n";
			$counter = 0;
			foreach( $array_to_print as $key => $value )
			{
				for($i = 0; $i < $depth; $i++ ) $text_to_return .= "\t";
			
				$counter++;
				if( $depth == 0 && $counter % AJAX_PRINT_NUM_ITEM_TO_BOLD == 0 )
				{
					$text_to_return .= '<strong class="ajax_print_bold">';
				}
				$text_to_return .= "    [".$key."] => ";			
				if(is_array( $value ))
				{
					$text_to_return .= $this->ajax_print_for_test( $value, $depth+1 );
				}
				else
				{
					$text_to_return .= $value."\n";			
				}
				if( $depth == 0 && $counter % AJAX_PRINT_NUM_ITEM_TO_BOLD == 0 )
				{
					$text_to_return .= "</strong>";
				}
			}
			for($i = 0; $i < $depth; $i++ ) $text_to_return .= "\t";
			$text_to_return .= ")\n";
		}
		
		if($ajax_debug)
		{
			for($i = 0; $i < $depth; $i++ ) $text_to_return .= "\t";
			$text_to_return .= "[END PHP print_r_for_test at depth $depth]\n\n";
		}
		
		return $text_to_return;
	}	

} // end class Ajax_Print_Model                                    
<?php
 /**
 * @author Tamara Jean (TJ) Fredrikson http://www.tfredrikson.com
 * @copyright Copyright (C) 2013 TJ Fredrikson
 * @license http://creativecommons.org/licenses/by-sa/3.0/ Attribution-ShareAlike 3.0
 */ 

/**
 * This is the simple front end view for the Ajax Print code test
 * 
 * It performs the following functions:
 *   1) presents the HTML5 and CSS that displays the view
 *   2) presents buttons that when clicked trigger an Ajax call
 *   3) has an area to display the data returned from the Ajax call
 * 
 */ 

$debug=0;

?>                    
                    <br />
                    <div class="hero-unit">
                        <h1>AJAX PRINT</h1>
                        <h2>code test</h2>
                        <p>this simple coding test uses Ajax to read in a JSON string and produce output as if you had coded print_r() on an array - read the requirements for more detail</p>
                        <div>
                            <a id="modal-120697" href="#modal-container-120697" role="button" class="btn btn-success btn-large" data-toggle="modal">requirements &raquo;</a>
                            <div id="modal-container-120697" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
                                    <h3 id="myModalLabel">Ajax Print Code Test Requirements</h3>
                                </div>
                                <div class="modal-body">
                                    <ol>
                                        <li>There is a front-end page which will call your page via AJAX. Your page should expect a JSON input of some kind. (You don't need to write this part, unless you want to)</li>
                                        <li>This input should be cleaned and converted into a php array.</li>
                                        <li>Next, please iterate through that array and print out every element of the array (Similar to PHP's print_r feature, without actually using print_r).</li>
                                        <li>Every 8th value that's printed should be bolded.</li>
                                    </ol>
                                    <blockquote>
                                        <small>this is somewhat impractical since an AJAX page wouldn't be printing information, but it's been requested as a code sample for reviewing coding style</small>
                                    </blockquote>
                                </div>
                                <div class="modal-footer">
                                    <button class="btn btn-inverse" data-dismiss="modal" aria-hidden="true">Close</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    
                    <!-- BEGIN CONTENT -->
                    <div id="the_input" class="span11">
                        <h3>THE INPUT:</h3>
                        <div style="text-align: center">
                            <input id="ajax_trigger" class="btn btn-inverse btn-small" type="button" value="simple &raquo;">&nbsp;&nbsp;
                            <input id="ajax_trigger_multi" class="btn btn-inverse btn-small" type="button" value="multi-dimensional &raquo;">&nbsp;&nbsp;
                            <input id="ajax_clear" class="btn btn-small" type="button" value="clear &raquo;">
                        </div>
                        <div class="span12" style="">
                            <small style="color: #666; ">Enter your JSON here - it must be valid JSON on a single line - the "json=" parameter in the URL will also load here:</small>
                            <textarea id="json_textarea" class="span12" style="height: 100px;">
                                <?php print $json_string; ?>
                            </textarea>
                            <div class="span12" style="text-align: right; ">
                                <input id="ajax_trigger_textarea" type="button" style="margin-right: 1.4em;" class="btn btn-success btn-medium" value="trigger ajax &raquo;">
                            </div>
                        </div>
                    </div>
                    <div class="span11">
                        <h3>THE OUTPUT:</h3>
                        <div class="tabbable" id="tabs-183435">
                            <ul class="nav nav-tabs">
                                <li class="active">
                                    <a href="#panel-293945" data-toggle="tab">Line Breaks</a>
                                </li>
                                <li>
                                    <a href="#panel-575900" data-toggle="tab">No Line Breaks</a>
                                </li>
                            </ul>
                            <div class="tab-content">
                                <div class="tab-pane active" id="panel-293945">
                                    <div id="ajax_wrap_with_lines">
                                        <div id="ajax_data_with_lines">
                                            <pre>ajax response will load here</pre>
                                        </div>
                                    </div>
                                </div>
                                <div class="tab-pane" id="panel-575900">
                                    <div id="ajax_wrap">
                                        <div id="ajax_data">
                                            <pre>ajax response will load here</pre>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="span11">
                        <hr />
                        <div style="text-align: right;">
                            <a href="#at_top">to top</a>
                        </div>
                        <hr />
                        <h3>THE CODE:</h3>
                        <h4 style="text-align: right;">download the complete source code:
                            <a href="code_samples/ajax_print_1_0.zip">ajax_print.zip</a>
                        </h4>
                        <div class="tabbable tabs-left" id="tabs-183436">
                            <ul class="nav nav-tabs">
                                <li class="active">
                                    <a href="#panel-293946" data-toggle="tab">controllers</a>
                                </li>
                                <li>
                                    <a href="#panel-575906" data-toggle="tab">models</a>
                                </li>
                                <li>
                                    <a href="#panel-575907" data-toggle="tab">views</a>
                                </li>
                                <li>
                                    <a href="#panel-575908" data-toggle="tab">index.php</a>
                                </li>
                                <li>
                                    <a href="#panel-575909" data-toggle="tab">json_sample_data.js</a>
                                </li>
                                <li>
                                    <a href="#panel-575910" data-toggle="tab">license.txt</a>
                                </li>
                            </ul>
                            <div class="tab-content">
                                <div class="tab-pane active" id="panel-293946">
                                    <pre>
                                        <?php print htmlentities(file_get_contents( "code_samples/ajax_print/controllers/ajax_print_controller.php.txt",true)); ?>
                                    </pre>
                                </div>
                                <div class="tab-pane" id="panel-575906">
                                    <pre>
                                        <?php print htmlentities(file_get_contents( "code_samples/ajax_print/models/ajax_print_model.php.txt",true)); ?>
                                    </pre>
                                </div>
                                <div class="tab-pane" id="panel-575907">
                                    <pre>
                                        <?php print htmlentities(file_get_contents( "code_samples/ajax_print/views/front_end_view.php.txt",true)); ?>
                                    </pre>
                                </div>
                                <div class="tab-pane" id="panel-575908">
                                    <pre>
                                        <?php print htmlentities(file_get_contents( "code_samples/ajax_print/index.php.txt",true)); ?>
                                    </pre>
                                </div>
                                <div class="tab-pane" id="panel-575909">
                                    <pre>
                                        <?php print htmlentities(file_get_contents( "code_samples/ajax_print/json_sample_data.js.txt",true)); ?>
                                    </pre>
                                </div>
                                <div class="tab-pane" id="panel-575910">
                                    <pre>
                                        <?php print htmlentities(file_get_contents( "code_samples/ajax_print/license.txt",true)); ?>
                                    </pre>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- END CONTENT -->
                    
        <!-- JavaScript Last as an optimization -->
        <script type="text/javascript" src="json_sample_data.js"></script>
        <script type="text/javascript">
            var json_from_request = '<?php print $json_string; ?>';
            var url_without_json_string = "controllers/ajax_print_controller.php?json="; // initialized
            
            function perform_ajax_call( json_string_triggered )
            {
            	// console.log('json_string_triggered: '+json_string_triggered);
              	// clear previous html
                $( "#ajax_data_with_lines" ).html( '' );
                $( "#ajax_data" ).html( '' );

            	if(json_string_triggered.length == 0)
            	{
            		// no data to send
            	 	var alert_error_html = '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">x</button><h4>OOPS</h4> <strong>no data to send</strong> please add JSON data</div>' ;
            	    $( "#ajax_data_with_lines" ).html( alert_error_html );
            	    $( "#ajax_data" ).html( alert_error_html );
					return false;             	
            	}

            	// send the ajax request
                var xmlRequest = $.ajax({
                    url: url_without_json_string+encodeURIComponent(json_string_triggered),
                    beforeSend: function() {
					  var loading_graphic_html = '<div id="ajax_data_with_lines_loading"><img src="views/img/loading-bar.gif" alt="loading graphic" style="" /></div>';
    				  $('#ajax_data_with_lines').html(loading_graphic_html);
    				  $('#ajax_data').html(loading_graphic_html);
  					},
                });
                
                // update with the response
                xmlRequest.done(function( html ) {
	            	// console.log('html returned from ajax: ['+html+']');
                	if( html.length > 0 )
                	{
            	        $( "#ajax_data_with_lines" ).html( "<pre>"+html+"</pre>" );
            	        $( "#ajax_data" ).html( html );
            	    } else {
            	    	var alert_error_html = '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">x</button><h4>OOPS</h4> <strong>something went wrong</strong> check your JSON format</div>' ;
            	        $( "#ajax_data_with_lines" ).html( alert_error_html );
            	        $( "#ajax_data" ).html( alert_error_html );
            	    }
                });
                
            }
            
            // bind events to the buttons
            $(document).ready(function(){
            
              // sample data buttons
              $("#ajax_trigger_multi").click(function(){
              		// console.log('jsonDocument_multi: ['+jsonDocument_multi+']');
            		$( "#json_textarea" ).val( jsonDocument_multi );
                });
              $("#ajax_trigger").click(function(){
              		// console.log('jsonDocument_multi: ['+jsonDocument+']');
            		$( "#json_textarea" ).val( jsonDocument );
                });  // end sample data buttons
                

              // clear ajax button
              $("#ajax_clear").click(function(){
              	// console.log('json_textarea: ['+$( "#json_textarea" ).html( '' )+']');
            	$( "#json_textarea" ).val( '' );
            	$( "#ajax_data_with_lines" ).html( "<pre>ajax response will load here</pre>" );
            	$( "#ajax_data" ).html( "<pre>ajax response will load here</pre>" );
              });  // end clear ajax button


              // trigger ajax button
              $("#ajax_trigger_textarea").click(function(){
            		perform_ajax_call( $("#json_textarea").val() );
            		// move to the input/output area
            		document.location.hash = "";
            		document.location.hash = "#the_input";
              });  // end trigger ajax button
              
            }); // end ready function
        </script>
        <!-- JavaScript Last as an optimization -->                    
                                    
<?php
 /**
 * @author Tamara Jean (TJ) Fredrikson http://www.tfredrikson.com
 * @copyright Copyright (C) 2013 TJ Fredrikson
 * @license http://creativecommons.org/licenses/by-sa/3.0/ Attribution-ShareAlike 3.0
 */ 

/**
 * This is the index file that loads the simple front end
 * 
 * It performs the following functions:
 *   1) reads in the parameters from the request
 *   2) loads the view with injected data
 * 
 */ 

$debug=0;

$json_string = '';
if( !empty($_REQUEST) && isset( $_REQUEST['json'] ) )
{
	$json_string = $_REQUEST['json'];
}

if($debug)
{
	print "\n<br />[BEGIN PHP print_r of _REQUEST params]<br />\n";
	print_r($_REQUEST);
	print "\n<br />[END PHP print_r of _REQUEST params]<br /><br />\n\n";

	print "\n<br />[BEGIN json_string]<br />\n";
	print($json_string);
	print "\n<br />[END json_string]<br /><br />\n\n";
}

$path_to_common = '../../../'; 
 
require_once( $path_to_common.'_common/views/sub_views/header.php' );
require_once( 'views/front_end_view.php' );
require_once( $path_to_common.'_common/views/sub_views/footer.php' );

                                    
// adapted from: 
// states_hash.json on GitHub Gist:
// https://gist.github.com/mshafrir/2646763#file-states_hash-json

var jsonDocument = '{ "AL": "Alabama", "AK": "Alaska", "AS": "American Samoa", "AZ": "Arizona", "AR": "Arkansas", "CA": "California", "CO": "Colorado", "CT": "Connecticut", "DE": "Delaware", "DC": "District Of Columbia", "FM": "Federated States Of Micronesia", "FL": "Florida", "GA": "Georgia", "GU": "Guam", "HI": "Hawaii", "ID": "Idaho", "IL": "Illinois", "IN": "Indiana", "IA": "Iowa", "KS": "Kansas", "KY": "Kentucky", "LA": "Louisiana", "ME": "Maine", "MH": "Marshall Islands", "MD": "Maryland", "MA": "Massachusetts", "MI": "Michigan", "MN": "Minnesota", "MS": "Mississippi", "MO": "Missouri", "MT": "Montana", "NE": "Nebraska", "NV": "Nevada", "NH": "New Hampshire", "NJ": "New Jersey", "NM": "New Mexico", "NY": "New York", "NC": "North Carolina", "ND": "North Dakota", "MP": "Northern Mariana Islands", "OH": "Ohio", "OK": "Oklahoma", "OR": "Oregon", "PW": "Palau", "PA": "Pennsylvania", "PR": "Puerto Rico", "RI": "Rhode Island", "SC": "South Carolina", "SD": "South Dakota", "TN": "Tennessee", "TX": "Texas", "UT": "Utah", "VT": "Vermont", "VI": "Virgin Islands", "VA": "Virginia", "WA": "Washington", "WV": "West Virginia", "WI": "Wisconsin", "WY": "Wyoming" }' ;



// adapted from
// http://stackoverflow.com/questions/1650090/javascript-multi-level-array-of-json-objects-how-to-access-key-value-pair-in-s

var jsonDocument_multi = '[{"title": "Parent1", "children": [{"childname": "Child11"}, {"childname":"Child12"}], "cars":[{"carname": "Car11"}, {"carname": "Car12"}] }, {"title": "Parent2", "children": [{"childname": "Child21"}, {"childname": "Child22"}], "cars": [{"carname": "Car21"}, {"carname": "Car22"}] }, {"title": "Parent2", "children": [{"childname": "Child21"}, {"childname": "Child22"}], "cars": [{"carname": "Car21"}, {"carname": "Car22"}] }, {"title": "Parent2", "children": [{"childname": "Child21"}, {"childname": "Child22"}], "cars": [{"carname": "Car21"}, {"carname": "Car22"}] }, {"title": "Parent2", "children": [{"childname": "Child21"}, {"childname": "Child22"}], "cars": [{"carname": "Car21"}, {"carname": "Car22"}] }, {"title": "Parent2", "children": [{"childname": "Child21"}, {"childname": "Child22"}], "cars": [{"carname": "Car21"}, {"carname": "Car22"}] },{"title": "Parent2", "children": [{"childname": "Child21"}, {"childname": "Child22"}], "cars": [{"carname": "Car21"}, {"carname": "Car22"}] }, {"title": "Parent2", "children": [{"childname": "Child21"}, {"childname": "Child22"}], "cars": [{"carname": "Car21"}, {"carname": "Car22"}] }, {"title": "Parent2", "children": [{"childname": "Child21"}, {"childname": "Child22"}], "cars": [{"carname": "Car21"}, {"carname": "Car22"}] }, {"title": "Parent2", "children": [{"childname": "Child21"}, {"childname": "Child22"}], "cars": [{"carname": "Car21"}, {"carname": "Car22"}] }, {"title": "Parent2", "children": [{"childname": "Child21"}, {"childname": "Child22"}], "cars": [{"carname": "Car21"}, {"carname": "Car22"}] }, {"title": "Parent2", "children": [{"childname": "Child21"}, {"childname": "Child22"}], "cars": [{"carname": "Car21"}, {"carname": "Car22"}] }, {"title": "Parent2", "children": [{"childname": "Child21"}, {"childname": "Child22"}], "cars": [{"carname": "Car21"}, {"carname": "Car22"}]}]';
                                    
Copyright (c) 2013 TJ Fredrikson
All rights reserved.

This license is a legal agreement between you and TJ Fredrikson for the use
of the Code Samples Software (the "Software").  By obtaining the Software you
agree to comply with the terms and conditions of this license.

The Software is released under the Creative Commons 
Attribution-ShareAlike 3.0 license.  The details can be found at: 
http://creativecommons.org/licenses/by-sa/3.0/ 


INDEMNITY
You agree to indemnify and hold harmless the authors of the Software and
any contributors for any direct, indirect, incidental, or consequential
third-party claims, actions or suits, as well as any related expenses,
liabilities, damages, settlements or fees arising from your use or misuse
of the Software, or a violation of any terms of this license.

DISCLAIMER OF WARRANTY
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR
IMPLIED, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF QUALITY, PERFORMANCE,
NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.

LIMITATIONS OF LIABILITY
YOU ASSUME ALL RISK ASSOCIATED WITH THE INSTALLATION AND USE OF THE SOFTWARE.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS OF THE SOFTWARE BE LIABLE
FOR CLAIMS, DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION
WITH THE SOFTWARE. LICENSE HOLDERS ARE SOLELY RESPONSIBLE FOR DETERMINING THE
APPROPRIATENESS OF USE AND ASSUME ALL RISKS ASSOCIATED WITH ITS USE, INCLUDING
BUT NOT LIMITED TO THE RISKS OF PROGRAM ERRORS, DAMAGE TO EQUIPMENT, LOSS OF
DATA OR SOFTWARE PROGRAMS, OR UNAVAILABILITY OR INTERRUPTION OF OPERATIONS.


                                    

1. Identify your toughest problem.
2. Solve it the simplest way possible.
3. Repeat. Kent Beck, eXtreme developer



This site is mobile responsive
(check it out at Am I Responsive)
it is valid HTML5 (see the validator)
and has been tested on many different devices and in many different browsers
(see the Browserstack screenshots)

this site is green


This site was built using the default design provided by
LayoutIt with Bootstrap.js and LESS.CSS
It's written in PHP and follows a loose MVC pattern
It uses JQuery for tabs and Ajax and
reads and writes some of it's data in JSON

Creative Commons License
This work is licensed under a
Creative Commons Attribution-ShareAlike 3.0 Unported License.
© 2013 TJ Fredrikson