Laravel Select2 Box not filtering - laravel

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>

Related

Multi select with select2 and ajax laravel resource

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

cannot upload file using jconfirm and ajax in codeigniter

My upload process without jconfirm works well, but when I need to use jconfirm library to upload the file, it always says undefined index: myfile.
Here is my code
function upload() {
// body...
$.confirm({
title:'Upload Dental Form',
type:'green',
theme:'material',
content: '<form method="post" id="myform" enctype="multipart/form-data">'
+'<label for="file" id="up"><h3>Select Dental Form</h3></label> <br><br>'
+'<input accept="image/*" type="file" name="myfile" id="myfile" '
+' /> '
+'</form>',
buttons: {
save: {
text:'save',
btnClas: 'btn-blue',
action:function() {
$.ajax({
url:"<?php echo base_url(); ?>Dental/form_upload",
//base_url() = http://localhost/tutorial/codeigniter
method:"POST",
data: $('form').serialize(),
contentType: false,
cache: false,
processData:false,
success:function(data)
{
alert(data);
}
});
}
},
cancel:function() {
}
},
onContentReady: function () {
// bind to events
var jc = this;
this.$content.find('form').on('submit', function (e) {
// if the user submits the form by pressing enter in the field.
e.preventDefault();
jc.$$save.trigger('click'); // reference the button and click it
});
}
});
}
in my controller
function form_upload()
{
echo json_encode(print_r($_FILES["myfile"]["name"]));
}
I'm just echoing for debugging purposes.
The response was undefined index: myfile. Why do I get this error? I have tried using new formData(this) instead of $('form').serialize() but it doesn't work either.

React Tutorial - Page Refreshing after Comments Added

I'm working through the official React tutorial and having a little trouble. When I add a comment I expect the comment to appear in the view, and for a split second it does, but then the page refreshes and the comment's gone.
On a related matter (and really just a request for a little FYI as I'm still learning AJAX), the code is supposed to add the comment to the JSON. I'm presuming that this wouldn't work on the Plunker but is there enough code there to actually update a JSON if the page is live?
Thanks for any help! Plunker link and code follows:
https://plnkr.co/edit/p76jB1W4Pizo0rDFYIwq?p=preview
<script type="text/babel">
// To get started with this tutorial running your own code, simply remove
// the script tag loading scripts/example.js and start writing code here.
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
handleCommentSubmit: function(comment) {
var comments = this.state.data;
// Optimistically set an id on the new comment. It will be replaced by an
// id generated by the server. In a production application you would likely
// not use Date.now() for this and would have a more robust system in place.
comment.id = Date.now();
var newComments = comments.concat([comment]);
this.setState({data: newComments});
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: comment,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
this.setState({data: comments});
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
getInitialState: function() {
return {data: []};
},
componentDidMount: function() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
</div>
);
}
});
var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.data.map(function(comment) {
return (
<Comment author={comment.author} key={comment.id}>
{comment.text}
</Comment>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
});
var CommentForm = React.createClass({
getInitialState: function() {
return {author: '', text: ''};
},
handleAuthorChange: function(e) {
this.setState({author: e.target.value});
},
handleTextChange: function(e) {
this.setState({text: e.target.value});
},
handleSubmit: function(e) {
e.preventDefault();
var author = this.state.author.trim();
var text = this.state.text.trim();
if (!text || !author) {
return;
}
this.props.onCommentSubmit({author: author, text: text});
this.setState({author: '', text: ''});
},
render: function() {
return (
<form className="commentForm" onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Your name"
value={this.state.author}
onChange={this.handleAuthorChange}
/>
<input
type="text"
placeholder="Say something..."
value={this.state.text}
onChange={this.handleTextChange}
/>
<input type="submit" value="Post" />
</form>
);
}
});
var Comment = React.createClass({
rawMarkup: function() {
var md = new Remarkable();
var rawMarkup = md.render(this.props.children.toString());
return { __html: rawMarkup };
},
render: function() {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
<span dangerouslySetInnerHTML={this.rawMarkup()} />
</div>
);
}
});
ReactDOM.render(
<CommentBox url="comments.json" pollInterval={2000} />,
document.getElementById('content')
);
</script>
As you said, your problem is that the information in the json file is static (see last paragraph), so every time the comments are refreshed, you lose the new one. The way you could handle it is using the json file during the first load and then just prevent refreshing them, just adding the new ones to the comment box state (after all this is just a example and you just want to see some eye candy, don't you?).
Checking the browser's console you can see that your AJAX request to store the new file is failing, you cannot update it on Plunker, that file is immutable.

select 2 not calling ajax function in Laravel

view:
<select class="js-data-example-ajax" id="tag_list">
<option value="3620194" selected="selected">select customer</option>
</select>
ajax:
$('#tag_list').select2({
placeholder: 'Enter a tag',
ajax: {
dataType: 'json',
url: '{{ url("api/tags") }}',
delay: 400,
data: function(params) {
return {
term: params.term
}
},
processResults: function (data, page) {
return {
results: data
};
},
}
});
I am using select 2 in Laravel. The ajax function is not calling in the view page. I have placed the ajax code at the bottom of the page. But the ajax function is not calling. But I have checked the data from controller using postman.The data is returning in the controller.

Refresh jQuery datatable table

Been plenty of questions about this but I never found one that worked for me. I have a plain and simple HTML table whos body is being filled with rows from an AJAX call.
Then I want to update the table with DataTable plugin but it does not work.
I have a HTML table that looks like this:
<table id="myTable">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
In my jQuery pageload
$(document).ready(function(){
var oTable = $('#myTable').dataTable({
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
And finally my on dropdownlist change function
$("#dropdownlist").on("change", function () {
$("tbody").empty();
$.ajax({
type: "POST",
url: "#Url.Action("ActionHere", "Controller")",
dataType: "json",
success: function (data) {
$.each(data, function (key, item) {
$("tbody").append("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>");
});
}
})
var oTable = $('#myTable').dataTable(); // Nothing happens
var oTable = $('#myTable').dataTable({ // Cannot initialize it again error
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
The append and so on has been modified to shorten it down, etc so do not focus too much on it.
Basically the question is how to update the table, I can do my AJAX and add new data to the table fine, but the datatable plugin does not update with it.
I've tried other things like
.fnDraw(false);
But it does nothing
While I get an JSON error from
fnReloadAjax()
Any clues on just how to refresh the table?
Try this
Initially you initialized the table so first clear that table
$('#myTable').dataTable().fnDestroy();
Then initialize again after ajax success
$('#myTable').dataTable();
Like this
$("#dropdownlist").on("change", function () {
$("tbody").empty();
$.ajax({
type: "POST",
url: "#Url.Action("ActionHere", "Controller")",
dataType: "json",
success: function (data) {
$.each(data, function (key, item) {
$("tbody").append("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>");
});
}
})
$('#myTable').dataTable().fnDestroy();
$('#myTable').dataTable({ // Cannot initialize it again error
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
DEMO
I Know this is an old post, but I've just investigated about the problem and I find the easiest way to solve it in DataTable man pages: https://datatables.net/reference/api/ajax.reload%28%29
All you need to call table.ajax.reload();
var table = $('#product_table').DataTable({
"bProcessing": true,
"serverSide": true,
responsive: true,
"ajax": {
url: get_base_url + "product_table", // json datasource
type: "post", // type of method ,GET/POST/DELETE
error: function () {
$("#employee_grid_processing").css("display", "none");
}
}
});
//call this funtion
$(document).on('click', '#view_product', function () {
table.ajax.reload();
});
I had done something that relates to this... Below is a sample javascript with what you need. There is a demo on this here: http://codersfolder.com/2016/07/crud-with-php-mysqli-bootstrap-datatables-jquery-plugin/
//global the manage member table
var manageMemberTable;
function updateMember(id = null) {
if(id) {
// click on update button
$("#updatebutton").unbind('click').bind('click', function() {
$.ajax({
url: 'webdesign_action/update.php',
type: 'post',
data: {member_id : id},
dataType: 'json',
success:function(response) {
if(response.success == true) {
$(".removeMessages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
manageMemberTable.ajax.reload();
// close the modal
$("#updateModal").modal('hide');
} else {
$(".removeMessages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
manageMemberTable.ajax.reload();
// close the modal
$("#updateModal").modal('hide');
}
}
});
}); // click remove btn
} else {
alert('Error: Refresh the page again');
}
}
From version 1.10.0 onwards you can use ajax.reload() api.
var table = $('#myTable').DataTable();
table.ajax.reload();
Keep in mind to use $('#myTable').DataTable() and not
$('#myTable').dataTable()

Resources