Bootstrap 2.2.1 Typeahead - javascript

PHP, returns a JSON encoded array
$this->load->model('car_model', 'cars');
$result = $this->cars->searchBrand($this->input->post('query'));
$this->output->set_status_header(200);
$this->output->set_header('Content-type: application/json');
$output = array();
foreach($result as $r)
$output['options'][$r->brandID] = $r->brandName;
print json_encode($output);
Outputs: {"options":{"9":"Audi","10":"Austin","11":"Austin Healey"}}
JS updated:
$(".searchcarBrands").typeahead({
source: function(query, typeahead) {
$.ajax({
url: site_url + '/cars/search_brand/'+query,
success: function(data) {
typeahead.process(data);
},
dataType: "json"
});
},
onselect: function(item) {
$("#someID").val(item.id);
}
});
UPDATE: Uncaught TypeError: Object function (){return a.apply(c,e.concat(k.call(arguments)))} has no method 'process'
If I type just 'A' then typeahead shows me only the first letter of each result (a bunch of A letters). If I type a second letter I see nothing anymore.
I've tried JSON.parse on the data or using data.options but no luck.
What am I doing wrong?

I've been battling this for the last day with Bootstrap 2.2.1. No matter what I did, it would not work. For me, I always got the process undefined error unless I put a breakpoint in the process function (maybe just because FireBug was open?).
Anyway, as a patch I re-downloaded Bootstrap with typeahead omitted, got the typeahead from here:
https://gist.github.com/2712048
And used this code:
$(document).ready(function() {
$('input[name=artist]').typeahead({
'source': function (typeahead) {
return $.get('/7d/search-artist.php', { 'artist': typeahead.query }, function (data) {
return typeahead.process(data);
});
},
'items': 3,
'minLength': 3
},'json')
});
My server returns this (for 'Bo'):
["Bo","Bo Burnham","Bo Diddley","Bo Bruce","Bo Carter",
"Eddie Bo","Bo Bice","Bo Kaspers Orkester","Bo Saris","Bo Ningen"]
Of course, now it ignores my minLength, but it will get me through the day. Hope this helps.
EDIT: Found the solution here:
Bootstrap 2.2 Typeahead Issue
Using the typeahead included with Bootstrap 2.2.1, the code should read:
$(document).ready(function() {
$('input[name=artist]').typeahead({
'source': function (query,typeahead) {
return $.get('/search-artist.php', { 'artist': encodeURIComponent(query) }, function (data) {
return typeahead(data);
});
},
'items': 3,
'minLength': 3
},'json')
});

Here's what I do to facilitate remote data sources with bootstrap's typeahead:
$("#search").typeahead({
source: function(typeahead, query) {
$.ajax({
url: "<?php echo base_url();?>customers/search/"+query,
success: function(data) {
typeahead.process(data);
},
dataType: "json"
});
},
onselect: function(item) {
$("#someID").val(item.id);
}
});
And then you just need to make sure your JSON-encoded arrays contain a value index for the label and an id field to set your hidden id afterwards, so like:
$this->load->model('car_model', 'cars');
$brands = $this->cars->searchBrand($this->uri->segment(4));
$output = array();
foreach($brands->result() as $r) {
$item['value'] = $r->brandName;
$item['id'] = $r->brandID;
$output[] = $item;
}
echo json_encode($output);
exit;

$.post is asynchronous, so you can't user return in it. That doesn't return anything.

Related

Ajax select list

I want to retrive the result of this kind of data list with CakePHP 3
<?= $this->Form->select('notif_message',
[ 'oui' => 'oui', 'non' => 'non'], array('id' => 'notifmess')); ?>
<?= $this->Form->hidden('notifmessage', ['value' => $notif_message]) ;?>
The goal is when a user chosse a value, an Ajax call to this controller be done
public function notifmessage() // mise à jour des paramètres de notifications 0 = non, 1 = oui
{
if ($this->request->is('ajax')) {
$notifmessage = $this->request->data('notifmessage');
if($notifmessage == 'oui')
{
$new_notif_message = 'non';
}
else
{
$new_notif_message = 'oui';
}
$query = $this->Settings->query()
->update()
->set(['notif_message' => $new_notif_message])
->where(['user_id' => $this->Auth->user('username') ])
->execute();
$this->response->body($new_notif_message);
return $this->response;
}
}
And i would like to do this call in Ajax without reloading , i have this script
<script type="text/javascript">
$(document).ready(function() {
$('.notif_message').change(function(){
$.ajax({
type: 'POST',
url: '/settings-notif_message',
data: 'select.notif_message' + val,
success: function(data) {
alert('ok');
},
error: function(data) {
alert('fail');
}
});
});
});
</script>
he doesn't work, nothing happend but i don't know why, i don't have any message in log, i can't debug without indication what doesn't not work
Thanks
In yout javascript you should use $('#notifmess').change(… or $('[notif_message]').change(… instead of $('.notif_message').change(….
In CakePHP the first argument of the select method will be used as the name attribute of the select tag.
Update:
In your controller you are retrieving the value of $_POST['notifmessage'], which is the name of the hidden input field.
To get the user's choice you either should use $this->request->data('notif_message'); in the controller, or setting up the ajax request to send the data with notifmessage like so:
$('[name="notif_message"]').change(function(){
$.ajax({
type: 'POST',
url: '/settings-notif_message',
data: {'notifmessage' : this.value},
success: function(data) {
// To change selected value to the one got from the server
$('#notifmess').val(data);
alert('ok');
},
error: function(data) {
alert('fail');
}
});
});
(Where in this case this is referring to <select> tag.)
i'm close to success: my ajax call is working, database update is working , i juste need to put the 'selected' to the other , i'm trying with this jquery code
<script type="text/javascript">
$(document).ready(function() {
$('#notifmess').change(function(){
var id = $('#notifmess').val();
$.ajax({
type: 'POST',
url: '/instatux/settings-notif_message',
data: {'id' : id},
success: function(data){
$('#notifmess option[value="'+data.id+'"]').prop('selected', true);
},
error: function(data)
{
alert('fail');
}
});
});
});

AJAX jquery json sending array to php

I'm trying to send a associative array via AJAX $.post to php. Here's my code:
var request = {
action: "add",
requestor: req_id,
...
}
var reqDetails = $("#request_details").val();
switch(reqDetails){
case 1:
request[note] = $("#note").val();
break;
...
}
if(oldRequest()){
request[previousID] = $("old_id").val();
}
$('#req_button').toggleClass('active');
$.post("scripts/add_request.php", {
request_arr: JSON.stringify(request)
}, function(data){
console.log(data);
$('#req_button').toggleClass('active');
}, 'json');
And i'm simply trying to read the received data in my php script:
echo json_decode($_POST["request_arr"]);
But it's not working. I'm a newbie to js, I can't figure out what I'm doing wrong.
Check below link for your reference
Sending an array to php from JavaScript/jQuery
Step 1
$.ajax({
type: "POST",
url: "parse_array.php",
data:{ array : JSON.stringify(array) },
dataType: "json",
success: function(data) {
alert(data.reply);
}
});
Step 2
You php file looks like this:
<?php
$array = json_decode($_POST['array']);
print_r($array); //for debugging purposes only
$response = array();
if(isset($array[$blah]))
$response['reply']="Success";
else
$response['reply']="Failure";
echo json_encode($response);
Step 3
The success function
success: function(data) {
console.log(data.reply);
alert(data.reply);
}
You are already using "json" as dataType, so you shouldn't apply 'stringify' operation on your data.
Instead of request_arr: JSON.stringify(request), can you try request_arr: request directly?

Jquery Autocomplete Search with Ajax Request as sourcedata

What I want to do:
I want to do a input text field with a jquery autocomplete function which gets the source data from a cross-domain curl request. The result should be exactly like this example (CSS not important here): http://abload.de/img/jquerydblf5.png (So I actually want to show additional infos which I get from the curl Request). The URL to get the source data is http://www.futhead.com/15/players/search/quick/?term= and in the end I add those letters which are currently typed in at my input field (for example "Ronaldo").
At the moment I only tried to perform the searchrequest without showing all infosin the dropdown as shown in the screen above. I only want to see which playernames I actually got back by the curl request. Later I will try to add more information for the dropdown. Maybe you guys can help me as well with this as well (I think its called custom renderItem ??).
This is what I've tried:
<script>
$( "#tags" ).autocomplete({
source: function (request, response) {
$.ajax({
type: 'GET',
url: 'playerscraper.php',
dataType: "json",
data: function () {
return $("#results").val()
},
success: function (data) {
// I have no idea what this response and map is good for
response($.map(data, function (item) {
return {
label: item.label,
id: item.value,
};
}));
},
});
}
});
</script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
My playerscraper.php is performing the curl request and actually returns a array (tested with echo):
$term = $_GET['term'];
$curlRequest = new CurlRequest();
$result = $curlRequest->get('http://www.futhead.com/15/players/search/quick/?term=' . $searchterm);
$players = array();
return json_encode($result);
My problem:
I have no idea how to do the source part for the autocomplete function this way, that I get the right results from the ajax request with my searchterm from the input field. When I type in something in the input field, nothing happens (the function which defines the source is getting called - tested with an alert).
First try to fix the problem with your help (current Code):
<script>
$( "#tags" ).autocomplete({
source: function (request, response) {
$.ajax({
type: 'GET',
url: 'playerscraper.php',
dataType: "json",
data: function () {
term: request.term
},
success: function (data) {
// I have no idea what this response and map is good for
response($.map(data, function(item) {
return {
label: item.full_name,
value: item.player_id
};
}));
},
});
},
minLength: 3,
delay: 500
});
</script>
The JSON is in a format which is incompatible with what autocomplete widget expects. This is where the $.map comes into play. You use this function to convert the JSON to desired format. Begin by returning a {label: "display name", value: "some id"} pairs like this:
response($.map(data, function(item) {
return {
label: item.full_name,
value: item.player_id
};
}));
Notes:
You should send content type header with your JSON:
header("Content-Type: application/json");
echo $result;
You should use request.term instead of input element value for the data parameter like this:
data: { term: request.term }
You should set higher delay and minLength values to reduce number of JSON requests:
delay: 500,
minLength: 3,
There are some undefined variables in your PHP script. Fix. Make sure that you echo the JSON instead of returning it. The remote server sends JSON so there is no need to json encode it again.
$term = $_GET['term'];
$result = file_get_contents('http://www.futhead.com/15/players/search/quick/?term=' . $term);
header("Content-Type: application/json");
echo $result;
Always check your PHP scripts for issues by opening directly in browser. Always look at browser JavaScript console to look for JavaScript errors and warnings.
Few things are looking wrong in in jQuery code
You have used $_GET['term'] in server side code but not passed term in ajax request query string
Need to fix as
data: {term: request.term}
extra comman(,) in code, it will create issue in IE browsers
response($.map(data, function (item) {
return {
label: item.label,
id: item.value
};
}));

Another way to load remote data in Select2

I'm trying to get the remote using json from one php page,the JSON data:
[{"id":"0","name":"ABC"},{"id":"1","name":"DEF I"},{"id":"2","name":"GHI"}]
and the script is like this:
$(document).ready(function() {
$('#test').select2({
minimumInputLength: 1,
placeholder: 'Search',
ajax: {
dataType: "json",
url: "subject/data_json.php",
data: function (term, page) {// page is the one-based page number tracked by Select2
return {
college: "ABC", //search term
term: term
};
},
type: 'GET',
results: function (data) {
return {results: data};
}
},
formatResult: function(data) {
return "<div class='select2-user-result'>" + data.name + "</div>";
},
formatSelection: function(data) {
return data.name;
},
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text');
callback({"name":elementText});
}
});
});
It works fine but it always reads the database whenever I typed one new character to search
. So i decided to use the another way (retrieve all data at first time and use select2 to search it):
$(document).ready(function() {
$("#test").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0; }).length===0) {
return {id:term, text:term};}
},
multiple: false,
data: [{"id":"0","text":"ABC"},{"id":"1","text":"DEF I"},{"id":"2","text":"GHI"}]
});
});
But the problem is how can I pass a request to data_json.php and retrieve data from it?
Say
data: $.ajax({
url: "subject/data_json.php",
data: function (term, page) {// page is the one-based page number tracked by Select2
return {
college: "ABC", //search term
};
}
dataType: "json",
success: function(data){
return data
}
}
But its not working, can anyone help?
Thanks
Why did you move away from your original code?
minimumInputLength: 1
Increase this and the search won't be called on the first character typed. Setting it to 3 for example will ensure the ajax call isn't made (and the database therefore not queried) until after the 3rd character is entered.
if I understood your question correctly you have data_json.php generating the options for select2 and you would like to load all of them once instead of having select2 run an ajax query each time the user inputs one or more characters in the search.
This is how I solved it in a similar case.
HTML:
<span id="mySelect"></span>
Javascript:
$(document).ready(function () {
$.ajax('/path/to/data_json.php', {
error: function (xhr, status, error) {
console.log(error);
},
success: function (response, status, xhr) {
$("#mySelect").select2({
data: response
});
}
});
});
I've found that the above does not work if you create a <select> element instead of a <span>.

Adding values to serialised Array Jquery

Im trying to add data to a preserialised array. Its not working. Anyone spot why?
$("#show-friends").live("click", function() {
var friendSelector = $("#jfmfs-container").data('jfmfs');
var sendArr = $(friendSelector).serializeArray();
sendArr.push({ name: "userid", value: "<?php echo $userId;?>" });
sendArr.push({ name: "fid", value: "<?php echo $fid;?>" });
$.post({
url:'test.php',
data: sendArr,
});
});
Edit: I changed my code to:
$("#show-friends").live("click", function() {
var friendSelector = $("#jfmfs-container").data('jfmfs');
var sendArr = friendSelector.serializeArray();
$.post({
url:'test.php',
data: "name=<?php echo $userId;?>&fid=<?php echo $fid;?>&jsondata="+sendArr,
});
});
However I get a error friendSelector.serializeArray is not a function
Your $post call is incorrect. You don't pass an object like you would for $.ajax. You pass the url, then the data (if any), and then a callback (if you want).
It should be:
$.post('test.php', sendArr);
Or with $.ajax:
$.ajax({
url:'test.php',
data: sendArr,
type: 'POST'
});
EDIT: When you do $("#jfmfs-container").data('jfmfs'), this is return you the value of the jfmfs data. friendSelector.serializeArray doesn't work, because friendSelector is whatever the data was, not a jQuery object.

Categories