make message not found in codeigniter - codeigniter

I have a problem, I want to make a message in view page that "no data found" in codeigniter:
this is in my controller:
function search_keyword()
{
$this->output->set_header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
$this->output->set_header('Cache-Control: no-cache, no-store, must-revalidate, max-age=0');
$this->output->set_header('Cache-Control: post-check=0, pre-check=0', FALSE);
$this->output->set_header('Pragma: no-cache');
$session_data = $this->session->userdata('logged_in');
$data['Username'] = $session_data['Username'];
$keyword = $this->input->post('keyword');
$data['results'] = $this->model_adminlogin->search($keyword);
$this->load->view('result_view',$data);
}

Try this
function search_keyword()
{
$this->output->set_header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
$this->output->set_header('Cache-Control: no-cache, no-store, must-revalidate, max-age=0');
$this->output->set_header('Cache-Control: post-check=0, pre-check=0', FALSE);
$this->output->set_header('Pragma: no-cache');
$session_data = $this->session->userdata('logged_in');
$userName = $session_data['Username'];
$keyword = $this->input->post('keyword');
$data['results'] = $this->model_adminlogin->search($keyword);
if(isset($data['results'])){
$this->load->view('result_view',$data);
}else {
echo "<h1>Data not found </h1>"
}
}

Your Model
function search($data)
{
//your code
// if found data return false otherwise true with data
if($result->num_row()>0)
{
return ['status'=>true,'data'=>$result->result()];
}
else{
return ['status'=>false];
}
}
Your Controller
function search_keyword()
{
$this->output->set_header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
$this->output->set_header('Cache-Control: no-cache, no-store, must-revalidate, max-age=0');
$this->output->set_header('Cache-Control: post-check=0, pre-check=0', FALSE);
$this->output->set_header('Pragma: no-cache');
$session_data = $this->session->userdata('logged_in');
$data['Username'] = $session_data['Username'];
$keyword = $this->input->post('keyword');
$result = $this->model_adminlogin->search($keyword);
if($result['status'])
$data['results'] = $result['data'];
else
$data['results'] = [];
$this->load->view('result_view',$data);
}
On your View
if(!empty($results))
{
//list your result
}
else{
echo 'No data Found';
}

Related

Call to undefined method Symfony\Component\HttpFoundation\StreamedResponse::header()

Can't Download File as CSV
I'm trying to export some data as CSV & every time i try to export data i got this error - Call to undefined method Symfony\Component\HttpFoundation\StreamedResponse::header()
I have tried different possible ways but they aren't working
My Function (Controller File)
public function exportd(Request $request)
{
$fileName = 'data.csv';
$data = json_decode($request->data);
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=$fileName",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);
$columns = array('Name', 'Gender', 'experrience', 'location', 'Pref Location', 'Salary'
...
);
$callback = function() use($data, $columns) {
$file = fopen('php://output', 'w');
fputcsv($file, $columns);
foreach ($data as $da) {
$row['Name'] = $da->name;
$row['Gender'] = $da->gender;
$row['experrience'] = $task->experrience;
$row['Pref Location'] = $task->pref_loc;
$row['Salary'] = $task->salary;
...
fputcsv($file, array($row['Name'], $row['Gender'],$row['experrience'], $row['location'], $row['Pref Location'], $row['Salary']
...
));
}
fclose($file);
};
return Response()->stream($callback, 200, $headers);
}
My Middleware (AuthCheck)
public function handle(Request $request, Closure $next)
{
if(!session()->has('LoggedUser') && ($request->path() !='auth/login' && $request->path() !='auth/register' )){
return redirect('auth/login')->with('fail','You must be logged in');
}
if(session()->has('LoggedUser') && ($request->path() == 'auth/login' || $request->path() == 'auth/register' ) ){
return back();
}
return $next($request)->header('Cache-Control','no-cache, no-store, max-age=0, must-revalidate')
->header('Pragma','no-cache')
->header('Expires','0');
}
$next($request) is an instance of Symfony\Component\HttpFoundation\StreamedResponse in your scenario.
StreamedResponse does not support ->header(...).
If you want to preserve your ->header(...) call, you must verify that the response is an instance of Illuminate\Http\Response
public function handle(Request $request, Closure $next)
{
if(!session()->has('LoggedUser') && ($request->path() !='auth/login' && $request->path() !='auth/register' )){
return redirect('auth/login')->with('fail','You must be logged in');
}
if(session()->has('LoggedUser') && ($request->path() == 'auth/login' || $request->path() == 'auth/register' ) ){
return back();
}
$response = $next($request);
if($response instanceof \Illuminate\Http\Response) {
return $response->header('Cache-Control','no-cache, no-store, max-age=0, must-revalidate')
->header('Pragma','no-cache')
->header('Expires','0');
}
return $response;
}

How to export or download csv file using ajax?

I have a problem with my code downloading csv file.
I can get the data but i can't download the csv file.
Here is my ajax code:
// Export
$('#export_csv').click(function(){
var checkbox = $('.checkbox:checked');
if(checkbox.length > 0)
{
var checkbox_value = [];
$(checkbox).each(function(){
checkbox_value.push($(this).val());
});
$.ajax({
url:"csv_action.php",
method:"POST",
data:{action:'export_csv'},
dataType:'json',
success:function(data)
{
$("#select_all").prop('checked', false);
$('#message').html(data);
setTimeout(function(){
$('#message').html('');
}, 5000);
}
});
}
else
{
alert("Please select at least one records");
}
});
Here is my php file code:
The output for this code is the data that i fetch from the database and the data of the student i selected from data table. I tried several methods changing the data type is response and function(success)
// Export CSV
if($_POST["action"] == 'export_csv')
{
$filename = 'reports.csv';
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
for($count = 0; $count < count($_POST["checkbox_value"]); $count++)
{
$object->query = "
SELECT * FROM tbl_student WHERE
s_scholar_stat = ''
";
$object->execute();
$result = $object->get_result();
$content = array();
$title = array("Student ID", "First Name", "Middle Initial", "Last Name", "Date of Birth", "Account Status");
foreach ($result as $rows) {
$row = array();
$row[] = $rows["ss_id"];
$row[] = $rows["sfname"];
$row[] = $rows["smname"];
$row[] = $rows["slname"];
$row[] = $rows["sdbirth"];
$row[] = $rows["s_account_status"];
$content[] = $row;
}
}
$output = fopen('php://output', 'w');
fputcsv($output, $title);
foreach ($content as $con) {
fputcsv($output, $con);
}
fclose($output);
echo '<div class="alert alert-success">Selected Student Data Exported in CSV
Successfully</div>';
}

I send variables to export.php through Ajax, but it is not received in export page

I send variables to export.php through Ajax, but it is not received in export page. it shows
Undefined index: name in D:\xampp\htdocs\Vergands - Admin1\export.php on line 2
customer.php
<script type="text/javascript">
$(document).ready(function(){
$(".export_button").click(function(){
var tableName = $("#tableName").val();
$.ajax({
method:"post",
url:"export.php",
data:{name:tableName}
});
});
});
</script>
export.php /*its working fine when i run export.php alone and excel file getting downloaded( using
this function export('customer_profile');
customer_profile is table name
*/
<?php
$tableName_final = $_POST["name"];
function export($tableName_final){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "admin_vergands";
//mysql and db connection
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) { //error check
die("Connection failed: " . $con->connect_error);
}
else
{
echo "connection failed";
}
$DB_TBLName = $tableName;
$filename = "excelfilename"; //your_file_name
$file_ending = "xls"; //file_extention
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
$sep = "\t";
$sql="SELECT * FROM $DB_TBLName";
$resultt = $con->query($sql);
while ($property = mysqli_fetch_field($resultt)) { //fetch table field name
echo $property->name."\t";
}
print("\n");
while($row = mysqli_fetch_row($resultt)) //fetch_table_data
{
$schema_insert = "";
for($j=0; $j< mysqli_num_fields($resultt);$j++)
{
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
}
export($tableName_final);
?>

POSTing Cross domain AJAX

Im trying to send a POST request to an external website, from what iv read so far its not possible due to same origin policy. But i'v also read a proxy can bypass this.
Is this possible AT ALL if I don't have access to the external website? I can't seem to clarify this.
I just want to send an AJAX POST and get the response like when i use Chrome's Advanced REST Client.
Set your header with
Access-Control-Allow-Origin: http://foo.example
To any other noobies in the problem
Slightly modified this:
https://github.com/eslachance/php-transparent-proxy
Now accepts a posting url:
<?php
if(!function_exists('apache_request_headers')) {
// Function is from: http://www.electrictoolbox.com/php-get-headers-sent-from-browser/
function apache_request_headers() {
$headers = array();
foreach($_SERVER as $key => $value) {
if(substr($key, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
}
}
return $headers;
}
}
// Figure out requester's IP to shipt it to X-Forwarded-For
$ip = '';
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
//echo "HTTP_CLIENT_IP: ".$ip;
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
//echo "HTTP_X_FORWARDED_FOR: ".$ip;
} else {
$ip = $_SERVER['REMOTE_ADDR'];
//echo "REMOTE_ADDR: ".$ip;
}
//
preg_match('#^(?:http://)?([^/]+)#i', $_SERVER['HTTP_REFERER'], $matches);
$host = $matches[1];
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
$domainName = "{$matches[0]}";
//
//writelog($_POST);
$method = $_SERVER['REQUEST_METHOD'];
$desturl;
// parse the given URL
if($method == "POST") {
$desturl = $_POST['url'];
unset($_POST['url']);
}
else if ($method == "GET") {
$desturl = $_GET['url'];
unset($_GET['url']);
}
$response = proxy_request($desturl, ($method == "GET" ? $_GET : $_POST), $method);
$headerArray = explode("\r\n", $response[header]);
foreach($headerArray as $headerLine) {
header($headerLine);
}
echo $response[content];
function proxy_request($url, $data, $method) {
// Based on post_request from http://www.jonasjohn.de/snippets/php/post-request.htm
global $ip;
// Convert the data array into URL Parameters like a=b&foo=bar etc.
//$data = http_build_query($data);
$data = json_encode($data, JSON_FORCE_OBJECT);
writelog($data);
$datalength = strlen($data);
$url = parse_url($url);
//echo $url;
if ($url['scheme'] != 'http') {
die('Error: Only HTTP request are supported !');
}
// extract host and path:
$host = $url['host'];
$path = $url['path'];
// open a socket connection on port 80 - timeout: 30 sec
$fp = fsockopen($host, 80, $errno, $errstr, 30);
if ($fp){
$out="";
if($method == "POST") {
$out ="POST $path HTTP/1.1\r\n";
} else {
$out ="GET $path?$data HTTP/1.1\r\n";
}
//Todo Get headers and forward them...
$requestHeaders = apache_request_headers();
while ((list($header, $value) = each($requestHeaders))) {
/*if($header !== "Connection" && $header !== "Host" && $header !== "Content-Length"
&& $header !== "Content-Type"
&& $header !== "Origin"
&& $header !== "Referer"
&& $header !== "X-Requested-With"
&& $header !== "Accept-Encoding"
) {
// $out.= "$header: $value\r\n";
writelog("$header: $value\r\n");
}*/
if($header == "Cookie" && $header == "User-Agent" ) {
$out.= "$header: $value\r\n";
//writelog("$header: $value\r\n");
}
}
$out.= "Host: $host\r\n";
$out.= "Content-Type: application/json; charset=UTF-8\r\n";
$out.= "Content-Length: $datalength\r\n";
$out.= "Connection: Close\r\n\r\n";
$out.= $data;
fwrite($fp, $out);
$result = '';
while(!feof($fp)) {
// receive the results of the request
$result .= fgets($fp, 128);
}
}
else {
return array(
'status' => 'err',
'error' => "$errstr ($errno)"
);
}
// close the socket connection:
fclose($fp);
// split the result header from the content
$result = explode("\r\n\r\n", $result, 2);
$header = isset($result[0]) ? $result[0] : '';
$content = isset($result[1]) ? $result[1] : '';
// return as structured array:
return array(
'status' => 'ok',
'header' => $header,
'content' => $content
);
}
?>

Export the mysql data (data in other language or having some special character ) as XLS file in php 1

I am exporting a file in *.xls format in PHP. After export, file some special charaters are in the file do you have any ideas why? My library is like this type of question mark
<?php
class Exportclass {
private $filename;
private $headerArray;
private $bodyArray;
private $rowNo = 0;
function ExportXLS($filename) {
$this->filename = $filename;
}
public function addHeader($header) {
if(is_array($header)) {
$this->headerArray[] = $header;
} else {
$this->headerArray[][0] = $header;
}
}
public function addRow($row) {
if(is_array($row)) {
if(is_array($row[0])) {
foreach($row as $key=>$array) {
$this->bodyArray[] = $array;
}
} else {
$this->bodyArray[] = $row;
}
} else {
$this->bodyArray[][0] = $row;
}
}
public function returnSheet() {
return $this->buildXLS();
}
public function sendFile() {
$xls = $this->buildXLS();
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=".$this->filename);
header("Content-Transfer-Encoding:binary");
echo $xls;
exit;
}
private function buildXLS() {
$xls = pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
if(is_array($this->headerArray)) {
$xls .= $this->build($this->headerArray);
}
if(is_array($this->bodyArray)) {
$xls .= $this->build($this->bodyArray);
}
$xls .= pack("ss", 0x0A, 0x00);
return $xls;
}
private function build($array) {
$build = '';
foreach($array as $key=>$row) {
$colNo = 0;
foreach($row as $key2=>$field) {
if(is_numeric($field)) {
$build .= $this->numFormat($this->rowNo, $colNo, $field);
} else {
$build .= $this->textFormat($this->rowNo, $colNo, $field);
}
$colNo++;
}
$this->rowNo++;
}
return $build;
}
private function textFormat($row, $col, $data) {
$data = utf8_decode($data);
$length = strlen($data);
$field = pack("ssssss", 0x204, 8 + $length, $row, $col, 0x0, $length);
$field .= $data; return $field;
}
private function numFormat($row, $col, $data) {
$field = pack("sssss", 0x203, 14, $row, $col, 0x0);
$field .= pack("d", $data);
return $field;
}
}
?>
use PHPExcel http://phpexcel.codeplex.com/ its the best possible solution to export excel files in PHP.

Resources