How to use autocomplete inside a dialog box using jQuery? - javascript

I have a form inside of a dialog box that is displayed when a user click on a button. When a user starts tying inside a field I want to display available options found inside a database.
The available options will need to be read using an AJAX request.
Here is my jQuery code where I try to initialize the autocomplete()
$("#icwsTransferTo")
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}
}).autocomplete({
source: function(request, response) {
$.ajax({
type: 'GET',
url: 'index.php',
data: {method: 'userSearch', term: request.term},
dataType: 'json',
cache: false,
timeout: 30000,
success: function(data) {
console.log(data);
if(!data){
return;
}
var array = $.map(data, function(m) {
return {
label: '<div syle="display: block;"><span>' + m.configurationId.displayName + '</span><span style="float: right"> (' + m.extension + ')</span></div>'
};
});
response(array);
}
});
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
alert('Worked!');
}
});
The field icwsTransferTo is located inside of a form which is displayed in the dialog box.
The problem is that when typing 2+ characters, I see the spinning icon in the field but no results is ever presented.
When I do a manual call to the index.php?method=userSearch&term=mike I get results like this
stdClass Object
(
[items] => Array
(
[0] => stdClass Object
(
[configurationId] => stdClass Object
(
[id] => msmith
[displayName] => Mike Smith
[uri] => /configuration/users/msmith
)
[extension] => 2062
)
[1] => stdClass Object
(
[configurationId] => stdClass Object
(
[id] => mjohns
[displayName] => Mike Jones
[uri] => /configuration/users/mjohns
)
[extension] => 2083
)
)
)
what am I doing wrong here? Why the results are not showing?

I am assuming you are using the Jquery UI autocomplete? According to their documentation here: Documentation you should pass it a JSON array not html.

Related

jQuery Ajax Upload File php receives array even with out content

It's working but on every submit I receive an array even tho a file is not even added to the file input (multifile input)
postData = new FormData(this);
$.ajax({
url: "/url",
type: "POST",
data: postData,
cache: false,
contentType: false,
processData: false,
success: function (data, textStatus, jqXHR) {
if (data === "true") {
window.location.replace("/url");
} else {
$(".errors").html(data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
swal("Der opstod en fejl");
}
});
What i get from $_FILES is the following
Array
(
[files] => Array
(
[name] => Array
(
[0] =>
)
[type] => Array
(
[0] =>
)
[tmp_name] => Array
(
[0] =>
)
[error] => Array
(
[0] => 4
)
[size] => Array
(
[0] => 0
)
)
)
Is there a way where I can avoid this from happening?
Try adding required attribute to input type="file" element to prevent submission of form if no files selected by user
$("form").on("submit", function(e) {
e.preventDefault();
// do `$.ajax()` stuff
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<form>
<input type="file" name="files[]" multiple required />
<input type="submit" />
</form>

jQuery UI Autocomplete - Search based on a json node

I'm trying to search based on a school name, once the school name is selected populate a form.
I'm having a few issues searching on that particular jSON node, which in this case is name I have got the JSON response working, But it's just returning everything back. Not the specific term.
An example of my jSON Data :
[
{
"name":"The Mendip School",
"ta":"ta552023",
"address1":"Longfellow Road",
"address2":"Radstock",
"town":"",
"postcode":"BA3 3AL"
}
]
My jQuery is as follows :
// School Search....
var data_source = 'schools.json';
$(".school_name").autocomplete({
source: function ( request, response ) {
$.ajax({
url: data_source,
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response( $.map( data, function ( item )
{
return {
label: item.name,
value: item.name
};
}));
}
});
},
minLength: 3,
focus: function (event, ui) {
$(event.target).val(ui.item.label);
return false;
},
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
}
});
How do I modify my JQuery to search on the name field? I will also need to get the other fields to populate input fields.
Thanks
Here is something that may suit your needs:
$("#school_name").autocomplete({
source: function ( request, response ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
$.getJSON("/schools.json?term=" + request.term, function (data) {
var x = $.grep(data, function (item, index) {
return matcher.test( item.name );
});
console.log(x);
response($.map(x, function (item) {
return {
label: item.name,
value: item.name
};
}));
});
}
The code above will filter the data using the regex(new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" )). This regex will search for names which start-begin(^) with the typed text(by the user). The 'i' in the regex is for case-insensitive while the escapeRegex will just escape any special characters in user input.
You can also use your code and do the respective changes, I think it will also work. I just prefer to use $.getJSON. Take care of the #school_name for id(in your code you are using '.')
Try it here: http://jsbin.com/vawozutepu

jQuery autocomplete issue - each character on separate line

I am trying to get an autocomplete text box working. Here is the code that I have so far:
if ($action == 'find_products')
{
$dept = $_POST['dept'];
$stk_adddep = "
SELECT * FROM stocktake_products WHERE stocktake_id = '{$stocktake_id}' AND is_deli = 0 AND department_description LIKE '{$dept}%' LIMIT 10; ";
$result = db::c()->query($stk_adddep);
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$data[] = array(
'full_name' => $row['product_name'],
'value' => $row['product_name']);
}
echo json_encode($data);
die();
}
Div to display the text box:
<input type="text" placeholder="Name" id="customerAutocomplte" />
JS code:
$('#customerAutocomplte').autocomplete({
source: function( request, response ) {
var dept = $('#customerAutocomplte').val();
$.ajax({
url: '<?php echo Navigation::gUrl('/users/admin/stocktake_details_nonbcodeditems.php', array('stocktake_id' => $stocktake_id, 'action' => 'find_products'));?>',
type: 'POST',
data: {'dept':dept},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
autoFocus: true,
minLength: 0
});
PHP part seems to be working fine, the response that I get is as follows:
[{"full_name":"Prince Hubert Cristal","value":"Prince Hubert Cristal"},{"full_name":"Schloer","value"
:"Schloer"},{"full_name":"Underberg 20ml","value":"Underberg 20ml"},{"full_name":"Odessa Vodka 20cl"
,"value":"Odessa Vodka 20cl"},{"full_name":"Marula","value":"Marula"},{"full_name":"Maderia Verdelho
15yr old","value":"Maderia Verdelho 15yr old"},{"full_name":"Madeira Malsmey 15yr old","value":"Madeira
Malsmey 15yr old"},{"full_name":"Hennessey 5cl","value":"Hennessey 5cl"},{"full_name":"Jack Daniels
35cl","value":"Jack Daniels 35cl"},{"full_name":"Madeira Bual 10 yr old","value":"Madeira Bual 10 yr
old"}]
However, the way that the results are displayed in the text box is incorrect. What gets displayed is the whole line "value":"Jack Daniels 35cl" for example which each character being a separate entry in the text box.
Try to use item.value in the callback function:
label: item.value value: item.value
$('#customerAutocomplte').autocomplete({
source: function( request, response ) {
var dept = $('#customerAutocomplte').val();
$.ajax({
url: '<?php echo Navigation::gUrl('/users/admin/stocktake_details_nonbcodeditems.php', array('stocktake_id' => $stocktake_id, 'action' => 'find_products'));?>',
type: 'POST',
data: {'dept':dept},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.value,
value: item.value
}
}));
}
});
},
autoFocus: true,
minLength: 0
});

Ajax response array

I want to insert ajax response array into form select input. for the purpose i want to look into array. here is my function;
function _get_student_failed_classes()
{
$failed_classes=$this->db->select('class_student.class_id,course.course_code,course.course_name,course.course_credit')
->join('class','class.class_id=class_student.class_id','LEFT')
->join('course','course.course_id=class.class_course','LEFT')
->where('class.class_status',$active)
->where('class_student.class_marks <=',50)
->where('class_student.student_id',$std_code)
->order_by('class.class_id')
->get('class_student')->result();
echo $failed_classes;
}
and here is my ajax call in form
$.ajax({
url: '<?php echo base_url()."index.php/student/get_student_failed_classes/s-14-1"; ?>',
type: 'POST', data: std_code,
success: function(response)
{
alert(response);
},
error: function()
{
alert(error);
}
I get the response is []
the actual array looks like this
Array
(
[0] => stdClass Object
(
[class_id] => 3
[course_code] => cs3
[course_name] => cs3
[course_credit] => 3
)
[1] => stdClass Object
(
[class_id] => 4
[course_code] => cs4
[course_name] => cs4
[course_credit] => 4
)
[2] => stdClass Object
(
[class_id] => 5
[course_code] => cs5
[course_name] => cs5
[course_credit] => 3
)
)
can some one help me out on this
var objectRet= jQuery.parseJSON(response);
for(var i=0;i<objectRet.length;++i) {
alert(objectRet[i].class_id)
}
success: function(response) {
var $select = $('<select id="mySelect"/>');
var $options = response.map(function(a, i) {
return $('<option />', {
value: a.class_id,
text: a.course_code + ' - ' +
a.course_name + ' (' + a.course_credit +')'
});
});
$options.appendTo($select.appendTo($('#someForm')));
}

jquery autocomplete 'Disable' show all terms

Hey could someone guide me out of this problem....
I successfully created the jquery autocomplete function , but my problem is that autocomplete suggestions shows all the available labels . Autocomplete is showing the results which are not even matching the search term . I mean it showing all available label . Is their any solution to show only matching labels. here is the java function.
Any help will be gladly appreciated . Thank You
$(document).ready(function () {
$("#search-title").autocomplete({
source: function ( request, response ) {
$.ajax({
url: "availabletags.json",
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response( $.map( data.stuff, function ( item ) {
return {
label: item.label,
value: item.value
};
}));
}
});
},
minLength: 2,
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
}
});
});
EDIT : - Here is the Json File
{"stuff":[ {"label" : "Dragon", "value" : "eg.com"} ,
{"label" : "testing", "value" : "eg2.com"}]}
Successful Edited Code
<script>
$(document).ready(function () {
$("#search-title").autocomplete({
source: function ( request, response ) {
$.ajax({
url: "availabletags.json",
dataType: "json",
success: function (data) {
var sData = data.stuff.filter(function(v) {
var re = new RegExp( request.term, "i" );
return re.test( v.label );
});
response( $.map( sData, function ( item ) {
return {
label: item.label,
value: item.value
};
}));
}
});
},
minLength: 2,
focus: function (event, ui) {
this.value = ui.item.label;
event.preventDefault(); // Prevent the default focus behavior.
},
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
}
});
});
</script>
Here is the change you want to make:
dataType: "json",
success: function (data) {
var sData = data.stuff.filter(function(v) {
return v.value.indexOf( request.term ) > -1;
});
response( $.map( sData, function ( item ) {
This search will be done by value. To search by label, in other words for the user's input to be compared to the label in your JSON use the following instead:
return v.label.indexOf( ........
UPDATE
To make your search case insensitive, use the following:
var re = new RegExp( request.term, "i" );
return re.test( v.label );
instead of return v.value.indexOf( request.term ) > -1;

Categories

Resources