Laravel passing data using ajax to controller - ajax

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;
}

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])}}".'

Laravel Ajax live search relationship

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.

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'] ?>;

CakePHP-2.4 : subcategories according to categories by ajax

I am trying to get subcategories according to categories by ajax.So I have sent data in controller by ajax get method like bellow code in add.ctp
$('document').ready(function(){
$( "#division" ).change(function() {
var value=$('#division').val();
$.get("<?php echo Router::url(array('controller'=>'userStoreSelections','action'=>'add'));?>",{list:value},function(data){
$('.districts').html(data);
alert(data);
});
});
});
In controller in find methods when I am writing bellow code It's working fine.
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list',array(
'conditions'=>array('mad_divisions_id'=>3)
));
But when I give the value that I have sent by ajax it's not working.I have written like this
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list',array(
'conditions'=>array('mad_divisions_id'=>"$list")
));
It showing the query like this
SELECT `MadDistricts`.`id`, `MadDistricts`.`name` FROM `store`.`mad_districts` AS `MadDistricts` WHERE `mad_divisions_id` IS NULL
After select categories nothing change in query.I have tested ajax code there is no problem to send value.
For more specific this is the add action code
public function add() {
if(isset($this->request->query['list'])){
$search = $this->request->query['list'];
echo $search;
}
else{
$search = '';
}
if ($this->request->is('post')) {
$this->UserStoreSelection->create();
if ($this->UserStoreSelection->save($this->request->data)) {
$this->Session->setFlash(__('The user store selection has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user store selection could not be saved. Please, try again.'));
}
}
$madDivisions = $this->UserStoreSelection->MadDivisions->find('list');
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list',array(
'conditions'=>array('mad_divisions_id'=>"$list")
));
$madAreas = $this->UserStoreSelection->MadAreas->find('list');
$users = $this->UserStoreSelection->Users->find('list',array('fields' => array('id','username')));
$madStores = $this->UserStoreSelection->MadStores->find('list',array('fields' => array('id','store_name')));
$this->set(compact('madDivisions', 'madDistricts', 'madAreas', 'users','madStores'));
}
You need to change your add.ctp file code like as :
$('document').ready(function () {
$("#division").change(function () {
var value = $(this).val();
$.ajax({
url: '<?php echo Router::url(' / ',true);?>userStoreSelections/subcategories',
type: "POST",
dataType: 'json',
data: 'category=' + id,
success: function (res) {
var html = '<option>Sub Category</option>';
if (res.flage == true) {
html = res.data;
}
$('.districts').html(html);
}
});
});
});
Than create a function in your userStoreSelections for get sub categories as
public function subcategories() {
$response = array('flage' => false);
$madDistricts = $this->UserStoreSelection->MadDistricts->find('list', array(
'conditions' => array('mad_divisions_id' => $this->request->data['category'])
));
$options = "<option>Subcategories</option>";
if ($states) {
$response['flage'] = true;
foreach ($madDistricts as $id => $name) {
$options .= "<option value='" . $id . "'>" . $name . "</option>";
}
$response['data'] = $options;
}
echo json_encode($response);
exit;
}

Resources