<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Zulius &#187; php</title>
	<atom:link href="http://www.zulius.com/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.zulius.com</link>
	<description>Advanced Application Development</description>
	<lastBuildDate>Fri, 30 Jul 2010 05:53:53 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Send multidimensional arrays to PHP with jQuery and AJAX</title>
		<link>http://www.zulius.com/how-to/send-multidimensional-arrays-php-with-jquery-ajax/</link>
		<comments>http://www.zulius.com/how-to/send-multidimensional-arrays-php-with-jquery-ajax/#comments</comments>
		<pubDate>Sat, 26 Dec 2009 14:48:46 +0000</pubDate>
		<dc:creator>Tim White</dc:creator>
				<category><![CDATA[how-to]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.zulius.com/?p=656</guid>
		<description><![CDATA[AJAX communication between the client browser and web server is a handy method of transferring data without forcing the user to refresh the page.  Typically, the data sent to the server is a simple set of form fields or flags.  However, it is also possible to submit more complex structured data.  This [...]]]></description>
			<content:encoded><![CDATA[<div class="wp-caption alignleft" style="width: 170px"><img alt="AJAX" src="/img/blog/assocArrayPhpJqueryAjax.png" title="AJAX" width="150" height="110" /><p class="wp-caption-text">javascript array</p></div>
<p><a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29">AJAX</a> communication between the client browser and web server is a handy method of transferring data without forcing the user to refresh the page.  Typically, the data sent to the server is a simple set of form fields or flags.  However, it is also possible to submit more complex structured data.  This tutorial will demonstrate 3 different methods used to pass multidimensional javascript arrays using <a href="http://jquery.com/">jQuery</a> and AJAX to a <a href="http://www.php.net/">PHP</a> web server.</p>
<h2>The Wrong Way</h2>
<p>My first instinct was that multidimensional JS arrays could be passed directly to jQuery's AJAX functions.  I expected that the array would be automatically preserved in the request, and show up in PHP's $_GET/$_POST variables.  The following example shows this doesn't work.</p>
<p>The code below attempts to post a JS associative array ("data", line 9) to the web server using jQuery's <a href="http://docs.jquery.com/Ajax/jQuery.ajax">$.ajax()</a> function.  The $.ajax() function is jQuery's lowest level AJAX function, but still provides a high level approach and lots of options.</p>
<pre class="brush: xml; first-line: 1; gutter: true;">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; dir=&quot;ltr&quot; lang=&quot;en-US&quot;&gt;
    &lt;head profile=&quot;http://gmpg.org/xfn/11&quot;&gt;
        &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;
        &lt;title&gt;jQuery AJAX arrays&lt;/title&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&quot;&gt;&lt;/script&gt;
        &lt;script type=&quot;text/javascript&quot;&gt;
                sendAjax = function(){
                    var data = {
                                  foo:  123,
                                  bar:  456,
                                  rows: [
                                          {
                                            column1 : 'hello',
                                            column2 : 'hola',
                                            column3 : 'bonjour',
                                          },
                                          {
                                            column1 : 'goodbye',
                                            column2 : 'hasta luego',
                                            column3 : 'au revoir',
                                          },
                                        ],
                                  test1:{
                                          test2: {
                                                   test3:  'baz'
                                                 }
                                        }
                                };

                    $.ajax({
                            type:           'post',
                            cache:          false,
                            url:            './ajax/',
                            data:           data
                           });
                }

        &lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;input type=&quot;button&quot; style=&quot;width: 130px; height: 60px&quot; value=&quot;send AJAX&quot; onclick=&quot;sendAjax();&quot; /&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>When the button is clicked, the following data shows up in PHP's $_POST variable:</p>
<pre class="brush: plain;">
Array
(
    [foo] =&gt; 123
    [bar] =&gt; 456
    [rows] =&gt; [object Object]
    [test1] =&gt; [object Object]
)
</pre>
<p>As shown, the first level of the array data is preserved (keys "foo" and "bar").  However, jQuery simply calls .toString() on the nested arrays at keys "rows" and "test1", and they get passed to PHP with the useless values "[object Object]".</p>
<h2>Method 1 - Form input arrays</h2>
<p>It's possible to name the keys of the JS array as HTML form input arrays (ie. named with square brackets) so that <a href="http://php.net/manual/en/language.variables.external.php">PHP decodes the array's key names as nested arrays</a>.  I don't recommend this method because it does not maintain the JS array's original structure in the Javascript.  However, it can be used if you just need to get the AJAX request working without using JSON.</p>
<p>
The original JS "data" array can be renamed/restructured as:
</p>
<pre class="brush: jscript;">
sendAjax = function(){
	var data = {
				  foo:  123,
				  bar:  456,
				  'rows[0][column1]':    'hello',
				  'rows[0][column2]':    'hola',
				  'rows[0][column3]':    'bonjour',
				  'rows[1][column1]':    'goodbye',
				  'rows[1][column2]':    'hasta luego',
				  'rows[1][column3]':    'au revoir',
				  'test1[test2][test3]': 'baz'
				};
	$.ajax({
			type:           'post',
			cache:          false,
			url:            './ajax/',
			data:           data
		   });
}
</pre>
<p>And the data is correctly received in PHP's $_POST variable:</p>
<pre class="brush: plain;">
Array
(
    [foo] =&gt; 123
    [bar] =&gt; 456
    [rows] =&gt; Array
        (
            [0] =&gt; Array
                (
                    [column1] =&gt; hello
                    [column2] =&gt; hola
                    [column3] =&gt; bonjour
                )

            [1] =&gt; Array
                (
                    [column1] =&gt; goodbye
                    [column2] =&gt; hasta luego
                    [column3] =&gt; au revoir
                )
        )

    [test1] =&gt; Array
        (
            [test2] =&gt; Array
                (
                    [test3] =&gt; baz
                )
        )
)
</pre>
<h2>Method 2 - JSON string parameter</h2>
<p>This method converts the JS array to a <a href="http://www.json.org/">JSON</a> string, and passes it as a POST or GET parameter, which can be manually decoded back into an array by PHP.  Modern browsers (Firefox 3, IE 8) now have a native JSON object that can be used to stringify JS arrays to JSON strings.  The following example uses the <a href="http://developer.yahoo.com/yui/json/">YUI JSON utility</a> to convert the JS array to a string ( <a href="http://www.json.org/json2.js">json2</a> is another populary lightweight utility for handling JSON).</p>
<pre class="brush: jscript;">
sendAjax = function(){
	var data = {
				  foo:  123,
				  bar:  456,
				  rows: [
						  {
							column1 : 'hello',
							column2 : 'hola',
							column3 : 'bonjour',
						  },
						  {
							column1 : 'goodbye',
							column2 : 'hasta luego',
							column3 : 'au revoir',
						  },
						],
				  test1:{
						  test2: {
								   test3:  'baz'
								 }
						}
				};
	data = YAHOO.lang.JSON.stringify(data);

	$.ajax({
			type:           'post',
			cache:          false,
			url:            './ajax/',
			data:           {myJson:  data}
		   });
}
</pre>
<p>On the PHP side, it's necessary to use <a href="http://us2.php.net/manual/en/function.json-decode.php">json_decode()</a> to convert the JSON $_POST parameter string (named "myJson") to an array:</p>
<pre class="brush: php;">
&lt;?php
$data = json_decode($_POST['myJson'], true);
print_r($data);
</pre>
<p>And the array is good to go:</p>
<pre class="brush: plain;">
Array
(
    [foo] =&gt; 123
    [bar] =&gt; 456
    [rows] =&gt; Array
        (
            [0] =&gt; Array
                (
                    [column1] =&gt; hello
                    [column2] =&gt; hola
                    [column3] =&gt; bonjour
                )

            [1] =&gt; Array
                (
                    [column1] =&gt; goodbye
                    [column2] =&gt; hasta luego
                    [column3] =&gt; au revoir
                )
        )

    [test1] =&gt; Array
        (
            [test2] =&gt; Array
                (
                    [test3] =&gt; baz
                )
        )
)
</pre>
<h2>Method 3 - JSON content-type</h2>
<p>My favorite method is to simply JSON stringify the JS array, and pass it as the AJAX request's body.  This requires that the content-type of the request be changed from the default "application/x-www-form-urlencoded" to "application/json", and that $.ajax()'s <a href="http://docs.jquery.com/Ajax/jQuery.ajax#options">processData</a> parameter be set to false so that the JSON data is not converted into a query string.  Also, the type of request must be POST, as the GET method does not support submitting data in the request body.</p>
<pre class="brush: jscript;">
sendAjax = function(){
	var data = {
				  foo:  123,
				  bar:  456,
				  rows: [
						  {
							column1 : 'hello',
							column2 : 'hola',
							column3 : 'bonjour',
						  },
						  {
							column1 : 'goodbye',
							column2 : 'hasta luego',
							column3 : 'au revoir',
						  },
						],
				  test1:{
						  test2: {
								   test3:  'baz'
								 }
						}
				};
	data = YAHOO.lang.JSON.stringify(data);

	$.ajax({
			type:           'post',
			cache:          false,
			url:            './ajax/',
			data:           data,
			processData:    false,
			contentType:   'application/json'
		   });
}
</pre>
<p>On the PHP side, it's necessary to manually read the JSON string directly from the request body using the <a href="http://php.net/manual/en/wrappers.php.php">php://input</a> stream.  The returned string can then be decoded into an array:</p>
<pre class="brush: php;">
&lt;?php
$data = file_get_contents('php://input');
$data = json_decode($data, true);
print_r($data);
</pre>
<p>Which gives us the array:</p>
<pre class="brush: plain;">
Array
(
    [foo] =&gt; 123
    [bar] =&gt; 456
    [rows] =&gt; Array
        (
            [0] =&gt; Array
                (
                    [column1] =&gt; hello
                    [column2] =&gt; hola
                    [column3] =&gt; bonjour
                )

            [1] =&gt; Array
                (
                    [column1] =&gt; goodbye
                    [column2] =&gt; hasta luego
                    [column3] =&gt; au revoir
                )
        )

    [test1] =&gt; Array
        (
            [test2] =&gt; Array
                (
                    [test3] =&gt; baz
                )
        )
)
</pre>
<p>Hopefully this tutorial has helped you get multidimensional array data passed to your webserver using AJAX.  If you know of another method, please submit it in the comments - thanks!</p>
<img src="http://www.zulius.com/blog/?ak_action=api_record_view&id=656&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.zulius.com/how-to/send-multidimensional-arrays-php-with-jquery-ajax/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>PHP: close browser connection and keep on executing</title>
		<link>http://www.zulius.com/how-to/close-browser-connection-continue-execution/</link>
		<comments>http://www.zulius.com/how-to/close-browser-connection-continue-execution/#comments</comments>
		<pubDate>Fri, 20 Nov 2009 05:31:55 +0000</pubDate>
		<dc:creator>Tim White</dc:creator>
				<category><![CDATA[how-to]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[prototype]]></category>

		<guid isPermaLink="false">http://www.zulius.com/?p=543</guid>
		<description><![CDATA[Sometimes you need to execute a really long process after displaying a web page.  For example, you may need to evaluate the data a user submitted, and that operation may take a lot of time.  And since you're a thoughtful programmer, you don't want make the user stare at a blank page while [...]]]></description>
			<content:encoded><![CDATA[<div class="wp-caption alignleft" style="width: 170px"><img alt="Close the browser's connection" src="/img/blog/php-close-browser-connection/titleImage.jpg" title="Close the browser's connection" width="150" height="110" /><p class="wp-caption-text">Close the browser's connection</p></div>
<p>Sometimes you need to execute a really long process after displaying a web page.  For example, you may need to evaluate the data a user submitted, and that operation may take a lot of time.  And since you're a thoughtful programmer, you don't want make the user stare at a blank page while they wait for the process to finish.</p>
<p>A good solution is to display a confirmation page and then close the browser's connection to the web server.  Closing the browser's connection will cause the browser to stop "spinning" and display a "Done" status.  The user can then feel assured that their part in the matter is over with, and can navigate elsewhere.  In the meantime, your PHP (or whatever language) continues executing on the server.  You could even get fancy with it, and use AJAX to display the script's execution progress to the user on the confirmation page.</p>
<p>The key to doing this are the two HTTP header fields:</p>
<pre style="margin: -5px 0 10px 0">
Connection: close
Content-Length: n (n = size of output in bytes )
</pre>
<p>The <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.10">"Connection: close"</a> header lets the browser know that it should not maintain a persistent connection.  The <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13">"Content-Length: "</a> header tells the browser how much data to expect.  Thus, it's necessary to supply the size of the output (in bytes) using "Content-Length: ".  Then the browser knows when it's downloaded everything and can terminate the connection.</p>
<h2>Example 1 - Basic Usage</h2>
<p>&nbsp;</p>
<pre class="brush: php; first-line: 1; gutter: true;">
&lt;?php
// buffer all upcoming output
ob_start();
echo &quot;Here's my awesome web page&quot;;

// get the size of the output
$size = ob_get_length();

// send headers to tell the browser to close the connection
header(&quot;Content-Length: $size&quot;);
header('Connection: close');

// flush all output
ob_end_flush();
ob_flush();
flush();

/******** background process starts here ********/
</pre>
<h2>Example 2 - embedded PHP with execution progress updates</h2>
<p><a target="_blank" href="/blog/scripts/examples/php/close-browser-connection/example1.php"class="demo">View the demo</a></p>
<p>This basic example executes some arbitrary time consuming code in the background, after the user clicks the submit button.  Notice that after clicking submit, the browser displays the web page and stops downloading.  Also, as a bonus, the execution progress of the script is displayed periodically using Prototype's PeriodicUpdater ajax calls.</p>
<ul>
<li><strong>Lines 02 - 19:</strong>&nbsp;&nbsp;AJAX handler that returns the progress of the background execution to the AJAX calls.  It's basically reading the contents of the progress file to the browser.</li>
<li><strong>Lines 22 - 35:</strong>&nbsp;&nbsp;Creates a uniquely named temporary file to track the background process's execution.  It also buffers all output (Line 034) so that we can calculate the size of all the content.  The size will be sent in the "Content-Length: " header.</li>
<li><strong>Lines 37 - 85:</strong>&nbsp;&nbsp;HTML content.  The javascript in Lines 68 - 80 setup a Prototype PeriodicUpdater.  It checks on the status of the background script every 1 second.</li>
<li><strong>Line 88:</strong>&nbsp;&nbsp;Calculates the size of the buffered output in bytes.</li>
<li><strong>Lines 90 -98:</strong>&nbsp;&nbsp;Sends the 2 necessary headers to the browser, and flushes all buffered output to the browser.</li>
<li><strong>Lines 100 - 115:</strong>&nbsp;&nbsp;This is where the background process should be executed.  In the example, some time consuming code is executed, and it's progress (ie. "Executing step n...") is written to a temporary progress file.</li>
</ul>
<p>Demo source code</p>
<pre class="brush: php; first-line: 1; gutter: true;">
&lt;?php
    // ajax updater handler
    if (isset($_POST['ajax']) &amp;&amp; $_POST['pidFile']){
        // clean input
        $pidFile = preg_replace('/[^\w\d]/', '', $_POST['pidFile']);
        $pidFile = &quot;../cache/$pidFile&quot;;

        if (! file_exists($pidFile)){
            header('HTTP/1.1 500 Internal Server Error');
            exit;
        }
        if(! $progress = file_get_contents($pidFile)){
            header('HTTP/1.1 500 Internal Server Error');
            exit;
        }

        echo nl2br($progress);
        exit;
    }

    // was form submitted?
    if(isset($_POST['submitted'])){
        // create a unique file to track script progress
        $pidFile = tempnam('../cache', '');

        // create the file for writing
        $fh = fopen($pidFile, 'wrx+');
        if (! $fh){
            print &quot;failed to create the file&quot;;
            exit;
        }

        // buffer all upcoming output
        ob_start();
    }
?&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
    &lt;head profile=&quot;http://gmpg.org/xfn/11&quot;&gt;
        &lt;title&gt;Zulius :: Close Browser Connection :: Example #1 Inline PHP&lt;/title&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js&quot;&gt;&lt;/script&gt;
        &lt;style&gt;
            body{ text-align: center; margin: 20px auto; font-family: Arial, Helvetica, sans-serif;}
            div#progress{ min-height: 220px; margin: 10px auto}
        &lt;/style&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h1&gt;
        &lt;?php
        if(isset($_POST['submitted'])){
            echo 'background process started';
        }
        else{
            echo 'click to start background process';
        }
        ?&gt;
        &lt;/h1&gt;
        &lt;div id=&quot;progress&quot;&gt;
        &lt;/div&gt;
        &lt;form method=&quot;POST&quot;&gt;
            &lt;input type=&quot;submit&quot; name=&quot;submitted&quot; value=&quot;Go!&quot;&gt;
        &lt;/form&gt;
    &lt;/body&gt;
    &lt;?php
        if(isset($_POST['submitted'])){
        // show progress in browser
    ?&gt;
        &lt;script type=&quot;text/javascript&quot;&gt;
            updater = new Ajax.PeriodicalUpdater({success: 'progress'}, '&lt;?php echo $_SERVER['REQUEST_URI'] ?&gt;',
                                                { method: 'post',
                                                  frequency: 1,
                                                  decay: 1,
                                                  parameters: {
                                                               ajax: 1,
                                                               pidFile: '&lt;?php echo basename($pidFile) ?&gt;'
                                                             },
                                                  onFailure: function(){ this.stop(); }
                                                });
            setTimeout('updater.stop()', 15000);
        &lt;/script&gt;
    &lt;?php
        }
    ?&gt;
&lt;/html&gt;
&lt;?php
if(isset($_POST['submitted'])){
    // get the size of the output
    $contentLength = ob_get_length();

    // these headers tell the browser to close the connection
    // once all content has been transmitted
    header(&quot;Content-Length: $contentLength&quot;);
    header('Connection: close');

    // flush all output
    ob_end_flush();
    ob_flush();
    flush();

    /******** background process starts here ********/
    for($i=1;$i&lt;=10;$i++){
        if(fwrite($fh, &quot;Executing step $i...\n&quot;) == false){
            print &quot;failed to write to the file: &quot; . error_get_last();
            exit;
        }
        sleep(1);
    }

    fwrite($fh, &quot;Done!\n&quot;);
    sleep(2);

    fclose($fh);

    // delete the progress file
    unlink($pidFile);

}
</pre>
<h2>Example 3 - include embedded PHP file</h2>
<p>If you've separated the HTML from your main script, it's very easy to close the browser connection. Just capture the output from your include command, get the size of the content, and send the headers and content:</p>
<pre class="brush: php; first-line: 1; gutter: true;">
// capture output of include file in buffer
ob_start();
include '/path/to/your/content/file';

// get the size of the output
$contentLength = ob_get_length();

// these headers tell the browser to close the connection
// once all content has been transmitted
header(&quot;Content-Length: $contentLength&quot;);
header('Connection: close');

// flush all output
ob_end_flush();
ob_flush();
flush();

/******** background process code here ********/
</pre>
<h2>Background Process</h2>
<p>If your background process is vital and could take a lot of time, make sure to set these flags at the top of your script:</p</p>
<pre class="brush: php; first-line: 1; gutter: true;">
ignore_user_abort(true);
set_time_limit(0);
</pre>
<p><span style="font-family:  'Lucida Console', 'Courier New', Courier, monospace;">ignore_user_abort(true)</span> will prevent the script from halting if the user happens to push the browser's stop button before the connection is closed.  <span style="font-family:  'Lucida Console', 'Courier New', Courier, monospace;">set_time_limit(0)</span> will prevent your script from being terminated if it surpasses the <span style="font-family:  'Lucida Console', 'Courier New', Courier, monospace;">max_execution_time</span> set in php.ini.</p>
<p>Related post: <a href="/how-to/close-browser-connection-zend-framework">Close browser connection with Zend Framework</a></p>
<img src="http://www.zulius.com/blog/?ak_action=api_record_view&id=543&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.zulius.com/how-to/close-browser-connection-continue-execution/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
