Undefined offset:0 at HandleExceptions->handleError - ajax

I have a page which is used to search the users. If I searched an existing user, the page will redirect to my wanted page. If the user is not existing, a message must be shown. But for me the message is not showing. I know may be this is a simple error, but it's not working for me. I am using Laravel 5.8.
Error is:
Undefined offset: 0
in ClientsController.php (line 344)
at HandleExceptions->handleError.
Here is my controller:
public function getMerchantDetails() {
$user = $_GET['user'];
$mid = $_GET['mid'];
$activity = "User $user has searched this merchant";
//This is for Activity Log Capturing. Added user variable
DB::insert("INSERT INTO activitylog (mid,activity) values ('$mid','$activity')");
//Activity ends here
$mobile = $_GET['mobile'];
$email = $_GET['email'];
$m = '';
if ($mobile != '') {
$m = " AND primary_number = '" . $mobile . "' ";
}
$e = '';
if ($email != '') {
$e = " AND email = '" . $email . "' ";
}
$i = '';
if ($mid != '') {
$i = " AND mid = '" . $mid . "' ";
}
if ($m == '' && $e == '' && $i == '') {
// print_r($m);
// die();
return response()->json(array('data' => ''), 200);
} else {
$res = DB::select(DB::raw("SELECT * FROM clients WHERE 1=1 " . $m . $e . $i . " LIMIT 1"));
if (!$res) {
//$res_config = DB::select( DB::raw("SELECT * FROM configuration WHERE code = 'PERL_SEARCH_MERCHANT'") );
$perl_path = DB::select(DB::raw("SELECT * FROM configuration WHERE code = 'PERL_PATH'"));
$perl_output = exec($perl_path[0]->description . ' -merchant_id ' . $mid . ' -mobile ' . $mobile . ' -email ' . $email);
$r = json_decode($perl_output, true);
if ($r['status'] == 'success') {
if ($r['id'] != '') {
$res = DB::select(DB::raw("SELECT * FROM clients WHERE id = " . $r['id']));
} else {
$res[0]['id'] = '';
}
}
}
return response()->json(array('data' => $res[0]), 200); (line 344)
}
}
My Ajax code:
$.ajax({
"url": '{!! route('clients.fetchMerchantDetails') !!}',
async: true,
type: "GET",
data: {
mobile: mobile,
email: email,
mid: mid,
user:userid
},
success: function (response) {
var data = response.data
if(data.id!=''){
clientEditUrl = clientEditUrl.replace(':id', data.id);
window.location = clientEditUrl;
}else{
$('.searchOutputDiv').html('<h3>No merchant found!</h3>');
}
}
});

Related

DataBase Schema File (.sql file ) Download with laravel

Schenario :
1) suppose that i have a database called myDataBase
2) Assume that myDataBase have some tables like A,B,C,D
3) i have to download the schema of the table A,B from the database with name myDataBase
Hope you have done the migration of all the table of your project . If you are using a xampp server then goto http://localhost/phpmyadmin and select your database and then goto export tab on the top tab bar and simply export with go button
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlUserName = "root";
$mysqlPassword = "";
$mysqlHostName = "localhost";
$DbName = "ukkoteknik";
$backup_name = "mybackup.sql";
$tables = array("admin", "sample");
Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName, $tables, $backup_name=false );
function Export_Database($host,$user,$pass,$name, $tables=false, $backup_name=false )
{
$mysqli = new mysqli($host,$user,$pass,$name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
if($tables !== false)
{
$target_tables = array_intersect( $target_tables, $tables);
}
foreach($target_tables as $table)
{
$result = $mysqli->query('SELECT * FROM '.$table);
$fields_amount = $result->field_count;
$rows_num=$mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE '.$table);
$TableMLine = $res->fetch_row();
$content = (!isset($content) ? '' : $content) . "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0)
{
while($row = $result->fetch_row())
{ //when started (and every after 100 command cycle):
if ($st_counter%100 == 0 || $st_counter == 0 )
{
$content .= "\nINSERT INTO ".$table." VALUES";
}
$content .= "\n(";
for($j=0; $j<$fields_amount; $j++)
{
$row[$j] = str_replace("\n","\\n", addslashes($row[$j]) );
if (isset($row[$j]))
{
$content .= '"'.$row[$j].'"' ;
}
else
{
$content .= '""';
}
if ($j<($fields_amount-1))
{
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num)
{
$content .= ";";
}
else
{
$content .= ",";
}
$st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}
//$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
$date = date("Y-m-d");
$backup_name = $backup_name ? $backup_name : $name.".$date.sql";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$backup_name."\"");
//echo $content; exit;
}
?>

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);
?>

Wordpress ajax: submit form then go to homepage instead of replacing html tag

I tried many times but it does not work as I expect to. I have a form submit a company name back to wordpress ajax to query AD in order to get a list of users. However, everytime I hit submit button, it just loads the homepage of the website. Please look at and show me the incorrect point in my code
Here is the code in function.php
function load_scripts() {
wp_enqueue_script('jquery');
wp_register_script('directory_script',get_template_directory_uri().'/js/directory.js',array('jquery'));
wp_enqueue_script('directory_script');
wp_register_script('directory1_script',get_template_directory_uri().'/js/directory1.js',array('jquery'));
wp_enqueue_script('directory1_script');
}
add_action ('wp_enqueue_scripts','load_scripts');
// buildDirectory function
function buildDirectory () {
$Company = $_GET["companyname"];
$ad = "ad1.p.local";
$result1;
exec("ping -n 3 " . $ad, $output, $result1);
if ($result1 != 0) {
$ad = "ad2.p.local";
exec("ping -n 3 " . $ad, $output, $result1); }
elseif ($result1 != 0) {
$ad = "ad3.p.local";
exec("ping -n 3 " . $ad, $output, $result1); }
//else { echo "Unable to get contact"; }
$ldap_connection = ldap_connect($ad);
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die("Unable to set LDAP protocol version");
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
$result;
$ldap_password = "abc";
$ldap_username = "cde";
$bind = ldap_bind($ldap_connection, $ldap_username, $ldap_password);
//$Company = "Patrick Industries";
//if (TRUE === $bind)
// {echo "Binding is successful<br />";}
//else {echo "Binding is unsuccessful<br />";}
if (TRUE === $bind) {
$ldap_base_dn = "DC=p,DC=local";
$search_filter = "(&(objectCategory=person)(objectClass=user)(company=$Company))";
$attributes = array();
$attributes[] = 'givenname';
$attributes[] = 'mail';
$attributes[] = 'samaccountname';
$attributes[] = 'sn';
$attributes[] = 'telephonenumber';
$attributes[] = 'company';
$result = ldap_search($ldap_connection, $ldap_base_dn, $search_filter, $attributes);
if (FALSE !== $result) {
$entries = ldap_get_entries($ldap_connection, $result);
// echo "<br />Found " . $entries["count"] . " entries <br />";
echo "<h4>List of contacts:</h4><br />";
echo "<table><tr>
<th style='font-weight:bold;font-size:16px;width:150px'>Name</th>
<th style='font-weight:bold;font-size:16px;width:120px'>Phone</th>
<th style='font-weight:bold;font-size:16px;width:220px'>Email</th>
<th style='font-weight:bold;font-size:16px;width:160px'>Company</th>
</tr><tr>";
$count1 = 0;
for ($x=0; $x<$entries['count']; $x++){
if (!empty($entries[$x]['givenname'][0]) &&
!empty($entries[$x]['mail'][0]) &&
!empty($entries[$x]['samaccountname'][0]) &&
!empty($entries[$x]['telephonenumber'][0]) &&
!empty($entries[$x]['sn'][0]))
{ echo "<td>". $entries[$x]['givenname'][0] . " " . $entries[$x]['sn'][0] . "</td>";
echo "<td>". $entries[$x]['telephonenumber'][0] . "</td>";
echo "<td>" . $entries[$x]['mail'][0] . "</td>";
echo "<td>". $entries[$x]['company'][0] . "</td></tr>";
$count1++; }
// { $user = $entries[$x]['givenname'][0] . " " . $entries[$x]['sn'][0] . " , " . $entries[$x]['telephonenumber'][0] . " , " . "" . $entries[$x]['mail'][0] . "" . " , " . $entries[$x]['company'][0] . " .<br />";}
}
// echo "There are " . $count1 . " contacts";
echo "</table>";
}
}
die();
}
add_action('wp_ajax_bDirectory','buildDirectory');
add_action('wp_ajax_nopriv_bDirectory','buildDirectory');
Here is js file
// Have to include in .js file
var $j = jQuery.noConflict();
var ajaxurl = "http://<ip>/wordpress/wp-admin/admin-ajax.php";
// build directory through form submission
$j("#company").submit(function(){
//var cname = $j("#cname").val();
var str = $(this).serialize();
$j.ajax({
url: ajaxurl,
type: "GET",
data: { action: "bDirectory", "cname": str },
success: function(html) {
$j("#company").replaceWith(html);
$j("#load").hide();
}
});
});
Here is HTML code
<form id="company" action="#">
<input id="cname" name="companyname" type="text"/>
<button type="submit">Submit</button>
</form>
You have to prevent the form from being submitted "the normal way":
$j("#company").submit(function(e){
e.preventDefault(); // Prevents the form default action to be triggered
var str = $(this).serialize();
$j.ajax({
url: ajaxurl,
type: "GET",
data: { action: "bDirectory", "cname": str },
success: function(html) {
$j("#company").replaceWith(html);
$j("#load").hide();
}
});
});
EDIT
In functions.php you use $_GET["companyname"]; but in your javascript you send data: { action: "bDirectory", "cname": str },, this should be corrected before anything.

laravel ajax post doesn't return values

I am trying to perform ajax post in laravel. I have a controller "show_freeCars" awich gets some values from ajax post and performs the query to return the results. I have this:
public function show_freeCars() {
$starttime = Input::get('starttime');
$endtime = Input::get('endtime');
$enddate = Input::get('enddate');
$startdate = Input::get('startdate');
$classes = Input::get('classes');
$free_cars = DB::select('SELECT * FROM cars WHERE id NOT IN (select distinct c.id from cars as c '
. 'left join rentals as r on c.id = r.vehicle '
. 'where STARTTIME="' . $startdate . ' ' . $starttime . '" '
. 'AND ENDTIME="' . $enddate . ' ' . $endtime . '" '
. 'AND (r.status="REZERVATION" OR r.status="CHECK_OUT") '
. 'order by c.id) AND class= "' . $classes . '" ');
if (Request::ajax()) {
$response_values = array(
'success' => 1,
'values' => $free_cars,
);
return Response::json($response_values);
} else {
dd('error');
}
}
and javascript
jQuery('#form-reservation').submit(function()
{
var startdate = $('input[name$="startdate"]').val();
var starttime = $('input[name$="starttime"]').val();
var enddate = $('input[name$="enddate"]').val();
var endtime = $('input[name$="endtime"]').val();
var classes = $('input[name$="classes"]').val();
var url = $(this).attr("action");
jQuery.ajax({
url: url,
type: "post",
data: {
startdate: startdate,
starttime: starttime,
enddate: enddate,
endtime: endtime,
classes: classes
},
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
}
})
.done(function(data)
{
$('#cars_table').empty()
if (data.success === 1)
{
var arr = data.values;
alert(arr);
}
else {
window.location = data.redirect_to;
}
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('Invalid Data');
});
return false;
});
It alerts an empty. But if i remove the lines $classes = Input::get('classes'); and AND class= "' . $classes . '" ' from controller it shows the results. The query is ok because I tested it with dd($free_cars) and it displays the list of cars. Just something is messed with ajax return values. Why it returns null?

error reading db in joomla

While i run a component i am getting 500 - An error has occurred error reading db in joomla.
My configuration file is perfect.
I don't know what else to change..
Any guidance will be helpful
Thanks in advance...
//No direct acesss
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
class DealsModelDeals extends JModel {
function getDeals(){
$db = $this->getDBO();
$db->setQuery('SELECT * from #__todaysdeal');
$deals = $db->loadObjectList();
if ($deals === null)
JError::raiseError(500, 'Error reading db');
return $deals;
}
function getDeal($id){
$query = ' SELECT * FROM #__todaysdeal '. ' WHERE id = '.$id;
$db = $this->getDBO();
$db->setQuery($query);
$deal = $db->loadObject();
if ($deal === null)
JError::raiseError(500, 'Deal with ID: '.$id.' not found.');
else
return $deal;
}
/**
* Method that returns an empty greeting with id 0
*
* #access public
*/
function getNewDeal(){
$dealTableRow =& $this->getTable('deals');
$dealTableRow->id=0;
$dealTableRow->clientName='';
return $dealTableRow;
}
/**
* Method to store a greeting in the DB
*
* #access public
*/
function saveDeal($deal)
{
//Parameter not necessary because our model is named DealsModelDeals (used to ilustrate that you can specify an alternative name to the JTable extending class)
$dealTableRow =& $this->getTable('deals');
//print_r($dealTableRow);
//print_r($_FILES); exit;
// Bind the form fields to the todaysdeal table
if (!$dealTableRow->bind($deal)) {
JError::raiseError(500, 'Error binding data');
}
// Make sure the deal record is valid
if (!$dealTableRow->check()) {
JError::raiseError(500, 'Invalid data');
}
// Insert/update this record in the db
if (!$dealTableRow->store()) {
$errorMessage = $dealTableRow->getError();
JError::raiseError(500, 'Error binding data: '.$errorMessage);
}
$id = $dealTableRow->id;
if(!empty($_FILES['dealImage']))
{
$file = $_FILES['dealImage'];
$id = $dealTableRow->id;
if ((($_FILES["dealImage"]["type"] == "image/gif") || ($_FILES["dealImage"]["type"] == "image/jpeg") || ($_FILES["dealImage"]["type"] == "image/pjpeg")) && ($_FILES["dealImage"]["size"] < 150000))
{
if ($_FILES["dealImage"]["error"] > 0)
{
echo "Return Code: " . $_FILES["dealImage"]["error"] . "<br />";
}
else
{
if (file_exists("components/com_deals/dealImages/" . $_FILES["dealImage"]["name"])) {
$_FILES["dealImage"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["dealImage"]["tmp_name"], "components/com_deals/dealImages/" .$id."_".$_FILES["dealImage"]["name"]);
echo "Stored in: " . "dealImages/" . $_FILES["dealImage"]["name"];
}
}
}
else
{
}
}
$dealImage = $_FILES['dealImage']['name'];
$dealImage .= (!empty($_FILES['dealImage']['name'])) ? ' ' . $_FILES['dealImage']['name'] : '';
$query = "UPDATE #__todaysdeal SET dealImage='".$id."_".$_FILES['dealImage']['name']."' WHERE id='".$id."'";
$db = $this->getDBO();
$db->setQuery($query);
$db->query();
//If we get here and with no raiseErrors, then everythign went well
}
function deleteDeals($arrayIDs)
{
$query = "DELETE FROM #__todaysdeal WHERE id IN (".implode(',', $arrayIDs).")";
$db = $this->getDBO();
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error deleting Deals: '.$errorMessage);
}
}
function dealsUploadPhoto($file, $id)
{
//UPLOAD FILE
$config = & JComponentHelper::getParams('com_deals');
$allowed = array('image/pjpeg', 'image/jpeg', 'image/jpg', 'image/png', 'image/x-png', 'image/gif', 'image/ico', 'image/x-icon');
$pwidth = $config->get('pwidth');
$pheight = $config->get('pheight');
$maxsize = $config->get('maxsize');
if($file['size'] > 0 && ($file['size'] / 1024 < $maxsize)){
if(!file_exists(JPATH_SITE . DS. 'images' . DS . 'deals'))
{
if(mkdir(JPATH_SITE . DS . 'images' . DS . 'deals')) {
JPath::setPermissions(JPATH_SITE . DS . 'images' . DS . 'deals', '0777');
if(file_exists(JPATH_SITE . DS . 'images' . DS . 'index.html')) {
copy(JPATH_SITE . DS . 'images' . DS . 'index.html', JPATH_SITE . DS . 'images' . DS . 'deals/index.html');
}
}
}
if($file['error'] != 0){
tpJobsMsgAlert('Upload file photo error.');
exit ();
}
if($file['size'] == 0){
$file = null;
}
if(!in_array($file['type'], $allowed)) {
$file = null;
}
if ($file != null){
$dest = JPATH_SITE.DS.'images'.DS.'deals'.DS.$id.'.jpg';
if(file_exists($dest))
{
$del = unlink($dest);
}
$soure = $file['tmp_name'];
jimport('joomla.filesystem.file');
$uploaded = JFile::upload($soure,$dest);
$fileAtr = getimagesize($dest);
$widthOri = $fileAtr[0];
$heightOri = $fileAtr[1];
$type = $fileAtr['mime'];
$img = false;
switch ($type)
{
case 'image/jpeg':
case 'image/jpg':
case 'image/pjpeg':
$img = imagecreatefromjpeg($dest);
break;
case 'image/ico':
$img = imagecreatefromico($dest);
break;
case 'image/x-png':
case 'image/png':
$img = imagecreatefrompng($dest);
break;
case 'image/gif':
$img = imagecreatefromgif($dest);
break;
}
if(!$img)
{
return false;
}
$curr = #getimagesize($dest);
$perc_w = $pwidth / $widthOri;
$perc_h = $pheight / $heightOri;
if(($widthOri<$pwidth) && ($heightOri<$height))
{
return;
}
if($perc_h > $perc_w)
{
$pwidth = $pwidth;
$pheight = round($heightOri * $perc_w);
}
else
{
$pheight = $pheight;
$pwidth = round($widthOri * $perc_h);
}
$nwimg = imagecreatetruecolor($pwidth, $pheight);
imagecopyresampled($nwimg, $img, 0, 0, 0, 0, $pwidth, $pheight, $widthOri, $heightOri);
imagejpeg($nwimg, $dest, 100);
imagedestroy($nwimg);
imagedestroy($img);
}
}else{
if($file['size'] / 1024 > $maxsize){
dealsMsgAlert('Size of file photo is too big. Maximum size".$maxsize." KB');
exit ();
}
}
}
function dealsMsgAlert($msg)
{
if (!headers_sent())
{
while(#ob_end_clean());
ob_start();
echo "<script> alert('".$msg."'); window.history.go(-1); </script>\n";
$out = ob_get_contents();
ob_end_clean();
echo $out;
exit();
}
echo "<script> alert('".$msg."'); window.history.go(-1); </script>\n";
exit();
}
}
?>
The problem that causes the red screen with 500 Error is happening because you are raising an exception if the requested quote is does not exist. You should not use JError::raiseError().
Use one of the following instead:
// This will set error to the model. You can get the errors from
// the model by your controller $model->getErrors() and output them to the screen.
$this->setError('ERROR MESSAGE GOES HERE');
OR
// This will output errors to the screen right the way
JFactory::getApplication()->enqueueMessage('ERROR MESSAGE GOES HERE', 'message');
Model already has _db property, you do not need to get db into variable. You can access it like this $this->_db. You can read about Joomla Model class here.
Also within your model you are using
$db = $this->getDBO();
$db->setQuery('SELECT * from #__todaysdeal');
$deals = $db->loadObjectList();
Model has simplified method to load list of object, like so
$deals =& $this->_getList('SELECT * from #__todaysdeal');

Resources