I am using select2 plugin(ivaynberg.github.io/select2). I am trying to display a dropdown(select). It is getting all the items in data.php as options. However select2 is meant to be autocomplete plugin and should search for the search term a client input, and display the matching results only. At the moment it is displaying all the items and not getting the search results. Sorry for my language
data.php is echoing out this:
[{
"id": "1",
"text": "item1",
"exercise": "blah text"
}, {
"id": "2",
"text": "item2"
}
]
The code is:
$(document).ready(function () {
$('#thisid').select2({
minimumInputLength: 2,
ajax: {
url: "data.php",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return {
results: data
};
}
}
});
});
and the input is:
<input type="hidden" id="thisid" style="width:300px" class="input-xlarge" />
I want to find a clue, I am quite new to this plugin and have spent a day for looking at examples.
select2 will not do AJAX if attached to a standard select form control. It MUST be attached to a hidden input control to load via AJAX.
Update: This has been fixed in Select2 4.0. From Pre-Release notes:
Consistency with standard <select> elements for all data adapters, removing the need for hidden <input> elements.
It can also be seen in function in their examples section.
I guess user2315153 wants to receive multiple remote values, and incorrectly assigning select2() with ajax call to a <select> element.
The correct way to get remote values, is using a normal <input> element, and if is desired multiple values, inform the "multiple" parameter on method call. Example:
<input type="hidden" id="thisid" style="width:300px" class="input-xlarge" />
<script>
$('#thisid').select2({
minimumInputLength: 2,
multiple: true,
ajax: {
...
The <select> element CAN NOT be used to remote values
UPDATE: As of select2 4.0.0, hidden inputs has deprecated:
https://select2.github.io/announcements-4.0.html#hidden-input
This means: Instead of using an input to attrib select2 plugin, use an SELECT tag.
Pay attention: it's easy to use any format of json from your server. Just use "processResults" to do it.
Example:
<select id='thisid' class='select2-input select2'></select>
<script>
$("#thisid").select2({
multiple: true,
closeOnSelect: true,
ajax: {
url: "myurl",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, page) { //json parse
console.log("processing results");
//Transform your json here, maybe using $.map jquery method
return {
results: yourTransformedJson
};
},
cache: (maybe)true
}
});
</script>
I try the code, it works well. I think you not include jquery framework or check the path of js and css.
<!DOCTYPE html>
<html>
<head>
<link href="select2.css" rel="stylesheet"/>
<script src="//code.jquery.com/jquery-latest.min.js"></script>
<script src="select2.min.js"></script>
<script>
$(document).ready(function() {
$('#thisid').select2({
minimumInputLength: 2,
ajax: {
url: "data.php",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return {
results: data
};
}
}
});
});
</script>
</head>
<body>
<input type="hidden" id="thisid" style="width:300px" class="input-xlarge" />
</body>
</html>
I think no need to go with hidden input element. You can give a try, get plain html data from ajax call and set it in and then init select2 resetting method. Here's code snippet
HTML
<select id="select" name="select" class="select2">
<option value="" selected disabled>Please Select Above Field</option>
</select>
Javascript
$.ajax({
type: "POST",
cache:false,
url: YOUR_AJAX_URL,
success: function(response)
{
$('#select').html(response);
}
});
$('#select').select2("val","");
Ajax Response :
<option value="value">Option Name</option>
.
.
.
<option value="value">Option Name</option>
After much reading, I decided to change the select2.js itself.
At line 2109 change it to
this.focusser.attr("id", "s2id_"+this.select.context.id);
If your input tag is as so
<select id="fichier">
Hence your input tag that is searching through the list will have an id of s2id_fichier_search
As far as I know, there shouldn't be a conflict and THIS will allow you to have multiple select2 on the same page and run your functions (including .get, .post) through their events eg.
$(function() {
$('#s2id_fichier_search').keyup(function() {
console.log('Be Practical')
})
}
So this will run like if you were to use
<select id="fichier" onkeyup="console.log('Be Practical')">
In my case, an older version of select2 library was causing the issue, make sure that you include the latest version of js and css in the web page.
Related
I'm trying to use an API to return data for 2 string variables: "_id" and "name". I'm connected correctly because I've tested the error feature by tweaking the API key and I get an error. I don't get that when I put in the correct API. However, what I do get is [Object object].
Here is the ajax code I am using (without the api keys):
$(document).ready(function() {
$("#submit-button").click(function() {
$.ajax({
method: "GET",
url: "myurl",
headers: { "x-api-key": "myapikey" },
data: $("#cdn :input").serialize(),
dataType: "json",
success: function(data){
$(".result").text(data);
},
error: function(d) {
$(".result").html(d.responseText);
}
});
});
});
And here is the HTML:
<html>
<body>
<div id="cdn">
<div>
<button id="submit-button">Submit</button>
</div>
<div class="result"></div>
</body>
</html>
Any help you can offer would be greatly appreciated. I need to be able to get the responses displayed.
The variable "data" in your "success" function is actually a json object.
So you need to get the property in that object.
Let's say the response from the server has a property named "name"
you would have to do this:
$(".result").text(data.name);
I can't find a working solution for this problem:
I want to update a part of my view without reloading it,
I have a form that collects the data to be passed to the controller,
the controller needs to get the data from the DB and spit out a JSON
to the view so that it can be filled with such data.
I tried to adapt this http://tutsnare.com/post-data-using-ajax-in-laravel-5/ but it's not working at all. The data collected is not reaching the controller.
My uderstanding is the javascript part in the view should listen to the click event and send a GET request to the controller, the controller checks if the data is sent through AJAX, gets the data from DB then returns the response in JSON form, the view is then updated.
Please, does anyone have a working example or can explain?
Simple working example using JQuery:
In you routes.php file:
Route::post('/postform', function () {
// here you should do whatever you need to do with posted data
return response()->json(['msg' => 'Success!','test' => Input::get('test')]);
});
and in your blade view file:
<form method="POST" action="{{ url('postform') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<input type="text" name="test" value="" />
<input type="submit" value="Send" />
</form>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function ($) {
$(document).ready(function()
{
var form = $('form');
form.submit(function(e){
e.preventDefault();
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: form.serialize(),
success: function(data)
{
console.log(data);
if(data.msg){
alert( data.msg + ' You said: ' + data.test);
}
}
})
});
});
});
</script>
As you can see, most of the logic is done in JavaScript which has nothing to do with Laravel. So if that is not understandable for you, I'd recommend to look for jQuery ajax tutorials or rtfm :)
I have experienced submitting a modal form without reloading the entire page. I let the user add option to the dropdown and then repopulate the items on that dropdown without reloading the entire page after and item is added.
you can have custom route to your controller that handles the process and can be called by javascript and will return json
Route::get('/profiles/create/waterSource',function(){
$data = WaterSource::orderBy('description')->get();
return Response::json($data);
});
then the javascript
<script>
$(document).on('submit', '.myForm-waterSource', function(e) {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(html) {
$.get('{{ url('profiles') }}/create/waterSource', function(data) {
console.log(data);
$.each(data, function(index,subCatObj){
if (!$('#waterSource option[value="'+subCatObj.id+'"]').length) {
$('#waterSource').append('<option value="'+subCatObj.id+'">'+subCatObj.description+'</option>');
}
});
$('#myModal-waterSource').modal('hide');
$('#modal-waterSource').val('');
});
}
});
e.preventDefault();
});
</script>
You can view the full tutorial at Creating new Dropdown Option Without Reloading the Page in Laravel 5
i would like to know if it is possible to make a file upload form and send the data via ajax with symfony2 ?
here is my twig view:
<form class="upavatar" method="post" action="{{ path('sbcUserBundle_avatar', {'id': app.security.getToken().getUser().getId()}) }}" {{ form_enctype(form) }}>
{{ form_end(form) }}
{{ form_errors(form) }}
</form>
</div>
<script>
$('.upavatar').submit(function()
{
$.post($(this).attr('action'), $(this).serialize(), function(data) {
$("#upmyavatar").empty();
$("#upmyavatar").html(data);
});
return false;
});
</script>
Because i did a form upload file within symfony2 and without ajax (jquery actually) it works like a charm, but when i try to send it trough ajax the form handler can't find the file variable (i checked with xdebug).So i'am starting to wonder if it's possible to send a file via ajax within symfony2, in the past i successfully used ajax for "normal" form.
Thanks.
ok i got it working by doing that:
<script>
$('#myForm').live('change', function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$(".myavatarupload").empty();
$(".myavatarupload").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
$("#message").html("<font color='red'> ERROR</font>");
}
};
$("#myForm").ajaxForm(options);
});
</script>
I am trying to import a file with AJAX, using the following plugin -
http://malsup.github.com/jquery.form.js
Based on the following example -
http://malsup.com/jquery/form/progress.html
The my View looks like this -
<form action="/MyController/MyAction" enctype="multipart/form-data" id="myFormId" method="post">
<input type="file" name="file" id="file">
<input type="submit" value="Import File"> </div>
</form>
<script type="text/javascript">
window.onload = function () {
(function () {
$('#myFormId').ajaxForm({
beforeSend: function () {
alert('before send');
},
success: function () {
alert('success');
},
complete: function (xhr) {
alert('xhr.responseText=' + xhr.responseText);
}
});
})();
}
</script>
The javacsript in window.onload = function (){} is never called. MyAction is called, and then the browser just displays the JSON Action Result of MyAction.
Can anyone tell me what I am doing wrong or suggest a different way of doing this?
Thanks very much!
Since the script you wrote is placed after the form, you don't need to be putting it in a window.onload handler. The following should work fine:
#using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, new { enctype = "multipart/form-data", id = "myFormId" }))
{
<input type="file" name="file" id="file">
<input type="submit" value="Import File"> </div>
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
(function ($) {
$('#myFormId').ajaxForm({
beforeSend: function () {
alert('before send');
},
success: function () {
alert('success');
},
complete: function (xhr) {
alert('xhr.responseText=' + xhr.responseText);
}
});
})(jQuery);
</script>
Also notice that it is important to make sure that jquery.js is included before the jquery.form.js plugin which needs to be included before the script using it. In the example I have shown I also passed jQuery as parameter to the anonymous function which was being used in order to ensure that there are no conflicts with other plugins you might be using and which might have hijacked the $ function.
Also I would recommend you using a javascript debugging tool such as FireBug or Chrome developer toolbar to ensure that all your scripts are properly included (no 404s) and that you do not have any duplicate scripts or javascript errors.
I am trying to use the type-ahead feature from bootstrap to populate a search bar dropdown using an AJAX call.
I saw some posts about it, but the best answer didn't solve my issue.
I get a TypeError: a is undefined from jquery.min.js (v1.8.1) each time I tap or erase one new letter in the input.
I am using the bootstrap-typeahead.js v2.1.1.
HTML:
<input class="input-xlarge" id="search" type="text" data-provide="typeahead">
JS:
$('#search').typeahead({
source: function (typeahead, query) {
return $.get('http://mywebsite.com/search', { query: query }, function(data){
return typeahead.process(data);
});
}
});
Target:
function search()
{
echo json_encode(array('toto', 'tata', 'word'));
}
I don't understand how this function can crash my jQuery lib.
try this
$(function(){
$('#search').typeahead({
source: function (query, process) {
return $.getJSON(
'http://mywebsite.com/search',
{ query: query },
function (data) {
return process(data);
});
}
});
});
and the json out put should be like this
[
"toto",
"tata",
"word"
]
and html should be
<input name="sometext" type="text" class="input-large" id="search" placeholder="type something">