Laravel: how to send selectedIndex to a controller by Ajax - php

What wants to be achieved ?
On-change the selection of a Select list, this selectedIndex is picked up by the controller, sent to the model the SQL query and results are returned via ajax underneath the select list. That is very easy to do in an ordinary php environment, but I am puzzled within the Laravel environment.
If it is not clear: what I want is to have this: http://www.w3schools.com/php/php_ajax_database.asp done in a Laravel environment
UPDATED: I have improven the code using the indications of Itachi:
This would be if I could use simple Ajax, but was adviced to use JQUERY/JSON instead, dont know why this would not work.
<script>
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
And then the PHP get stuff etc, would be easy.
So, the JQUERY/JSON would go more or less like this, though I dont know how to complete it
$('#ajax').submit(function(e){
$.ajax({
url: '<?php echo route("hint");?>',
type: 'POST',
data: { especialidades: $('especialidades').val() },
dataType: 'json',
success: THIS WOULD BE A FUNCTION THAT WOULD PRINT THE RESULTS FROM THE CONTROLLER
}
});
e.preventDefault();
});
And my own form looks like this:
<form role="form" class="bg-success" id="ajax">
<div class="form-group">
<select name ="especialidades" id = "especialidades" class="form-control" onchange="showHint(this.value)">
<?php foreach($data['kategori'] as $detalle): ?>
<option value="<?php echo $detalle->id_specialty; ?>"><?php echo $detalle->spec_description; ?></option>
<?php endforeach;?>
</select>
</div>
</form>
<div id="txtHint"><b>Person info will be listed here.</b></div>
And the controller should look like this:
class Hint extends BaseController{
public $restful = true;
public function post_appajax()
{
NEED TO GET THE SELECTED INDEX SENT BY THE JQUERY SCRIPT IN THE VIEW: HOW??
SOMETHING EQUAL TO THIS ===> ::json(Input::get('especialidades'));
}
}
AND THE ROUTE FILE GOES LIKE THIS: (by Itachi)
Route::post('hint', array(
'as' => 'hint',
'uses' => 'Hint#getHint'
));

it is actually very simple.
Routes.php
Route::post('hint', array(
'as' => 'hint',
'uses' => 'HintController#getHint'
));
HintController.php
class HintController extends BaseController {
public function getHint()
{
return Response::json(//whatever you want);
}
}
View
$.ajax({
url: '<?php echo route("hint");?>', //<-------- see this
type: 'POST',
data: { especialidades: $('especialidades').val() },
dataType: 'json',
success: SEND IT TO THE CONTROLER HOWEVER YOU CAN...
}
});
Rest will be upto you.

According to the method name in your controller the route should be (Laravel-3:RESTfull controller)
Route::post('hint', array( 'as' => 'hint', 'uses' => 'Hint#appajax'));
Your Controller
class Hint extends BaseController{
public $restful = true;
public function post_appajax()
{
// ...
}
}

Related

Pass parameters to a controller from the View by using ajax and controller pass the new eloquent to the view

This is how my Controller and View work
Controller
class DayhomeController extend Controller{
public function index(){
$Dataset = Modal::all();
return view('DayHome')->with('DataSet',$DataSet)
}
View
<div class="container" id="container1">
<input type="date" id="datepicker" name="datepicker" value="<?php echo date('Y-m-d'); ?>"
</div>
#for ($i = 0; $i < count($DataSet); $i++)
<div class="container" id="container2">
<div> {{$DataSet[$i]->name}} </div>
<div> {{$DataSet[$i]->number}} </div>
</div>
#endfor
<script type="text/javascript">
$('#datepicker').on('change', function() {
var datepicker = $('#datepicker').val();
alert(datepicker);
$.ajax({
url: '/orderdata',
data: datepicker,
type: "get",
cache: false,
success: function () {
$('#something').empty();
$('#something').append();
},
error: function () {
;}});});
</script>
Route
Route::get('/orderdata', 'DayhomeController#OrderDataorIndex');
1.I would like to ask if I use ajax to pass the datepicker value to the controller, should I pass it to the index or create another public function OrderData($Request $datepickerVal){} ? because I need to use the value of the datepicker as a condition to retrieve the modal update Dataset[i] again.
2.The data enters function index or function OrderData, and finally returns a new dataset[], will this help me refresh the page, or should I do something like $('#something').empty $('#something').append() in ajax success:function to update my object and its {{$DataSet[$i]->name}} {{$DataSet[$i]->number}} number?
You have 3 ways to accomplish this
Page reload
Reload the page and send query string in the url eg: "/yourpath?date=" + $date, then in your controller:
window.location.href = 'https://your.url/path?date=' + $('#datepicker').val();
class DayhomeController extend Controller{
public function index(){
$Dataset = Modal::all();
if(request()->get('date')){
$Dataset = $Dataset->where('date',request()->get('date'))
}
return view('DayHome')->with('DataSet',$DataSet)
}
Ajax return HTML
you could make a controller+page/view that only returns the HTML of your rendered data set.
then you can call this route/controller and just replace the html with jQuery:
$.ajax({
url: '/orderdata',
data: datepicker,
type: "get",
cache: false,
success: function (htmlReceived) {
$('#something').html(htmlReceived);
},
});})
Ajax + javascript rendiner library
you could also always get the Data set via ajax and instead create your render method locally using, react, alpineJS, svelte, vue or any other frontend rendering library or framework
*** This code does not follow best practises but tries to explain your problem

How to send dropdown selected value through ajax call to controller in laravel

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>

AJAX JSON and routing in cakephp

I am trying to implement a search module by using AJAX.
There is an index.ctp file in my Items Controller and I have linked my index.ctp file of Items to my search.ctp file which is present under Pages controller as below:
<li><?= $this->Html->link(__('Search Products'),['controller'=>'Pages','action' => 'search']) ?></li>
For the search.ctp pages the URL displayed is :
http://onlineelectronic.com/pages/search
In my search.ctp file the code is as follows:
<head>
<title> Search Results</title>
<?php echo $this->Html->script('//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js', array('inline' => false));?>
<script type="text/javascript">
$(document).ready(function() {
$("#Submit1").click(function () {
$.ajax({
type: 'post',
url: '/Items/searchData",
data: {
name: "search"
},
beforeSend: function(){
$("#resultField").html("Loading...");
},
success: function(response) {
jQuery('#resultField').val(response);
},
error: function(response, error) {
alert("Search :Error"+response.error());
},
dataType: 'json',
global: false
});
return false;
});
});
</script>
</head>
<div>
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __('Search Item') ?></legend>
<?php
echo $this->Form->input('search',['label'=>'Search']);
?>
</fieldset>
<?= $this->Form->button('Search Items',['label'=>'Submit1']); ?>
<?= $this->Form->end() ?>
</div>
<div id="resultField">
</div>
In my ItemsContoller page the searchData method is implemented like this:
class ItemsController extends AppController
{
public $helpers = ['Form', 'Html', 'Time'];
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
public function search(){
//dummy
}
/**
*obtains search result for a given string.
*/
public function searchData()
{
$this->layout = 'ajax';
echo "here";
$search_data=[];
var_dump($search_data);
//$search_results = [];
if ($this->request->is('post')) {
$search_data= $this->request->data;
$search_data=implode("|",$search_data);
$search_results = $this->Items->find('all', array('conditions'=>array('Items.itemName LIKE'=>"%$search_data%")));
if(!empty($search_results)) {
$this->set(compact($search_results));
$this->set('_serialize',array('search_results'));
return json_encode($search_results);
}
}
}
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow(['index', 'view','search','searchData']);
}
}
My issue is that the SearchData method is not being called and I am not getting any javascript errors also.How do i make sure that the method gets called on pressed after pressing the button.Is it due to the url in json?
I see 2 possible problems. First in ItemsController, you have to allow searchData method
// change this line
$this->Auth->allow(['index', 'view','search']);
// to this
$this->Auth->allow(['index', 'view','searchData']);
also make sure, that you have proper jQuery selector
// try to change this line
<?= $this->Form->button('Search Items',['label'=>'Submit1']); ?>
// to this
<?= $this->Form->button('Search Items',['id'=>'Submit1']); ?>
Edit: make more corrections to javascript:
Data passed with ajax should be double quoted
data: {
name: "search"
},
add return false; to the end of click handler, so you prevent submiting form and reloading page
Also note that you must have template for searchData in Template/Items/search_data.ctp

laravel 5 simple ajax retrieve record from database

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"

ajax demo for laravel, step by step

I think this code has a lot of errors. What i need is to create a form, do a XHR submit to the controller, get the data, send to model, check the validations, return to controller with the output of validation and then sent to the view the message "errors or success"
routes.php
Route::get('checkValidationEmail', 'HomeController#checkValidationEmail');
<?php
echo Form::open(array('url' => 'checkValidationEmail', 'class' => 'form_notify'));
echo Form::text('Email', Input::old('Email'), array('placeholder'=>'Email', 'class' => 'hg'));
echo Form::close()
?>
Notify Me!
ok, this works fine, next, the problems begin.
AJAX
<script>
$(function () {
$(".send_email").click(function () {
email = $('.hg').val();
$.ajax({
type: "POST",
url: 'checkValidationEmail', //what is the correct url?
data: {
email: email
}
}).done(function (msg) {
alert(msg);
});
});
});
</script>
500 error:
{"error":{"type":"Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException","message":"","file":"C:\\VertrigoServ\\www\\laravel\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php","line":1439}}
Controller
class HomeController extends BaseController {
public function checkValidationEmail() {
//how to get the data from form and pass to the model, more exactly validate($input)
if ($validation) {
return true;
}
else {
return 'incorrect email'; //how send this message to the view?
}
}
}
Model
class Home extends Eloquent {
protected $table = 'emails';
public function validate($input) {
//validations
}
}
In your route you are defined the checkValidationEmail as GET request and from your ajax, you are trying to access this as a POST request. So this will throw MethodNotAllowedHttpException. So you have to change your route from,
Route::get('checkValidationEmail', 'HomeController#checkValidationEmail');
To,
Route::post('checkValidationEmail', 'HomeController#checkValidationEmail');
Or,
Route::any('checkValidationEmail', 'HomeController#checkValidationEmail');

Categories