Multi select with select2 and ajax laravel resource - laravel

For my series form, I need to have all the actors ready for a selection. I have a lot of actors and I need to get them with an api.
I made a Actor Resource :
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class ActorResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
// return parent::toArray($request);
return [
'id'=> $this->id,
'name'=> $this->name,
];
}
}
With routes :
Route::get('/actor', function () {
return ActorResource::collection(Actor::all());
});
Route::get('/actor/{actor}', function (Actor $actor) {
return new ActorResource($actor);
});
In my blade :
<label for="creators" class="label">Créateur</label>
<select class="form-control tags-selector" id="creators" name="creators[]" multiple="multiple">
</select>
<script>
$(document).ready(function() {
$('.tags-selector').select2({
minimumInputLength: 2,
ajax: {
url: '/api/actor',
dataType: 'json',
delay: 250,
},
});
});
</script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/js/select2.min.js"></script>
Nothing is working... And how can I get the selected value after ?
Is this the right way to do a multi select with a big table ?

$(document).ready(function() {
$('.tags-selector').select2({
minimumInputLength: 2,
$.ajax: {
method:'get'// I am assuming this is a get method
url: '/api/actor',
dataType: 'json',
delay: 250,
success: function (data) {
console.log(data)//after you see the structure of data, try smt like
//this. You should change this part acording yo your data
for(int i =0;i<data.data.lenght;i++){
$("#creators").append(new Option(data.data[i].name, data.data[i].id));
}
},
error: function (error) {
console.log(error);
},
},
});
});
Well,I hope that will help you. I am also not the expert of them. Let me know if its works or not
Update
<html >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="box" onkeydown="asd()" />
<select name="asd" id="select_box">
</select>
<script>
function asd() {
var data = {"data":[{"id":50,"name":"Alec"},{"id":51,"name":"Recep"},{"id":52,"name":"Aecep"}]};
$("#box").on("keyup", function(){
$('#select_box').empty();
var search_text = $("#box").val().toLowerCase();
data_value = data.data[0].name.substring(search_text.length).toLowerCase();
for (var i=0; i<data.data.length; i++) {
if(search_text === data.data[i].name.substring(0,search_text.length).toLowerCase()){
$("#select_box").append(new Option(data.data[i].name, data.data[i].id));
}
}
});
}
</script>
</body>
</html>
This code is working. Change the variables properly for your project

Related

ajax not return anything when checkbox is checked

I have a list of manufacturers with checkbox when i checkbox is checked ajax is called and hit the controller but not return anything
I am using laravel 5.1
#foreach($manufacturers as $leedsManufacturer) {{-- #foreach($leedManufacturers as $leedsManufacturer) --}}
<div class="post" id="post{{$leedsManufacturer['mfgg_id']}}">
<label class=" my-checkbox gry2" id="manufacturer">{{str_limit($leedsManufacturer['mfgg_name'], 300)}}
<input type="checkbox" class="manufacturer common_selector" name="manufacturer[]" value="{{$leedsManufacturer['mfgg_id']}}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<span class="checkmark"></span>
</label>
</div>
#endforeach
#endif
script
$(document).ready(function() {
filter_data();
function filter_data() {
var manufacturer = get_filter('manufacturer');
// var products = get_filter('products');
// var chps_approved = get_filter('chps_approved');
$.ajax({
url: "{{url('ajax1')}}",
method: 'POST',
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
data:{manufacturer:manufacturer} ,
success:function(data){
console.log(data);
}
});
// alert(manufacturers);
}
function get_filter(class_name) {
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
alert(filter);
// return filter
}
$('.common_selector').click(function(){
filter_data();
});
});
controller
public function ajax1(Request $request){
$data= $request->manufacturer;
return response()->json($data);
}
On checkbox select, it should return the ID so i can use it in controller. but $request->manufacturer show this on console.
try this lets see if you are getting the id from the form. i use javascript alert
$(document).ready(function() {
filter_data();
function filter_data() {
var manufacturer = get_filter('manufacturer');
alert(manufacturer);
// var products = get_filter('products');
// var chps_approved = get_filter('chps_approved');
$.ajax({
url: "{{url('ajax1')}}",
method: 'POST',
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
data:{manufacturer:manufacturer} ,
success:function(data){
console.log(data);
}
});
// alert(manufacturers);
}
function get_filter(class_name) {
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
alert(filter);
// return filter
}
$('.common_selector').click(function(){
filter_data();
});
});

laravel search - returning all results even if no match and make delay to ajax

I have a problem with my search.
Problem 1
Currently if I type in the field it is searching however the search never ever stops, so if I type hello, it will make about 500 requests within a minute.
Problem 2
I am searching in film table to find matching 'title' as well as find business name corresponding to business_id in business table.
Problem 3
Each time request is made it brings back master page again i.e. loading all js and css (which might be why it is making so many requests?) but if I don't extend master, result blade doesn't work.
however even if I input 'e' it brings me back 'guardians of the galaxy' which doesn't have 'e' My thoughts are that it is searching throught business table as well somehow. They have both eloquent one to one relationships
Controller:
public function cinema_search($cinema_value) {
$cinema_text = $cinema_value;
if ($cinema_text==NULL) {
$data = Film::all();
} else {
$data = Film::where('title', 'LIKE', '%'.$cinema_text.'%')->with('business')->get();
}
return view('cinemasearch')->with('results',$data);
}
Form::
<form id="cinema_display">
<div class="form-group">
<input type="text" class="form-control" id="search_cinemas" onkeyup="search_cinema(this.value);" placeholder="Search film">
</div>
<div id="show"
</div>
</div>
</form>
ajax:
function search_cinema(cinema_value) {
$.ajax({
url: '/cinemasearch/' + cinema_value,
type: 'post',
dataType: 'html',
success: function(data) {
$('#show').append(data);
$('.se-pre-con').fadeOut('slow', function () {
$(".container").css({ opacity: 1.0 });
});
},
error: function(data) {
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
cinemasearch.blade(results):
#extends('master') #section('title', 'Live Oldham') #section('content')
#section('content')
<table style="width:100%">
#if (isset($results) && count($results) > 0)
#foreach( $results as $film )
<tr>
<td>{{ $film->business->name }}</td>
<td>{{ $film->title }}</td>
<td>{{ $film->times}}</td>
</tr>
#endforeach
#endif
</table>
#endsection
function search_data(search_value) {  
$.ajax({
        url: '/searching/' + search_value,
        type: 'post',
        dataType: 'html',
        success: function(data) {
            $('#show_search_result').append(data);
            $('.se-pre-con').fadeOut('slow', function () {
$(".container").css({ opacity: 1.0 });
            });
        },
        error: function(data) {
            $('body').html(data);
        },
        headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        }
    });
}
function tram_stops(tram_value) {
    $.ajax({
        url: '/tramsearch/' + tram_value,
        type: 'post',
        dataType: 'html',
        success: function(data) {
            $("#display").html(data);
            var tram_value = tram_value;
        },
        error: function(data) {
            
        },
        headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        }
    });
}
/*
setInterval(tram_stops, (30 * 1000));
*/
function search_cinema(cinema_value) {
    $.ajax({
        url: '/cinemasearch/' + cinema_value,
        type: 'post',
        dataType: 'html',
        success: function(data) {
                var items = JSON.parse(data);
                var showElement = $('#show');
                showElement.html('');
                $.each(data, function() {
                   showElement.append(this.title +' '+ this.times+'<br />');
                });
        },
        error: function(data) {
        },
        headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        }
    });
}
You are returning the wrong response type from cinema_search. Ajax expects a JsonResponse, not what the view helper returns which is \Illuminate\Http\Response. Put your search results in:
return response()->json(['results' => $data]);
to start with if you just want the data. If you want to actually return the rendered view file, you would need to do:
return response()->json(['results' => view('cinemasearch')->with('results',$data)->render()]);
then inject that into your DOM. The problem with rendering server side is nothing is bound client side so if you have any interaction requiring JS, you'll need to create those manually in your success callback.
Problem 1:
Remove the keyUp event in your html and add an event in Jquery.
Your HTML structure is not correct
This:
<form id="cinema_display">
<div class="form-group">
<input type="text" class="form-control" id="search_cinemas" onkeyup="search_cinema(this.value);" placeholder="Search film">
</div>
<div id="show"
</div>
</div>
</form>
Should be:
<form id="cinema_display">
<div class="form-group">
<input type="text" class="form-control" id="search_cinemas" onkeyup="search_cinema(this.value);" placeholder="Search film">
<div id="show">
</div>
</div>
</form>
Then again you should consider to remove the onkeyup event. And change add it in Jquery to something like this:
Problem 2 & 3: I would recommend a raw Query and return an json instead of a view. And you shouldn't check if($cinema_text === NULL) this won't be the case ever. Unless you put NULL in your url and even then it will be an String and not NULL and if('NULL' === NULL) returns false look at this post for the diff of == and ===.
public function cinema_search($cinema_value) {
$cinema_text = $cinema_value;
if (empty($cinema_text)) {
$data = Film::all();
} else {
$data = DB::select('*')
->from('films')
->join('businesses', 'businesses.id', '=', 'films.business_id')
->where('films.title', 'LIKE', '%'.$cinema_text.'%')
->orWhere('bussiness.title', 'LIKE', '%'.$cinema_text.'%')
->get();
}
return response()->json(['results' => $data]);
}
Then in your JavaScript do something like this:
$( document ).ready(function() {
console.log( "ready!" );
$( "#search_cinemas" ).change(function() {
search_cinema(this.value);
console.log( "New value"+this.value+"!" );
});
function search_cinema(cinema_value) {
console.log('setup ajax');
$.ajax({
url: '/cinemasearch/' + cinema_value,
type: 'post',
success: function(data) {
console.log('success!');
var showElement = $('#show');
showElement.html('');
$.each(items, function() {
showElement.append(this.title +' '+ this.times+'<br />');
});
},
error: function(data) {
console.log(data);
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
});

Laravel Select2 Box not filtering

in my Laravel 5.4 app I want to use Select2 to filter for my "Providers" like that:
https://paste.laravel.io/RowKK
The Select2 Box show the correct content but when I start typing the name of a Provider it doesn't filter the correct items.
When using the same on the example pages, this is working.
Any ideas what I make wrong?
Regards
kay899
It will still be your API backend that will do the filtering, all you have to do is to pass the query term via data property in your ajax. Example the params.term was passed to a q property and pulled from the API backend.
Example GitHub Repositories pulling:
function formatRepo (repo) {
if (repo.loading) return repo.text;
return repo.full_name
}
function formatRepoSelection (repo) {
return repo.full_name || repo.text;
}
$(".js-data-example-ajax").select2({
placeholder: 'Select an item',
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// notice we return the value of more so Select2 knows if more results can be loaded
//console.log(data.items)
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>
<select class="js-data-example-ajax" style="width:500px;">
<option selected="selected"></option>
</select>

i am not getting pie chart using codeigniter

I want a pie chart of expenses in percentage,my code is below, when i run the code it is not displaying nothing.please help.if possible please correct the code. i am really confused,only blank page is coming.
my controller chart
class Chart extends CI_Controller {
function chart() {
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->model('chart_m');
$this->load->library('session');
}
public function index()
{
$data['pie'] = json_encode($this->chart_m->selectexpenses());
$this->load->view('home',$data);
}
}
model chart_m
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Chart_m extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
function selectexpenses()
{
$results = $this->db->query("SELECT expenses from myTable");
return $results->result_array();
}
}
my view page home.php
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<head><script>
$(document).ready(function () {
$(function () {
var chart;
// Build the chart
$('.widget-lower-left#widget').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'expenses'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'expenses',
data: []
}]
});
});
function requestData() {
$.ajax({
url:'<?php echo base_url().'index.php/chart'?>',
datatype: "json",
success: function(data) {
alert(data);
console.log(data);
var newData = [];
for( var i = 0, len = data.length; i < len; i++ ) {
var item = data[i];
for(var j in item){
newData.push([j,item[j]]);
}
}
chart.series[0].setData(newData);
</script>
},
cache: false
});
};
});
////////////////////////
May be You should Try This..
RewriteEngine on
RewriteCond $1 !^(index\.php|public|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
The controller is like
<?php
class Charts extends Controller {
public function __construct() {
parent::__construct();
$this->load->library('FusionCharts');
}
public function index() {
$this->load->view('charts_index');
}
public function getData($year='2010') {
// Instantiate the FusionCharts object
$FC = new FusionCharts();
// specify the graph parameters
$strParam="caption=Quarterly Sales for ".$year.";xAxisName=Quarter;yAxisName=Revenue;numberPrefix=$;decimalPrecision=0;formatNumberScale=1";
$FC->setChartParams($strParam);
// specify the data bsaed on the $year parameter
if ($year=='2010') {
$FC->addChartData("40800","name=Q1");
$FC->addChartData("31400","name=Q2");
$FC->addChartData("26700","name=Q3");
$FC->addChartData("54400","name=Q4");
} else {
$FC->addChartData("800","name=Q1");
$FC->addChartData("400","name=Q2");
$FC->addChartData("700","name=Q3");
$FC->addChartData("200","name=Q4");
}
// output the FusionCharts XML
print $FC->getXML();
}
}
?>
and the view is like this
<html>
<head>
<title>Dynamic Graphs with JQuery and FusionCharts</title>
<script language="JavaScript" src="/public/js/FusionCharts.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script language="JavaScript">
function drawChart(chartSWF, strXML, chartdiv) {
//Create another instance of the chart.
var chart = new FusionCharts(chartSWF, "chart1Id", "400", "300", "0", "0");
chart.setDataXML(strXML);
chart.render(chartdiv);
}
function updateChart() {
//call the CI data url
$.get('/charts/getData/'+$('#changeData').val(), function(data) {
if ($('#changeChart').val()==='3d') {
drawChart("/public/fscharts/FCF_Column3D.swf", data,"chart1div");
} else {
drawChart("/public/fscharts/FCF_Column2D.swf", data,"chart1div");
}
});
}
$(document).ready(function(){
//create the chart initially
$.get('/charts/getData/', function(data) {
drawChart("/public/fscharts/FCF_Column3D.swf", data, "chart1div");
});
//update the chart if the dropdown selection changes
$('#changeChart').change(function() {
updateChart();
});
$('#changeData').change(function() {
updateChart();
});
});
</script>
</head>
<body>
<select name="changeData" id="changeData">
<option value="2010" selected>2010</option>
<option value="2009">2009</option>
</select>
<select name="changeChart" id="changeChart">
<option value="3d">3D Version</option>
<option value="2d">2D Version</option>
</select><br>
<div id="chart1div" align="left">The chart will appear within this DIV. This text will be replaced by the chart.</div>
</body>
</html>
hope this will help you other wise visit this site...
Click ON this for More Help

ng-grid in from tag with run at server in aspx page

i am calling the ajax function on click of button it returns the json data and i am passing the data to the main.js script file(controller) its getting the data and binding the data to the ng-grid, the question here is whne i put the ng-grid in the from tag it does not dispaly the data
<script type="text/javascript">
$(document).ready(function () {
$("#mybutton").click(function () {
var scope = angular.element(document.getElementById("wrap")).scope(); // to get access all the varibales defined in the contoller
scope.$apply(function () {
$.ajax({
type: "POST",
url: "Website/Nggrid.asmx/GetDataForNgGrid",
success: function (result) {
// console.log(result);
var fd = JSON.parse(result); //parsing the json string
scope.updateMessage(fd);
alert("hi");
},
error: function (xmlhttprequest, Status, thrownError) {
alert(thrownError.toString());
alert(thrownError);
}
});
});
});
});
</script>
this is the function i am calling when the user clicks on button
<body ng-controller="MyCtrl">
<%--<form id="form1" runat="server">--%>
<div id="wrap" class="gridStyle" ng-grid="gridOptions">
</div>
<button id="mybutton">
Try it</button>
<%-- </form>--%>
</body>
this is the main.js
var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function ($scope) {
$scope.myData = [];
$scope.updateMessage = function (_s) {
$scope.myData = _s;
// $scope.Enable = true;
};
$scope.gridOptions = {
data: 'myData',
columnDefs: [
{ field: 'Status', displayName: 'Status', width: "*" }
]
};
});
my question is here that when i put ng-grid in the from tag it wont show the data, please give the suggestion on this
<form id="form1" runat="server">
<div id="wrap" class="gridStyle" ng-grid="gridOptions">
</div>
<button id="mybutton">
Try it</button>
</form>

Resources