Laravel Ajax live search relationship - ajax

Laravel ajax live search does not work. In the console browser, he writes a 500 error. The problem is this relationships. If I do not use it relationship, the ajax live sarch is work. How do I edit my code to work?
Here the code, to be precise:
$contract->typzakazky->nazov_typu.
My model:
public function typzakazky()
{
return $this->belongsTo('App\ContractsType','contracts_type_id');
}
Controller:
public function index()
{
return view('contracts.index');
}
public function search(Request $request)
{
if ($request->ajax()) {
$output = "";
$contracts = DB::table('contracts')->where('nazov', 'LIKE', '%' . $request->search . "%")->get();
if ($contracts) {
foreach ($contracts as $key => $contract) {
$output .= '<tr>' .
'<td>' . $contract->poradove_cislo . '</td>' .
'<td>' . $contract->nazov . '</td>' .
'<td>' . $contract->typzakazky->nazov_typu. '</td>' .
'<td>' . $contract->datumodovzdania. '</td>' .
'</tr>';
}
return Response($output);
}
}
}
View:
...
<script type="text/javascript">
$('#search').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{URL::to('search')}}',
data:{'search':$value},
success:function(data){
$('tbody').html(data);
}
});
})
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>
How to use it properly relationship in ajax? Very thank you.

Related

Obtain User Name Laravel Yajra Datatables

I have this database of user reports with this structure.
SQL DATABASE
I need to get the username out of the ids
the ids are in the tables "reportante" and "user_id_afectado"
These data are in the database
users.
Currently I only have the ids of the users I need to have the names as well but they are in another table.
I have this current code.
In ReportesDatatable.php
<?php
namespace App\Http\Controllers\Datatables;
use App\User;
use Carbon\Carbon;
use Yajra\DataTables\DataTables;
use App\Reportes;
class ReportesDatatable
{
public function ReportesDatatable()
{
$reportes = Reportes::get();
$usernameafectado = User::get();
//dd($usernameafectado[0]->name);
return Datatables::of($reportes)
->editColumn('user_id_afectado', function ($usernameafectado) {
return '<span data-popup="tooltip" data-placement="left" title="' . $usernameafectado[0]->name . '">' . $usernameafectado->name . '</span>';
})
->editColumn('created_at', function ($reportes) {
return '<span data-popup="tooltip" data-placement="left" title="' . $reportes->timestamp . '">' . $reportes->timestamp . '</span>';
})
->addColumn('action', function ($reportes) {
return '<div class="btn-group btn-group-justified"> Ver Reportante Afectado <i class="icon-circle-right2 text-white"></i></div>';
})
->rawColumns(['role', 'action', 'created_at'])
->make(true);
}
}
In my controller
//Solicitud reportes
public function verreportesadmin()
{
$usuarios = User::orderBy('id', 'DESC')->paginate(20);
//dd($usuarios);
$users = Reportes::orderBy('id', 'DESC')->paginate(20);
$count = $users->total();
return view('admin.verreportesadmin', array(
'users' => $users,
'usuarios' => $usuarios,
'count' => $count,
));
}
//Solicitud reportes
Currently I get this result where only the ids are shown.
Image RESULT
EDIT!!!! I FOUND SOLUTION I did it by doing a search with the id but I don't know if this is optimal for the server.
<?php
namespace App\Http\Controllers\Datatables;
use App\User;
use Carbon\Carbon;
use Yajra\DataTables\DataTables;
use App\Reportes;
class ReportesDatatable
{
public function ReportesDatatable()
{
$reportes = Reportes::get();
return Datatables::of($reportes)
->editColumn('reportante', function ($reportes) {
$reportante = User::find($reportes->reportante);
return $reportante->name;
})
->editColumn('user_id_afectado', function ($reportes) {
$nameafectado = User::find($reportes->user_id_afectado);
return $nameafectado->name;
})
->editColumn('created_at', function ($reportes) {
return '<span data-popup="tooltip" data-placement="left" title="' . $reportes->timestamp . '">' . $reportes->timestamp . '</span>';
})
->addColumn('action', function ($reportes) {
return '<div class="btn-group btn-group-justified"> Ver Reportante Afectado <i class="icon-circle-right2 text-white"></i></div>';
})
->rawColumns(['role', 'action', 'created_at'])
->make(true);
}
}
I FOUND SOLUTION I did it by doing a search with the id but I don't know if this is optimal for the server.
<?php
namespace App\Http\Controllers\Datatables;
use App\User;
use Carbon\Carbon;
use Yajra\DataTables\DataTables;
use App\Reportes;
class ReportesDatatable
{
public function ReportesDatatable()
{
$reportes = Reportes::get();
return Datatables::of($reportes)
->editColumn('reportante', function ($reportes) {
$reportante = User::find($reportes->reportante);
return $reportante->name;
})
->editColumn('user_id_afectado', function ($reportes) {
$nameafectado = User::find($reportes->user_id_afectado);
return $nameafectado->name;
})
->editColumn('created_at', function ($reportes) {
return '<span data-popup="tooltip" data-placement="left" title="' . $reportes->timestamp . '">' . $reportes->timestamp . '</span>';
})
->addColumn('action', function ($reportes) {
return '<div class="btn-group btn-group-justified"> Ver Reportante Afectado <i class="icon-circle-right2 text-white"></i></div>';
})
->rawColumns(['role', 'action', 'created_at'])
->make(true);
}
}

use route in controller

i'm trying to fetch data(jobs) and display each single job i have route for jobs and route for single job but when i use route in controller i get route not defined even all is good please check my question
ajax call
<script>
$(document).on('click','.submit', function(e) {
var category = $("input[name=category_id]").val();
var location= $(".js-example-basic-single option:selected" ).val();
console.log(location);
$.ajax({
type:'get',
data: {location : location,category : category},
url:'/job_listing',
success:function(data) {
$('.job-list').html(data);
console.log(category);
console.log(location);
}
})
});
function in cotroller
public function show_offers(Request $request){
$category = $request->category;
$location= $request->location;
if($request->ajax()) {
$data = Job_offer::where([
'category_id' => $category,
'location_id' => $location,
])->orwhere('location_id','=',$location)->orwhere('category_id','=',$category)->get();
// ->orWhere('location_id','LIKE','%'.$input.'%')->with('location')->get();
$output = '';
if (count($data)>0) {
$output = '';
foreach ($data as $row){
$output .= '<div class="job-info"> <div class="job_offer-img"><img class="offer-img" src='.'img/'.$row->offer_image.'></div>';
$output .= '<div class="job-title"> <span class="job"> '.$row->offer_title.'</span>';
$output .= '<span class="location">'.$row->location->Name.'</span></div>';
$output .= '<div class="job-contrat"> <span class="contract"> '.$row->type_emploi.'</span></div></div>';
}
$output .= '';
}
else {
$output .= '<li class="list-group-item">'.'No results'.'</li>';
}
return $output;
}
route
Route::get('single_offer/{offer_id}','job_seeker\Job_offers#single_offer')->name('single/offer');
Route::get('job_listing','job_seeker\home_job_seeker#show_offers');
Your routes need to be in routes/api.php file instead of routes/web.php file.
Use like this
href='."{{route('single/offer',['offer_id'=>$row->id])}}".'

OpenCart throws Invalid Token Session after deleting orders

I have written a bespoke Ajax call and function to delete missing orders in OpenCart 2.1.0.2. Although the function works as it should, and the orders are deleted, upon return from the controller, OpenCart logs me out and gives me an Invalid Token Session error, even though the passed token is correct.
Here's my ajax call on the order_list.tpl template:
$('#button-delete_missing').on('click', function(e) {
if (confirm('<?php echo $text_confirm; ?>')) {
var node = this;
$.ajax({
url: '<?php echo $store; ?>index.php?route=api/order/deleteMissing&token=<?php echo $_GET["token"] ?>',
dataType: 'json',
crossDomain: true,
beforeSend: function () {
$(node).button('loading');
},
complete: function () {
$(node).button('reset');
},
success: function (json) {
$('.alert').remove();
if (json['error']) {
$('#content > .container-fluid').prepend('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + json['error'] + ' <button type="button" class="close" data-dismiss="alert">×</button></div>');
}
if (json['success']) {
$('#content > .container-fluid').prepend('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">×</button></div>');
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
});
This is exactly the same as the other calls on the page, except it's going to a different function in the controller:
public function deleteMissing() {
$this->load->language('api/order');
$json = array();
$this->load->model('checkout/order');
$this->model_checkout_order->deleteMissingOrders();
$json['success'] = $this->language->get('text_success');
if (isset($this->request->server['HTTP_ORIGIN'])) {
$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$this->response->addHeader('Access-Control-Max-Age: 1000');
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
Which, in turn, is the same as the delete function, just without the need for a specific order id. Here's the function in the model that actually does the delete:
public function deleteMissingOrders() {
$query = $this->db->query("SELECT order_id FROM " . DB_PREFIX . "order WHERE order_status_id = 0 OR order_status_id = null");
$rows = $query->rows;
$order_ids = array();
foreach($rows as $row) {
$order_ids[] = $row['order_id'];
}
if(!empty($order_ids)) {
foreach($order_ids as $order_id) {
$this->db->query("DELETE FROM `" . DB_PREFIX . "order` WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM `" . DB_PREFIX . "order_product` WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM `" . DB_PREFIX . "order_option` WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM `" . DB_PREFIX . "order_voucher` WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM `" . DB_PREFIX . "order_total` WHERE order_id = '" . (int)$order_id . "'");
}
}
}
The function gets all the null or zero ID order statuses and deletes all relevant data - this WORKS. I've tried it, and all the missing orders are deleted; it's just that when it comes back it throws a non-descript error (i.e. does not run the success part of the ajax call) and logs me out of the admin area.
If anyone can help with this I would be grateful. Maybe there's one thing I've missed, or something I haven't put in which is needed?
I I'm reading this correctly, your script doesnt seem to know what token is. Does it have a declaration? Because Jquery doesnt know what PHP knows.
Do something like
var token = <?php echo $_GET['token'] ?>;

Laravel passing data using ajax to controller

How do I pass the id from this ajax call to the TestController getAjax() function? When I do the call the url is testUrl?id=1
Route::get('testUrl', 'TestController#getAjax');
<script>
$(function(){
$('#button').click(function() {
$.ajax({
url: 'testUrl',
type: 'GET',
data: { id: 1 },
success: function(response)
{
$('#something').html(response);
}
});
});
});
</script>
TestController.php
public function getAjax()
{
$id = $_POST['id'];
$test = new TestModel();
$result = $test->getData($id);
foreach($result as $row)
{
$html =
'<tr>
<td>' . $row->name . '</td>' .
'<td>' . $row->address . '</td>' .
'<td>' . $row->age . '</td>' .
'</tr>';
}
return $html;
}
In the end, I just added the parameter to the Route::get() and in the ajax url call too. I changed $_POST['id'] to $_GET['id'] in the getAjax() function and this got my response back
Route::get('testUrl/{id}', 'TestController#getAjax');
<script>
$(function(){
$('#button').click(function() {
$.ajax({
url: 'testUrl/{id}',
type: 'GET',
data: { id: 1 },
success: function(response)
{
$('#something').html(response);
}
});
});
});
</script>
TestController.php
public function getAjax()
{
$id = $_GET['id'];
$test = new TestModel();
$result = $test->getData($id);
foreach($result as $row)
{
$html =
'<tr>
<td>' . $row->name . '</td>' .
'<td>' . $row->address . '</td>' .
'<td>' . $row->age . '</td>' .
'</tr>';
}
return $html;
}
Your ajax's method is GET but in controller you use $_POST to get
value. This is problem.
You can you
$id = $_GET['id'];
But in Laravel, it have a pretty method to do this. It's here. You do not need to worry about the HTTP verb used for the request, as input is accessed in the same way for all verbs.
$id = Input::get("id");
If you want, you can filter request type to control exception. Docs here
Determine If The Request Is Using AJAX
if (Request::ajax())
{
//
}
#in your controller function
public function getAjax()
{
#check if request is ajax
if ($request->ajax()) {
//your code
}
return $your_data;
}

CI and GroceryCRUD DB update row

I use CI 2.1 and GroceryCRUD 1.3.3, i use this 2 function in my controller Admin, but i cant update value of row wher i have 2 values 0/1:
bolean from my view side by click on link or with AJAX (prefered)
function programs_management()
{
if($this->input->get("enable_recomandation"))
{
// $this->programs_management->recomandation((int)$this->input->get("programs"), ($this->input->get("recomandation")=="1")?"1":"0");
$data_for_update = array(
'recomandation' => ($this->input->get("recomandation")=="1")?"1":"0",
);
$this->db->update('programs',$data_for_update,array('program_id' => $this->input->get("programs")));
}
}
function enable_recomandation($value, $row = NULL)
{
// or For AJAX some solution need
// return "<form action='' method='post'>
// <input onClick='document.getElementById('row').value=this.value' type='radio' name='recom' value='activ'>Activ<br>
// <input onClick='document.getElementById('row').value=this.value' type='radio' name='recom' value='inactiv'>Inactiv
// </form>";
if($value=="1")
return '<a href="'.base_url().'/admin/programs_management/?recomandation=0&program_id='.$row->program_id.'" >Active</a>';
else
return '<a href="'.base_url().'/admin/programs_management/?recomandation=1&program_id='.$row->program_id.'" >Inactive</a>';
}
Or somebody can help with alternative, how to do this with AJAX ?
function programs_management()
{
if ($this->input->get("recomandation"))
{
// $this->programs_management->recomandation((int)$this->input->get("programs"), ($this->input->get("recomandation")=="1")?"1":"0");
$data_for_update = array(
'recomandation' => ($this->input->get("recomandation") == "y") ? "1" : "0",
);
$this->db->update('programs', $data_for_update, array('program_id' => $this->input->get("program_id")));
}
}
function enable_recomandation($value, $row = NULL)
{
if ($value == "1")
return '<a href="' . base_url() . 'admin/programs_management/?recomandation=n&program_id=' . $row->program_id . '" >Active</a>';
else
return '<a href="' . base_url() . 'admin/programs_management/?recomandation=y&program_id=' . $row->program_id . '" >Inactive</a>';
}

Resources