How can I retrieve data using ajax? I have my ajax code that I've been using in some of my projects when retrieving records from database but dont know how to make it in laravel 5 because it has route and controller.
I have this html
<select name="test" id="branchname">
<option value="" disabled selected>Select first branch</option>
<option value="1">branch1</option>
<option value="2">branch2</option>
<option value="3">branch3</option>
</select>
<select id="employees">
<!-- where the return data will be put it -->
</select>
and the ajax
$("#branchname").change(function(){
$.ajax({
url: "employees",
type: "post",
data: { id : $(this).val() },
success: function(data){
$("#employees").html(data);
}
});
});
and in my controller, I declared 2 eloquent models, model 1 is for branchname table and model 2 is for employees table
use App\branchname;
use App\employees;
so I could retrieve the data like (refer below)
public function getemployee($branch_no){
$employees = employees::where("branch_no", '=', $branch_no)->all();
return $employees;
}
how to return the records that I pulled from the employees table? wiring from routes where the ajax first communicate to controller and return response to the ajax post request?
any help, suggestions, recommendations, ideas, clues will be greatly appreciated. Thank you!
PS: im a newbie in Laravel 5.
At first, add following entry in your <head> section of your Master Layout:
<meta name="csrf-token" content="{{ csrf_token() }}" />
This will add the _token in your view so you can use it for post and suchlike requests and then also add following code for global ajax setting in a common JavaScript file which is loaded on every request:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
So, you don't need to worry or add the csrf_token by yourself for methods who require this _token. Now, for a post request you may just use usual way to make an Ajax request to your Controller using jQuery, for example:
var data = { id : $(this).val() };
$.post(url, data, function(response){ // Shortcut for $.ajax({type: "post"})
// ...
});
Here, url should match the url of your route declaration for the employees, for example, if you have declared a route like this:
Route::post('employees/{branch_no}', 'EmployeeController#getemployee');
Then, employees is the url and return json response to populate the select element from your Controller, so the required code for this (including javaScript) is given below:
$.post('/employees/'+$(this).val(), function(response){
if(response.success)
{
var branchName = $('#branchname').empty();
$.each(response.employees, function(i, employee){
$('<option/>', {
value:employee.id,
text:employee.title
}).appendTo(branchName);
})
}
}, 'json');
From the Controller you should send json_encoded data, for example:
public function getemployee($branch_no){
$employees = employees::where("branch_no", $branch_no)->lists('title', 'id');
return response()->json(['success' => true, 'employees' => $employees]);
}
Hope you got the idea.
First check url of page from which ajax call initiates
example.com/page-using ajax
In AJAX
If you call $.get('datalists', sendinput, function())
You are actually making GET request to
example.com/page-using ajax/datalists
In Routes
Route::get('page-using-ajax/datalists', xyzController#abc)
In Controller Method
if (Request::ajax())
{
$text = \Request::input('textkey');
$users = DB::table('datalists')->where('city', 'like', $text.'%')->take(10)->get();
$users = json_encode($users);
return $users;
}
In Ajax Success Function
function(data) {
data = JSON.parse(data);
var html = "";
for (var i = 0; i < data.length; i++) {
html = html + "<option value='" + data[i].city + "'>";
};
$("#datalist-result").html(html);
}
Add in your route:
Route::post('employees', [
'as' => 'employees', 'uses' => 'YourController#YourMethod'
]);
Ajax:
Change:
url: "employees"
to:
url: "/employees"
Related
I'm new with laravel and I want to send the selected dropdown option value of product name through ajax data to the controller
For Example: If I'm select 1st plastic product option value from a drop-down then in the controller from request object I want that selected product name
as per my below code I'm getting null in the request object of the product name
Here is my route:
Route::get('product', 'ProductController#index')->name('product');
Here is my controller:
public function index(Request $request)
{
if (isset($request->productName)) {
$productName = $request->productName;
dump($productName); // getting null
} else {
$productName = null;
}
return view('Product.product');
}
Here is my an ajax call:
function display(productName){
productName = $('#product_filter').val(); // Here, I'm getting selected value of dropdown
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('product')}}",
type: "GET",
data:{
'productName' : productName // in header request I'm getting value [productName: plastic product] *
},
success:function(data){
console.log(data);
},
error:function(e){
console.log(e,'error');
}
});
}
header request result
I don't know if I'm doing something wrong,
ends with wanting to get help from helping hands please help me to get the selected value to the controller object
I believe you got null because you are returning a full HTML to the Ajax request. In order to get the payload sent from the Ajax, you have to return a JSON response like this:
public function index(Request $request)
{
$productName = null;
if (isset($request->productName)) {
$productName = $request->productName;
}
return response()->json($productName);
}
That being said, I'm unable to reproduce the issue without seeing how do you call the method and where would you show the data to. And I assume you want to simply just do a console.log(data) like you did on the given snippet. In this case, the snippet above will work.
And if you want to keep the view to prevent error when you refresh the page, just add a new method for that specific call in your controller and send the request to that endpoint, like this:
web.php
<?php
Route::get('/', [ProductController::class, 'index']);
Route::get('/productFilter', [ProductController::class, 'productFilter'])->name('dashboard-product-data');
ProductController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index(Request $request)
{
return view('welcome');
}
public function productFilter(Request $request)
{
$productName = null;
if (isset($request->productName)) {
$productName = $request->productName;
}
return response()->json($productName);
}
}
welcome.blade.php
<div>Product Name: <span id="product-name"></span></div>
<select id="product_filter" name="product_filter">
<option value="plastic product">plastic product</option>
</select>
<button id="submit-button" type="button">Send data</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
function display(productName){
productName = $('#product_filter').val(); // Here, I'm getting selected value of dropdown
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{route('dashboard-product-data')}}",
type: "GET",
data:{
'productName' : productName // in header request I'm getting value [productName: plastic product] *
},
success:function(data){
console.log(data);
document.querySelector('#product-name').innerHTML = data
},
error:function(e){
console.log(e,'error');
}
});
}
const submitButton = document.querySelector('#submit-button')
submitButton.addEventListener('click', () => display())
</script>
I've Signup form in my website. It was properly submitting before. Now I wanted to submit my form using ajax and wanted to return a variable from controller into JSON that I will use into blade file.
The form is submitting and values are showing into database but after redirection, it returns error.
Undefined variable: seller in report blade
I tried to decode my variable to make it work but still the same error.
How would I make it work?
Report-Blade
#foreach(json_decode($seller, true) as $row)
<a href="{{route('Report', $row->id) }}" >
{{ __('Show Report of ')}} {{$row->car_title}}
</a>
#endforeach
Controller
$seller = Sellers::take(1)->latest()->get();
return response(view('report',array('seller'=>$seller)),200, ['Content-Type' =>
'application/json']);
JavaScript
$("#submit-all").click(function(e){
e.preventDefault();
var _token = $('input[name="_token"]').val();
$.ajax({
type: "post",
url: "{{ route('form_for_private_sellers') }}",
data : $('#msform').serialize() + "&_token=" + _token,
dataType: 'JSON',
beforeSend: function(){
// Show loading image
$("#se-pre-con").show();
},
success: function(data) {
window.location = "http://127.0.0.1:8000/report/";
},
complete:function(data){
// Hide loading image
$("#se-pre-con").hide();
}
});
});
As understood from your comments,
window.location = "http://127.0.0.1:8000/report/";
will hit the route
Route::get('/report', function () {
return view('report');
})->name('private_seller_report');
Report blade expects a variable named $seller, and it is not being sent from the route. You would need to change the route to something similar to this:
Route::get('/report', function () {
$sellers = Seller::get(); //your logic
return view('report', ['seller' => $sellers]);
})->name('private_seller_report');
Alternatively you can point the route to a method in a controller if you want to avoid bulking up your routes.
you need two route for this
first for rendering blade
return view('report');
and the second for fetch seller
$seller = Sellers::latest()->take(1)->get();
return $seller
I want to send drop-down list data from view to controller via AJAX as a form variable using post method.
I am able to send the drop-down list data from view to controller using get method and using route parameters.
Here is my view code snippet:
function drawChart(frmyear, toyear)
{
console.log(frmyear);
console.log(toyear);
var jsonData = $.ajax({
url: "get_salesthree/"+ frmyear + "/"+ toyear +"/",
dataType: 'json',
async: false
}).responseText;
console.log(jsonData);
Route code snippet:
Route::get('get_salesthree/{frmyear}/{toyear}', array('uses'=>'Analytics\DashboardController#get_salesthree'));
For security reasons I don't want to pass user input data using route parameters. Also I have multiple user input parameters which needs to send to controller hence above method is not feasible as well. Hence any other alternative solution available in this case?
Controller code snippet:
public function get_salesthree($frmyear, $toyear)
{
return \Response::json(Salethree::get_formatted_salesthree($frmyear, $toyear ));
}
Dropdownlist code snippet:
<label>From Date</label>
<select id="ddlfrmyear" name="frmyear" onchange="check(this);">
<option value="-1">Select Date </option>
#foreach ($date_lists as $date_list)
<option value="{{ $date_list}}">{{ $date_list}}</option>
#endforeach
</select>
JavaScript check function:
function check(sel)
{
document.getElementById('ddltoyear').disabled = !sel.selectedIndex;
var frmyear = document.getElementById('ddlfrmyear').value;
var toyear = document.getElementById('ddltoyear').value;
console.log(frmyear);
console.log(toyear);
if (toyear != '-1')
{
drawChart(frmyear, toyear);
//drawChart();
}
}
Now I am getting check function is not defined after changing ajax call as suggested. I am wondering what it the relation between on-select event of drop-down list and AJAX route?
This is just an example for your understanding, I hope this will guide you to get your functionality.
if you don't want to show your data/parameter in URL, then you can also use Ajax Post,
$.ajax({
type: 'POST'
url: "get_salesthree/",
data: yourForm.serialize()
dataType: 'json'
and in your routes, remove variable for query string, and make it like this.
Route::post('get_salesthree/', array('uses'=>'Analytics\DashboardController#get_salesthree'));
and in your controller
public function get_salesthree(Request $request){
$frmyear = $request->input('frmyear');
$toyear = $request->input('toyear');
//do your functionality as per your need
return \Response::json(Salethree::get_formatted_salesthree($frmyear, $toyear ));
}
Try this jquery answer:
js:
$('form').submit(function(e){
e.preventDefault();
var frmyear = $('#ddlfrmyear').val();
var toyear = $('#ddltoyear').val();
$.ajax({
type: 'POST'
url: "get_salesthree/",
data: {frmyear:frmyear ,toyear:toyear},
dataType: 'json',
success:function(data){
console.log(data);
}});
});
laravel:
Route::post('get_salesthree/', function(Request $request){
$frmyear = $request->input('frmyear');
$toyear = $request->input('toyear');
return \Response::json(Salethree::get_formatted_salesthree($frmyear, $toyear
});
I am new to jquery and am having trouble with the autocomplete function. edit:I should mention I am using MVC with Codeigniter. My AJAX response is returning like this [{"customer_name":"Adecco Management & Consulting S.A."}]. It is also not all in a row it is each character in the dropdown like this
[
{
"
c
u
s
t
and so on. Here is my autocomplete script.
$('#cust_name').autocomplete({
source: function(request,response){
var request = {
toSearch: $('#cust_name').val()
};
$.ajax({
url: '/researchDB/index.php/rdb_con/autoComplete',
data: request,
datatype:"json",
type: 'POST',
success: function(data){
response(data);
}
});
}
});
and my controller:
function autoComplete(){
$data['id'] = $this->rdb_mod->autoComplete();
echo json_encode($data['id']);
}
model:
public function autoComplete(){
$toSearch = $_POST['toSearch'];
$this->db->select('customer_name');
$this->db->like('customer_name', $toSearch, 'after');
$query = $this->db->get('research');
return $query->result();
}
input in view:
<input data-input-type="cust_name" id="cust_name" class="ids form-control search-query " type="text" name="customer_name">
I am not sure I set up the jquery function correctly but the response includes the desired results, in the wrong format, when I type in the input. Thanks for any help you can give!
I received the answer outside of SO and want to post the solution here for others.
controller: I needed to put the results into an array and pass that to the ajax response as one object.
function autoComplete(){
$data['id'] = $this->rdb_mod->autoComplete();
$results = array();
foreach($data['id'] as $row){
$results[]=$row->customer_name;
}
echo json_encode($results);
}
jquery: As far as I understand this section, I wasn't making use of the built in functions and therefore overwriting the request variable that autocomplete sets up.
$('#cust_name').autocomplete({
source: function(request,response){
$.ajax({
url: '/researchDB/index.php/rdb_con/autoComplete',
data: request,
datatype:"json",
type: 'POST',
success: function(data){
var items = JSON.parse(data);
response(items);
}
});
}
});
model: didn't change much. I added distinct to limit dup values.
public function autoComplete(){
$toSearch = $_POST['term'];
$this->db->distinct();
$this->db->select('customer_name');
$this->db->like('customer_name', $toSearch, 'after');
$query = $this->db->get('research');
return $query->result();
}
Thanks to all those who helped me with this!
I have a CodeIgniter MVC application.
I have a model called city that has a method:
<?php
class Cities_model extends Model{
function Cities_model(){
parent::Model();
}
function get_cities($id = null){
$this->db->select('id, city_name');
if($id != NULL){
$this->db->where('country_id', $id);
}
$query = $this->db->get('cities');
$cities = array();
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->id] = $city->city_name;
}
return $cities;
}else{
return FALSE;
}
}
...
Controller:
function Post(){
$this->load->helper('form');
$this->load->model('cities_model');
$this->load->model('country_model');
$this->load->model('field_model');
$data['cities'] = $this->cities_model->get_cities();//optional $id parameter
$data['countries'] = $this->country_model->get_countries();
$data['fields'] = $this->field_model->get_fields(); //subject field
$this->load->view('post_view',$data);
}
This method is used to fill the contents of a dropdown list. I have a similar model for countries, which also has a dropdown.
You can see that the get_cities method is set up to accept a country_id. This would be used to filter the results if a country was selected.
My question is I need help calling this method using Ajax (preferably jQuery). I'm new to ajax and have never done anything like this before.
Any help most appreciated!
Billy
UPDATE
I've added jquery library and have created method in my controller:
function get_cities($country){
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode(array($this->cities_model->get_cities($country))));
}
here is my javascript on my view:
<script type="text/javascript">
$(document).ready(function(){
$('#country').change(function(){
var country_id = $('#country').val(); // here we are taking country id of the selected one.
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>home/get_cities/"+country_id,
data: ({country : country_id}),
success: function(cities){
$.each(cities,function(i,city)
{
var opt = $('<option />');
opt.val(city.value);
opt.text(city.text);
$('#cities').append(opt);
});
}
});
});
});
This is the json reply:
[{"2":"Accra"}]
So it is successfully retriving the correct data. the only problem is it's adding blank values/text to the drop down. and each time I change the city the data is being added on, so I guess i'd have to clear the dropdown first?
extending Alpesh's answer:
you should have a controller's function which return cities filtered by country:
/controller/get_cities/<country>
i'm assuming that your controller's function will return a json object, you can obtain it by doing:
function get_cities($country)
{
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode(array($this->cities_model->get_cities($country))));
}
then on the view you'll have 2 select boxes:
one filled up with the contries
one empty and to be filled up with the cities retrived via ajax
now, you have to write something like Alpesh did in order to retrive the cities of the selected country; URL will be
url: '/controller/get_cities/'+country_id
while the success function would be something like
success: function(cities)
{
$('#cities').empty();
$.each(cities,function(i,city)
{
var opt = $('<option />');
opt.val(city.value);
opt.text(city.text);
$('#cities').append(opt);
});
}
UPDATE
in your ajax success function you are dealing with a json objects, infact you are doing this:
opt.val(city.value);
opt.text(city.text);
where city is a json object and value and text are its properties.
when you generate the json via php you have to respect what you use in jquery so your model should return an array like this:
array
(
array("value"=>"2","text"=>"Accra"),
array("value"=>"3","text"=>"Kumasi"),
....
);
the json_encode that array and it should work. Maybe you don't need to wrap the model call into an array but i'm not sure depens on how you return the array
echo(json_encode(array($this->cities_model->get_cities($country))));
or
echo(json_encode($this->cities_model->get_cities($country)));
You can do it this way by jquery -
lets say you have 'country' as an id for the select for country -
then on change of country you can bring it's specific cities as follows -
$(document).ready(function(){
$('#country').change(function(){
var country_id = $('#country').val(); // here we are taking country id of the selected one.
$.ajax({
type: "POST",
url: "the url you want to call",
data: ({id : country_id}),
success: function(cities){
//populate the options of your cities dropdown here.
}
});
});
});
you can refer detailed documentation here -
JQuery
Ajax API
Ajax