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>');
}
}
});
I have a case of wanting to create a div element based on the element div obtained from json response I checked in the console data successfully passed to view blade, the error is to fail add new element div based on json response obtained. Can anyone help?
my code
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
foreach ($list as $row) {
$val = array();
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
AJAX
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (data) {
alert(data);
$('#potonganku').html(data);
},
error: function (request, status, error) {}
});
});
blade
<div id="potonganku" class="form-group row"> </div>
Best way in that case is to build markup on the client side. Return raw JSON data from controller, and then build HTML via JS.
Controller:
public function getIDpotongan($id)
{
return response()->json([
'data' => PotonganPenggajianModel::where('nip', $id)
->select('jenis_potongan', 'some_field')
->get(),
]);
}
JS
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
var buildHTML = function (data) {
var html = '';
for (i in data) {
html += '<h3>' + data[i].jenis_potongan + '</h3>';
// someting with data[i].some_field
}
return html;
};
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (response) {
$('#potonganku').html(buildHTML(response.data));
},
error: function (request, status, error) {}
});
});
You're creating a new empty $val = array(); array for every foreach. lets put it outside.
So your Controller would be:
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
$val = array();
foreach ($list as $row) {
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
I don't understand why call_script_id is showing as a string instead of the content stored in the variable. The other variables work fine, but literally, call_script_id is setting id="call_script_id" whereas call_reason_id is setting the proper number.
$.ajax({
url: "../selections/call-reasons.php",
type: 'post',
data: {company_uid:"<?php echo $row['company_uid']; ?>"},
dataType: 'json',
success:function(response){
var len = response.length;
$("#call_reasons").empty();
for( var i = 0; i<len; i++){
var call_script_id = response[i]['call_script_id'];
var call_reason_id = response[i]['call_reason_id'];
var call_type = response[i]['call_type'];
var active = response[i]['active'];
$("#call_reasons").append("<tr><td href='../modals/call-types.php' class='call_reason_row' id=" + call_script_id + ">" + call_reason_id + "</td><td id=" + call_script_id + "></td><td id=" + call_script_id + "></td><td><i class='far fa-edit'></i><i class='far fa-calendar-alt'></i><i class='far fa-trash-alt call_reason_trash' id=" + call_reason_id + "></i></td></tr>");
}
// Brings up the pop up to edit call reasons/types
$(".call_reason_row").click(function() {
$('#main-content',parent.document).load($(this).attr('href'), {call_reason_id: this.id, company_uid: "<?php echo $row["company_uid"];?>", active: active});
});
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
$sql = "SELECT cs.id, cs.call_reason, sct.call_type FROM call_script AS cs INNER JOIN selection_call_types AS sct ON cs.call_reason = sct.id WHERE cs.company_uid = '$company_uid'";
$result = mysqli_query($conn, $sql);
$my_array = array();
while($row = mysqli_fetch_array($result) ){
$call_script_id = $row['id'];
$call_reason_id = $row['call_reason'];
$call_type = $row['call_type'];
$active = $row['active'];
$my_array[] = array("call_script_id" => call_script_id, "call_reason_id" => $call_reason_id, "call_type_id" => $call_type, "active" => $active);
}
I guess I expecting the issue to be in ajax since I'm not as familiar with the language. Instead, it was because I was missing the dollar sign on the variable call_reason_id, in $my_array on the very last line.
Here i'm doing a JSONP request, that will get an object literal passed into the callback function.
My Issue:
1.From the filename.php i'm passing two different array's like :
echo $_GET['jsoncallback'] . '(' . json_encode($manufacturers). ');';
echo $_GET['jsoncallback'] . '(' . json_encode($Stock). ');';
2.I'm receiving only one array as output at a time.
3. i need the both array .
function onLoad(){
var output = $('#product');
$.ajax({
url:'filename.php',
data : {type : 'details'},
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success:function(data){
$.each(data, function(c,prdetail){
if(prdetail.field_name=='' || prdetail.field_name==undefined )
{
var firstdata= '<h2 >'+prdetail.field_name1+ '</h2>';
output.append(firstdata);
}
else
{
var secondata ='<h2 >'+prdetail.field_name2+ '</h2>';
output.append(secondata);
}
});
}
});
}
FILENAME.PHP
if($status=1)
{
$manufacturers_sql = mysql_query('select * FROM tablename');
$rowcount = mysql_num_rows($result);
$records = array();
$row = mysql_fetch_assoc($result);
$records[] = $row;
echo $_GET['jsoncallbacks'] . '(' . json_encode($records) . ');';
}
else
{
$manufacturers_sql = mysql_query('select * FROM tablename');
$rowcount = mysql_num_rows($result);
$records = array();
$row = mysql_fetch_assoc($result);
$records[] = $row;
echo $_GET['jsoncallbacks'] . '(' . json_encode($records) . ');';
}
Try
$response = array();
$response['manufacturers'] = $manufacturers;
$response['Stock'] = $Stock;
echo $_GET['jsoncallback'] . '(' . json_encode($response). ');';
I am attempting to use a variable in my SELECT statement but I'm running into some very strange problems .code below.
do not work,none data!
Code:
$fid= $_GET['f'];
echo $fid;//prints 3
$SQL = "SELECT threadid, thumb, title, stage, status, startdate ,duedate, forumid FROM thread WHERE forumid = '$fid' ";
work fine!
**Code:**
$SQL = "SELECT threadid, thumb, title, stage, status, startdate ,duedate, forumid FROM thread WHERE forumid ='3' ";
thank you!
grid.php
<?php include ("add/add_config.php");?>
<?php include ("php/jqAutocomplete.php");?>
<?php include ("php/jqCalendar.php");?>
<?php include ("php/jqGrid.php");?>
<?php
ini_set("display_errors","1");
$fid= $_GET['f'];
include ("php/jqGridPdo.php");
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
$conn->query("SET NAMES utf8");
// Create the jqGrid instance
$grid = new jqGridRender($conn);
echo $fid;
$grid->SelectCommand ="SELECT threadid, thumb, title, stage, status, startdate ,duedate FROM thread WHERE forumid='3'";
//$g="SELECT threadid, thumb, title, stage, status, startdate ,duedate, forumid FROM thread WHERE forumid='$fid'";
//echo $g;
// set the ouput format to json
$grid->dataType = 'json';
$grid->table ="thread";
$grid->setPrimaryKeyId("threadid");
$grid->setUrl('grid.php');
$grid->cacheCount = true;
$grid->addCol(array(
"name"=>"actions",
"formatter"=>"actions",
"editable"=>false,
"sortable"=>false,
"resizable"=>false,
"fixed"=>true,
"width"=>60,
"formatoptions"=>array("keys"=>true)
), "first");
$grid->setGridOptions(array(
"caption"=>"cdbdev",
"rownumbers"=>true,
"toppager"=>true,
"rowNum"=>10,
"sortname"=>"threadid",
"hoverrows"=>true,
"rowList"=>array(10,20,50),
"postData"=>array("grid_recs"=>776),
"height"=>"auto",
"width"=>"auto"
));
$grid->addCol(array("name"=>"fileToUpload", "editable"=>true, "edittype"=>"file", "editrules"=>array("edithidden"=>true)));
$upload = <<<UPLOAD
function(formid) {
//These are needed for fileupload plugin
$(formid).attr("method","POST");
$(formid).attr("action","");
$(formid).attr("enctype","multipart/form-data");
$("<br/><button id='buttonUpload'>Upload</button>").insertAfter("#fileToUpload",formid);
// bind a event
$("#buttonUpload",formid).click(function(){
$.ajaxFileUpload({
url:'doajaxfileupload.php',
secureuri:false,
fileElementId:'fileToUpload',
dataType: 'json',
success: function (data, status) {
console.log(data);
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else{
$("#fileToUpload").val("");
alert(data.msg);
}
}
},
error: function (data, status, e)
{
alert(e);
}
});
return false;
});
}
UPLOAD;
$grid->setJSCode($upload);
$image = <<<CUSTOM
function formatImage(cellValue, options, rowObject) {
var imageHtml = "<img src='images/" + cellValue + "' originalValue='" + cellValue + "' />";
return imageHtml;
}
function unformatImage(cellValue, options, cellObject) {
return $(cellObject.html()).attr("originalValue");
}
function formatRating(cellValue, options, rowObject) {
var color = (parseInt(cellValue) > 0) ? "green" : "red";
var cellHtml = "<span style='color:" + color + "' originalValue='" +
cellValue + "'>" + cellValue + "</span>";
return cellHtml;
}
function unformatRating(cellValue, options, cellObject) {
return $(cellObject.html()).attr("originalValue");
}
CUSTOM;
$grid->setJSCode($image);
$grid->setSelect('stage', "SELECT id, name FROM selection where statid=1");
$grid->setSelect('status', "SELECT id,name FROM selection where statid=2 ");
$grid->setColProperty("threadid", array( "width"=>80 , "align"=>center));
$grid->setColProperty("stage", array( "width"=>120 , "align"=>center));
$grid->setColProperty("forumid", array( "width"=>0 ,));
$grid->setColProperty("status", array( "width"=>120 , "align"=>center ));
$grid->setColProperty("title", array( "width"=>280, "align"=>center ,"formatter"=>"showlink","formatoptions"=>array("baseLinkUrl"=>"showthread.php", "target"=>"_blank", "idName"=>"t")));
$grid->setColProperty("startdate", array("width"=>130,"align"=>center,
"formatter"=>"date",
"formatoptions"=>array("srcformat"=>"Y-m-d H:i:s","newformat"=>"m/d/Y")
)
);
$grid->setColProperty("duedate", array("width"=>130,"align"=>center,
"formatter"=>"date",
"formatoptions"=>array("srcformat"=>"Y-m-d H:i:s","newformat"=>"m/d/Y")
)
);
$grid->setColProperty("CustomerID", array("editrules"=>array("required"=>true)));
$grid->setAutocomplete("CustomerID",false,"SELECT CustomerID, CompanyName FROM customers WHERE CompanyName LIKE ? ORDER BY CompanyName",null,true,true);
$grid->setUserTime("m/d/Y");
$grid->setUserDate("m/d/Y");
$grid->setDatepicker("startdate",array("buttonOnly"=>false));
$grid->datearray = array('startdate');
$grid->setUserTime("m/d/Y");
$grid->setUserDate("m/d/Y");
$grid->setDatepicker("duedate",array("buttonOnly"=>false));
$grid->datearray = array('duedate');
$grid->navigator = true;
$grid->setNavOptions('navigator', array("cloneToTop"=>true,"excel"=>true,"add"=>false,"edit"=>false,"del"=>false,"view"=>false));
$grid->exportfile = 'Report.xls';
$grid->setNavOptions('navigator', array("cloneToTop"=>true,"pdf"=>true,"add"=>false,"edit"=>false,"del"=>false,"view"=>false));
$grid->inlineNav = true;
$grid->setNavEvent('edit', 'onInitializeForm', $upload);
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>
What SQL engine are you using? If it's MySQL you can use:
echo mysql_error();
after running the select to see what error you're having
also try echoing the SELECT statement after generating it to make sure no additional whitespace etc is added to $fid