PHP JQuery – Trick Ajax external site (cURL)

Here is a way to call through Ajax an external link
we use curl in a PHP function to read external url and print result in a Dialog Box

example.html

<!doctype html>
 <html lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <title>PHP JQuery - Trick Ajax external site</title>

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/ui-lightness/jquery-ui.css" type="text/css" media="all" />

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
  
<script type="text/javascript">
function getWrapper() {
  var request = $.ajax({
    url: "wrapper.php",
    data: {
     
    },
    dataType:   "html", 
    beforeSend: function() {
   
    },              
    success: function(data){
 
      var tag = $("<div></div>"); //This tag will the hold the dialog content.
         
             
      tag.html(data).dialog({
                            modal: true, 
                            title: 'Ajax', 
                            width: 'auto',
                            show: 'blind',
                            hide: 'blind'
                        }).dialog('open');                  
    },
    complete:   function() {
    
    },
    error: function() {
     alert('Error');
    },          
  });
}
  
 
 $(document).ready(function() {
   $('#cmd').click( function() {
     getWrapper();     
   });
 });
</script>
</head>
  
<body>
<button id="cmd" name="cmd" >Open</button>
</body>

wrapper.php

$url = "http://www.google.com";
echo readHTML($url);

function readHTML($url) { 
    if(!function_exists("curl_init")) return "cURL extension is not installed";
    if (trim($url) == "") die("@ERROR@");
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);                         
    curl_setopt($curl, CURLOPT_USERPWD, 'username:password');
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);                    
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);                          
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);                           
    $response = curl_exec($curl);                                          
    $resultStatus = curl_getinfo($curl);                                   
    if($resultStatus['http_code'] == 200) {
        // All Ok
    } else {
        echo 'Call Failed '.print_r($resultStatus);                         
    }
    $curl = null;
    return utf8_encode($response);      
} //* readHTML */
Posted in JQuery, PHP | Tagged | 2 Comments

PHP transform array to an HTML table

PHP transform array to an HTML table

//---Show an array content (1st level) in a HTML table format
// $option = array(
//		'order' => '{field}',	- list fields on which order and show
//		'options' => array(
//			'field_color_row' => 'red' / '#FFFFFF'	// row color
//			'cellpadding' => '5' / '#FFFFFF'		// cellpadding table
//			'cellspacing' => '0' / '#FFFFFF'		// ininfluente con bordercollapse
//			'classtable' => 'nameClassTable' 		// class table
//		),
//		'{field}' => array(
//			'header' => '{Name Field 1}'				//Header column
//			'type' => 'date' / 'integer', 'income'		//type data
//			'align' =>	'left' / 'center' / 'right'		//align
//			'class' => 'nameClass'					//column class <td>
//			'unit' => 'kg'								//unit measure
//		)
// $id - id table to assign
function showTable($array, $options = array(), $id = ''){
	if(is_array($array))  {
		//---reorder $array defined in $options['order']
		if(isset($options['order'])) {
			
			$array1 = array();
			$array_order = $options['order'];
			foreach ($array as $key => $item){
				$array2 = array();
				foreach ($array_order as $field){
					$array2[$field] = $item[$field];
				}
				$array1[$key] = $array2;
			}
			
			$array = $array1;
		}
		
		//---options field on which set color (if not defined alternate color)
		$field_color_row = "";
		if(isset($options['options']['field_color_row'])) {
			$field_color_row = $options['options']['field_color_row'];
		}

		//---options cellpadding
		$cellpadding = "0";
		if(isset($options['options']['cellpadding'])) {
			$cellpadding = $options['options']['cellpadding'];
		}
		//---options cellspacing
		$cellspacing = "0";
		if(isset($options['options']['cellspacing'])) {
			$cellspacing = $options['options']['cellspacing'];
		}
		//---options cellpadding
		$classtable = "";
		if(isset($options['options']['classtable'])) {
			$classtable = $options['options']['classtable'];
		}
								
		?>
        <table <?= $id ? 'id="'.$id.'"' : ''; ?> <?= $classtable ? 'class="'.$classtable.'"' : '';?>" border="1" cellpadding="<?= $cellpadding;?>" cellspacing="<?= $cellspacing;?>" style="border-collapse:collapse">
        
        <?
		$n = 0;
		$prev = "";
		$flag_header = true;
		foreach ($array as $key => $item){

			if($field_color_row) {
				if($item[$field_color_row] != $prev) {
					$prev =	$item[$field_color_row];
					$n++;
				}	
			} else {
				$n++;
			}
			
			$class = "odd";
			if ($n % 2 == 0){
				$class = "even";
			}
				
			
			if($flag_header) {
				?>
                <thead>
                <tr class="head">
                <?
				foreach(array_keys($item) as $campo) { 
					if(isset($options[$campo]['header']) && $options[$campo]['header']) {
						$campo = $options[$campo]['header'];
					}
				
				?>
					<th><?= $campo ?></th>
                <?
				}
				?>
                </tr>
                </thead>
                <tbody>
                <?
				$flag_header = false;
			}//End if($flag_header) {
			?>
            	<tr class="<?= $class; ?>">
            <?
			if(is_array($item)) {
			foreach($item as $key => $el) { 
				$align = 'left';
				if(isset($options[$key]['type']) && $options[$key]['type']) {
					//---tipo formato
					switch($options[$key]['type']) {
//						case 'checkbox':
//							$align = 'center';
//							$el = '<input name="chk" type="checkbox" ' . ($el ? 'checked="checked"' : '') . ' value="' . $el . '" />';
//							break;
						case 'date':
							$el = RigiraData(EpuraData($el));
							break;
						case 'integer':
							$align = 'right';
							$el = frwt_printNumber($el, $dec = 0);
							break;
                                                case 'currency':
						case 'income':
							$align = 'right';
							$el = frwt_printNumber($el, $dec = 2);
							break;	
					}

					//echo "el=".$el."<br />";
					//die("TEST");
				}

				if(isset($options[$key]['unit']) && $options[$key]['unit']) {
					//---unit measure
					$unit = $options[$key]['unit'];
					$el .= " " . $unit;
				}

				if(isset($options[$key]['align']) && $options[$key]['align']) {
					//---align
					$align = $options[$key]['align'];
				}
				
				//---class
				$td_class = "";
				if(isset($options[$key]['class']) && $options[$key]['class']) {
					$td_class = $options[$key]['class'];
				}
				?>
					<td <?= $td_class ? 'class="'.$td_class.'"' : ''; ?> valign="top" align="<?= $align;?>"><?= $el ?></td>
                <?
			}//End foreach($item as $el) {
			}
			?>
            	</tr>
			<?
			
			
		}//End foreach ($array as $key => $item){
		?>
        </tbody>
        </table>
        <?
	}
}

Example with MySQL

$SQL = "SELECT name, surname, city FROM users");
$res = mysql_query($SQL);
while($item = mysql_fetch_assoc($res)) {
  $array[] = $item;
);

showTable($array);

Results

name surname city
Kobe Bryant Los Angeles
Mike Smith New York
Mark Anthony Chicago
Dave Sullivan San Francisco
Posted in PHP | Tagged , , | Leave a comment

JQuery click + shift button for selecting group of checkboxes as desktop application

Click start checkox and then click + shif button on end checkbox

<!doctype html>
 <html lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <title>JQuery checkbox click + shift</title>
<style>
 table tr td input.selected {
 outline-color:#6CF;
 outline-style:solid;
 outline-width:thin
}
 </style>
 <script type="text/javascript" src="jquery-1.7.1.min.js" charset="utf-8"></script>
 <script type="text/javascript" src="jquery-ui-1.8.17.custom.min.js" charset="utf-8"></script>

<script type="text/javascript">
 $(document).ready(function() {
 TABLE.selectable('#contacts');
 });

var TABLE = {};

TABLE.selectable = function(table) {
    var $tables = $(table);

    $tables.each(function () {
        var _table = $(this);
/*
//        _table
//            .find('thead tr th:nth-child(1)')
//            .before($('<th><input id="checker" type="checkbox" value="Select" /></th>'));
//        _table
//            .find('tbody tr td:nth-child(1)')
//            .before($('<td><input type="checkbox" value="Select" /></td>'));
*/
        var chkSelector = 'tr td:nth-child(1) :checkbox';
        //--- this one if you put in class for each checkbox class="checbox"
        //var chkSelector = '.checkbox';

        $('#checker').click(function() {
            _table.find(chkSelector)
                .prop('checked', $(this).prop('checked'));        
        });

        _table.find(chkSelector).click(function(e) {
            var $table = $(this).parents('table');
            var lastRow = $table.data('lastRow');
            var lastIndex = $table.data('lastIndex');

            var thisRow = $(this).parents('tr').index();

            //---THIS INDEX
            var str = $(this).attr('index');
            //var pos = str.lastIndexOf('_');
            var thisIndex = parseInt(str);
            //str = str.substring(0,pos+1) + str.substring(pos+1)

            var checked = $(this).prop('checked');

            _table.find(chkSelector).removeClass('selected');
            $(this).addClass('selected');

            //if(lastRow !== undefined && e.shiftKey) {
            if(lastIndex !== null && e.shiftKey) {                
                var numChecked = 0;
                //var start = lastRow < thisRow ? lastRow : thisRow;
                //var end = lastRow > thisRow ? lastRow : thisRow;

                var start = lastIndex < thisIndex ? lastIndex : thisIndex;
                var end = lastIndex > thisIndex ? lastIndex : thisIndex;

                $table
                    .find(chkSelector)
                    .slice(start, end + 1)
                    .prop('checked', checked);

//                var $list =    $table
//                    .find(chkSelector);
//                alert($list.length);
//                alert($list.slice(start, end + 1).prop('checked', checked).length);
            }
            $table.data('lastRow', thisRow);
            $table.data('lastIndex', thisIndex);

        });
    });
}
</script>
</head>

<body>
  <table id="contacts" style="border-collapse:collapse" border="1" cellpadding="5" align="center">
    <thead>
      <tr>
        <th><input id="checker" type="checkbox" value="1" /></th>
        <th>Contact</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><input type="checkbox" value="1" index="0" /></td>
        <td>Mike Brown</td>
      </tr>
      <tr>
        <td><input type="checkbox" value="1" index="1" /></td>
        <td>Chris Mullin</td>
      </tr>
      <tr>
        <td><input type="checkbox" value="1" index="2" /></td>
        <td>Scottie Pippen</td>
      </tr>
      <tr>
        <td><input type="checkbox" value="1" index="3" /></td>
        <td>Micheal Jordan</td>
      </tr>
      <tr>
        <td><input type="checkbox" value="1" index="4" /></td>
        <td>Grant Hill</td>
      </tr>
      <tr>
        <td><input type="checkbox" value="1" index="5" /></td>
        <td>Alonso Mourning</td>
      </tr>  
      <tr>
        <td><input type="checkbox" value="1" index="6" /></td>
        <td>David Rivers</td>
      </tr>  
      <tr>
        <td><input type="checkbox" value="1" index="7" /></td>
        <td>Carlton Myers</td>
      </tr>                                          
    </tbody>
  </table>
</body>
</html>
Posted in checkbox, JQuery | Tagged , , , | 2 Comments

PHP Excel – array to excel

Passing an Array ($_SESSION[‘excel_report’])

It creates a PhpExcel

Notes:
You should put the PHP Excel Library in “/utils/PHPExcel” folder otherwise you should change below

<?
session_start();
ob_start();

//----------------------------------------------------
$data = array();

if(isset($_SESSION['excel_report']) && $_SESSION['excel_report']) {
  $data = $_SESSION['excel_report'];
} else {
  die();
}

//$titolo = "TVO - " . date('Y-m-d');
$titolo = $_SESSION['excel_report_titolo'];
if(isset($_POST['titolo'])) {
  $titolo = $_POST['titolo'];
}

//--- sheet title
$titolo_sheet = $_SESSION['excel_report_titolo_foglio'];
/** Error reporting */
//error_reporting(E_ALL);

/** Include path **/
//ini_set('include_path', ini_get('include_path').';'.$_SERVER['DOCUMENT_ROOT'] . '/utils/PHPExcel/Classes/');

/** PHPExcel */
include $_SERVER['DOCUMENT_ROOT'] . '/utils/PHPExcel/Classes/' . 'PHPExcel.php';

/** PHPExcel_Writer_Excel2007 */
include $_SERVER['DOCUMENT_ROOT'] . '/utils/PHPExcel/Classes/' . 'PHPExcel/Writer/Excel2007.php';

// Create new PHPExcel object
//echo date('H:i:s') . " Create new PHPExcel object\n";
$objPHPExcel = new PHPExcel();

//--- Set properties
//echo date('H:i:s') . " Set properties\n";
$objPHPExcel->getProperties()->setCreator("Sesamo");
$objPHPExcel->getProperties()->setLastModifiedBy("Sesamo");
//$objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
//$objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
//$objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");

// Add some data
//echo date('H:i:s') . " Add some data\n";
$objPHPExcel->setActiveSheetIndex(0);
$flag_array_intestazione = false;

//scrivo PADRI
$row = 2;
$column = 0;

//$start_row = count($data) + 3 + 1;
$start_row = 3 + 1;
//$row = 1;
$row = $start_row;
$column = 0;
$flag_array_intestazione = true;
foreach($data as $key => $item) {

  foreach($item as $key1 => $item1) {
    //$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($column, $row, $item1);
    switch($key1) {
      case 'class':
        continue;
        break;
      case 'Code': //---force to string
        $objPHPExcel->getActiveSheet()->getCellByColumnAndRow($column, $row)->setValueExplicit($item1, PHPExcel_Cell_DataType::TYPE_STRING);
        break;
      case 'Income':
      case 'Capacity':
        //$item1 = str_replace(",",".",$item1);
        $item1 = currency2float($item1);
        // $item1 = str_replace(".","",$item1);
        // $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($column, $row, $item1);
        $objPHPExcel->getActiveSheet()->getCellByColumnAndRow($column, $row)->setValueExplicit($item1, PHPExcel_Cell_DataType::TYPE_NUMERIC);
        break;
      default:
       $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($column, $row, $item1);
    }

    switch($key1) {
      case 'Price':
        $char = chr(ord("A") + $column);
        $range = $char . $row;
        $objPHPExcel->getActiveSheet()->getStyle($range)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        break;
      case 'Income':
        $char = chr(ord("A") + $column);
        $range = $char . $row;
        $objPHPExcel->getActiveSheet()->getStyle($range)->getNumberFormat()->setFormatCode('#,##0.00');
        $objPHPExcel->getActiveSheet()->getStyle($range)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        break;
      case 'Capacity':
        $char = chr(ord("A") + $column);
        $range = $char . $row;
        $objPHPExcel->getActiveSheet()->getStyle($range)->getNumberFormat()->setFormatCode('#,##');
        $objPHPExcel->getActiveSheet()->getStyle($range)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
        break;
      default:
    }

    if($flag_array_intestazione) $array_intestazione[] = $key1;
    $column++;
  }

  $argb = "FFFFFFFF";
  if ($row % 2 == 1){
    $argb = "FFE0E0E0"; //FFA0A0A0
  }
  //---row---colored
  $styleArray = array(
    'fill' => array(
      'type' => PHPExcel_Style_Fill::FILL_SOLID,
      'startcolor' => array(
        'argb' => $argb, //'FFA0A0A0'
      ),
      // 'endcolor' => array(
        // 'argb' => 'FFFFFFFF',
      // ),
    ),
  );
  $char = chr(ord("A") + $column - 1);
  $objPHPExcel->getActiveSheet()->getStyle('A'. $row .':' . $char . $row)->applyFromArray($styleArray);

  if($flag_array_intestazione) $flag_array_intestazione = false;
  $column = 0;
  $row++;
}

$end_row = $row - 1;

//---ROW HEADER
//$row = 1;
$header_row = 3;

$row = $header_row;
$column = 0;
foreach($array_intestazione as $key) {
  switch($key) {
    case 'class':
      continue;
      break;
    default:
      $objPHPExcel->getActiveSheet()->getCellByColumnAndRow($column, $row)->setValueExplicit($key, PHPExcel_Cell_DataType::TYPE_STRING);
      $column++;
  }
}

$styleArray = array(
  'font' => array(
    'bold' => true,
  ),
  // 'alignment' => array(
  // 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
  // ),
  // 'borders' => array(
  // 'top' => array(
  // 'style' => PHPExcel_Style_Border::BORDER_THIN,
  // ),
  // ),
  // 'fill' => array(
  // 'type' => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR,
  // 'rotation' => 90,
  // 'startcolor' => array(
  // 'argb' => 'FFA0A0A0',
  // ),
  // 'endcolor' => array(
  // 'argb' => 'FFFFFFFF',
  // ),
  // ),
);

//echo "count(array_intestazione)=" .(count($array_intestazione) - 1) ."<br />";
$char = chr(ord("A") + count($array_intestazione) - 1);
//echo "char=".$char."<br />";
//die();

//---Cell Merge
$objPHPExcel->getActiveSheet()->mergeCells('A1:' . $char . '1');
//$objPHPExcel->getActiveSheet()->mergeCells('A'. ($start_row - 1).':' . $char . ($start_row-1));

//---TITLES
$objPHPExcel->getActiveSheet()->setCellValue('A1', $titolo); //'LISTA'
//$objPHPExcel->getActiveSheet()->setCellValue('A'.($start_row - 1), 'COMMESSE');
//---STYLE
$objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
//$objPHPExcel->getActiveSheet()->getStyle('A'.($start_row - 1))->applyFromArray($styleArray);

$styleArray = array(
  'font' => array(
    'bold' => true,
  ),
  'alignment' => array(
    'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
  ),
  // 'borders' => array(
  // 'top' => array(
  // 'style' => PHPExcel_Style_Border::BORDER_THIN,
  // ),
  // ),
  'fill' => array(
    'type' => PHPExcel_Style_Fill::FILL_SOLID,
    // 'rotation' => 90,
    'startcolor' => array(
     'argb' => 'FFA0A0A0',
    ),
    // 'endcolor' => array(
    // 'argb' => 'FFFFFFFF',
    // ),
  ),
);
$objPHPExcel->getActiveSheet()->getStyle('A'. $header_row .':' . $char . $header_row)->applyFromArray($styleArray);

foreach($array_intestazione as $key => $el) {
  //---AUTOSIZE COLUMN ---
  $char = chr(ord("A") + $key);
  $objPHPExcel->getActiveSheet()->getColumnDimension($char)->setAutoSize(true);
}

// Set cell B8
//$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 8, 'Some value');

// Get cell B8
//$objPHPExcel->getActiveSheet()->getCellByColumnAndRow(1, 8)->getValue();

// 4.6.7. Explicitly set a cell's datatype
//You can set a cell's datatype explicitly by using the cell's setValueExplicit method, or the setCellValueExplicit method of a worksheet. Here's an example:
//$objPHPExcel->getActiveSheet()->getCell('A1')->setValueExplicit('25', PHPExcel_Cell_DataType::TYPE_NUMERIC);

//$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Hello');
//$objPHPExcel->getActiveSheet()->SetCellValue('B2', 'world!');
//$objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Hello');
//$objPHPExcel->getActiveSheet()->SetCellValue('D2', 'world!');

//--- Rename sheet
//echo date('H:i:s') . " Rename sheet\n";
$objPHPExcel->getActiveSheet()->setTitle($titolo_sheet); //'Commesse'

//---Borders
$styleArray = array(
  'borders' => array(
    'allborders' => array(
      'style' => PHPExcel_Style_Border::BORDER_THIN,
      //'color' => array('argb' => 'FFFF0000'),
    ),
  ),
);
$objPHPExcel->getActiveSheet()->getStyle('A'. $header_row .':' . $char . $end_row)->applyFromArray($styleArray);
// Save Excel 2007 file
//echo date('H:i:s') . " Write to Excel2007 format\n";
//$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
//$objWriter->save(str_replace('.php', '.xlsx', __FILE__));

// Echo done
//echo date('H:i:s') . " Done writing file.\r\n";

// Redirect output to a client's web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $titolo . '.xls"');
header('Cache-Control: max-age=0');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

/*
// Redirect output to a client's web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
header('Cache-Control: max-age=0');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
*/

//End, go with header.
ob_end_flush();

exit;
?>
Posted in PHP, Php Excel | Tagged , , | 1 Comment