I'm trying to get a field on my view to autocomplete with values from a database but can't seem to figure out what is going wrong....
In my view I have the following script:
$(document).ready(function() {
$(function() {
$( "#searchQuestion" ).autocomplete({
source: function(request, response) {
$.ajax({ url: "<?php echo site_url('contentmanagement/suggestions'); ?>",
data: { term: $("#searchQuestion").val()},
dataType: "json",
type: "POST",
success: function(data){
response(data);
}
});
},
minLength: 2
});
});
});
Within my contentmanagement controller I have the "suggestions" function:
function suggestions() {
$this->load->model('onlinehelp');
$term = $this->input->post('term', TRUE);
if (strlen($term) < 2)
break;
$rows = $this->onlinehelp->GetAutocomplete($term);
$keywords = array();
foreach ($rows as $row)
array_push($keywords, $row->question);
echo json_encode($keywords);}
And Finally within my model I have the follow function -
function GetAutocomplete($term) {
$this->db->select('question');
$this->db->like('question',$term, 'both');
$query = $this->db->get('question');
return $query->result();
}
The query above is the equivalent to "SELECT question FROM question WHERE question LIKE %$term%.
Can anyone see where I am going wrong with this??
You might be getting a 500 Internal Server Error caused by CSRF protection being enabled. If so, every POST request must contain a CSRF value. You have a few options:
1. Include the CSRF value in your data using $this->input->cookie('your_csrf_name');
2. Perform GET request instead of POST.
Use $this->input->get('term', TRUE); in your controller. Remember to sanitize and validate the value.
3. Disable CSRF protection. Not recommended.
This works with the CSRF enabled:
Use the jquery cookie plugin
<script type='text/javascript' src='<?php echo base_url(); ?>/js/lib/jquery.cookie.js'></script>
Then on your autocomplete thing:
<script type="text/javascript">
$(document).ready(function() {
$(function() {
$("#searchQuestion").autocomplete({
source: function(request, response) {
$.ajax({ url: "<?php echo site_url('contentmanagement/suggestions'); ?>",
data: { term: $("#searchQuestion").val(), ci_csrf_token: $.cookie("ci_csrf_token") },
dataType: "json",
type: "POST",
success: function(data){
response(data);
}
});
},
minLength: 2,
focus: function( event, ui ) {
$("#searchQuestion").val(ui.item.term);
return false;
}
})
.data("autocomplete")._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.term + "</a>" )
.appendTo( ul );
};
});
});</script>
Related
I'm trying to make this code to work but it look I'm doing something wrong when passing the two variables with ajax, please help, here is the code, basically is a drag and drop code to move items between boxes and organize inside each box.
<script type="text/javascript">
$(document).ready(function() {
// Example 1.3: Sortable and connectable lists with visual helper
$('#sortable-div .sortable-list').sortable({
connectWith: '#sortable-div .sortable-list',
placeholder: 'placeholder',
delay: 150,
stop: function() {
var selectedData = new Array();
$('.sortable-list>li').each(function() {
selectedData.push([$(this).attr("id"), $(this).attr("pagenum")])
});
updateOrder(selectedData);
}
});
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data,
page: data
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
</script>
You can make it using this way:
$('.spremiUredivanje').click(function(){
ai = document.getElementById('ai_mjerila_edit').value;
broj_mjerila = document.getElementById('broj_mjerila_edit').value;
adresa = document.getElementById('adresa_edit').value;
stanje = document.getElementById('stanje_edit').value;
$( "#datum_edit" ).datepicker( "option", "dateFormat", "yy-mm-dd" );
datum = document.getElementById('datum_edit').value;
operater = document.getElementById('operater_edit').value;
$.ajax({
url: 'test.php',
type: 'POST',
data: {
post1: broj_mjerila, post2: adresa, post3:stanje, post4: datum, post5: operater, post6:ai
},
beforeSend: function(){
$('#loaderEdit').show();
},
So your php file should look like this:
$broj_mjerila = $_POST['post1'];
$adresa = $_POST['post2'];
$stanje = $_POST['post3'];
$datum = $_POST['post4'];
$operater = $_POST['post5'];
$ai = $_POST['post6'];
To control your response use success inside ajax call:
success: function(response) {
if(response == 1) {
//alert("success!");
$('#editUspjesan').show();
$('#loaderEdit').hide();...
Can you explain your requirement clear. Are you trying to get page number and id in 2 separate array?
// If page no and id need to be in separate array
var position = [], pages = [];
$('.sortable-list>li').each(function() {
position.push($(this).attr("id"));
pages.push($(this).attr("pagenum"));
});
updateOrder(position, pages);
function updateOrder(position, page) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: position,
page: page
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
// If page no and id can be combined use objects
var selectedData = [];
$('.sortable-list>li').each(function() {
selectedData.push({id: $(this).attr("id"), page: $(this).attr("pagenum")})
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
<script type="text/javascript">
$(document).ready(function() {
// Example 1.3: Sortable and connectable lists with visual helper
$('#sortable-div .sortable-list').sortable({
connectWith: '#sortable-div .sortable-list',
placeholder: 'placeholder',
delay: 150,
stop: function() {
var selectedData = new Array();
$('.sortable-list>li').each(function() {
selectedData.push([$(this).attr("id"), $(this).attr("pagenum")])
});
updateOrder(selectedData);
}
});
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data.id,
page: data.pagenum
},
dataType:'json',
success: function() {
/* alert('your change successfully saved');*/
}
})
}
</script>
Let's try this one
I have a problem with my code. I receive data via ajax and it works, but the problem is that when I try to search for an element and all the elements appear so the search does not work properly.
JS code :
let marque_id =$("#marque_id").val();
$( "#grp_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id : id_marque
},
success: function( data ) {
response( data );
console.log(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
PHP code :
$data = array();
while($line = mysqli_fetch_object($liste_grp) ){
$data[] = array("label"=>$line->grp_nom,"value"=>$line->grp_nom ,"id"=>$line->groupement_id);
}
echo json_encode($data);
result
you should send the text you are searching for to ajax request so your autocomplete function should be
let marque_id =$("#marque_id").val();
$( "#grp_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id : id_marque ,
term: request.term
},
success: function( data ) {
response( data );
console.log(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
request.term is your search text and in your example it is group text
and also you need to modify your mysql query and add condition (like)
for example
$rs = mysql_query("SELECT * FROM table WHERE colum LIKE '%" . $_POST['term'] . "%'");
and finally you can check https://jqueryui.com/autocomplete/#remote-jsonp
I would advise the following jQuery:
$( "#grp_name" ).autocomplete({
source: function(request, response) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id: request.term
},
success: function( data ) {
console.log(data);
response(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
This is a small change. This will send the request.term to your PHP Script. For example, if the user types "gro", this will be sent to your script and would be accessed via:
$_POST['marque_id']
This would assume your SQL Query is something like:
$stmt = $mysqli->prepare("SELECT * FROM table WHERE column LIKE '?%'");
$stmt->bind_param("s", $_POST['marque_id']);
$stmt->execute();
$liste_grp = $stmt->get_result();
$data = array();
while($line = $liste_grp->fetch_assoc()) {
$data[] = array(
"label" => $line['grp_nom'],
"value" => $line['grp_nom'],
"id" => $line['groupement_id']
);
}
$stmt->close();
header('Content-Type: application/json');
echo json_encode($data);
This uses the MySQLi Prepared Statement, and will help prevent SQL Injection. I also included the JSON Header as good practice. The result of search "gro" would be something like:
[
{
"label": "GROUPE DATAPNEU TEST",
"value": "GROUPE DATAPNEU TEST",
"id": 1
}
];
Thanks guys i found a solution it works better
i used tokeninput with many options
http://loopj.com/jquery-tokeni
$.ajax({
url:"ajax_get_societe_authorisation",
method:"POST",
scriptCharset: "iso-8859-1",
cache: false,
dataType: "json",
data: {
marque_id : id_marque
},
success: function( data ) {
console.log(data);
$("#soc_name").tokenInput(data
,{
tokenLimit: 1,
hintText: "Recherche une société par son nom",
noResultsText: "Aucune société trouvé",
searchingText: "Recherche en cours ...",
onAdd: function (data) {
$("#soc_id").val(data.id);
},
onDelete: function (item) {
$("#soc_id").val("");
}
}
);
}
});
I have the following jQuery code for the autocomplete,
$( "#text" ).autocomplete({
source: function( request, response ) {
$.ajax({
type: 'GET',
url: 'server.php',
dataType: 'json',
data: {
input: request.term
},
success: function(data) {
response( $.map(data, function(item) {
return {
label: item.Symbol + " - " + item.Name + " ( " + item.Exchange + " )"
}
}));
}
});
},
minLength: 1,
select: function( event, ui ) {
var symbol = ui.item.label.split(' ');
setTimeout(function() {
$('#text').val(symbol[0]);
},0);
}
});
Whenever a user enters a key in the textbox, an AJAX call is made to a PHP file. This PHP file will retrieve data from an API and update the suggestions list for the autocomplete feature?
I've got the following code in the PHP side,
<?php
if(!empty($_GET['term'])) {
$term = $_GET['term'];
$url = "http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input=".$term;
$j_response = file_get_contents($url);
$j_response = json_decode($j_response);
print json_encode($j_response);
}
?>
For some reason, the autocomplete isn't working for me- what am I doing wrong here?
In the PHP, you are trying to use $_GET['term'], but in the JavaScript your variable is called input. Change the data object to use term not input:
data: {
term: request.term
},
I am new to jquery. In my current cakephp page url is:
http://localhost/ultimate/admin/treatments/add
I have a json array: <?php $json = $this->Js->object($matchs);?>the content has: '[{"Type":{"name":"Items 1","price":"15","duration":"10"}},{"Type":{"name":"Items 2","price":"30","duration":"25"}}]'
Now I have a name: Items 1, how can I get the price from json array by using Jquery and update to one input area.
Something like this, but I have no idea:
$(document).ready(function(){
$('#treatment_foo').change(function(){
$.ajax({
url: 'add',
data:
dataType: 'json',
cache: false,
success: function(result) {
$('#fee_foo').val($('#treatment_foo').val());
},
});
});
});
success: function(result) {
$('#fee_foo').val( result[0].Type.price );
},
You can also use getJson jQuery function.
Like
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
(function($)
{
$.getJSON(URL,
{
params1: "value",
params2: "value"
},
function(result)
{
$.each(result.Type, function(i,item)
{
console.log(item.name);
console.log(item.price);
console.log(item.duration);
if ( item.name == 'Item 1' ) return;
});
});
});
</script>
As you can see you can loop through result json and display and compare it as you need,
Cheers...
Feel Free To Ask.
After a few hours of deciphering tutorials, I finally got codeigniter and jquery autocomplete to work with each other...kind of.
Firebug is displaying the correct search terms back in JSON format, but the drop down box is not displaying any text. If there are 2 results, it displays 2 empty rows.
you can see it 'not working' here: http://rickymason.net/blurb/main/home
JS:
$(document).ready(function() {
$(function(){
$( "#filter" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "http://rickymason.net/blurb/main/search/",
data: { term: $("#filter").val()},
dataType: "json",
type: "POST",
success: function(data){
response(data);
}
});
},
minLength: 2
});
});
});
Controller:
public function search()
{
$term = $this->input->post('term', TRUE);
$this->thread_model->autocomplete($term);
}
Model:
public function autocomplete($term)
{
$query = $this->db->query("SELECT tag
FROM filter_thread ft
INNER JOIN filter f
ON ft.filter_id = f.filter_id
WHERE f.tag LIKE '%".$term."%'
GROUP BY tag");
echo json_encode($query->result_array());
}
Hopefully its an easy fix!
Thanks
Changing your code to something like this would work(I have tested in your site)
$( "#filter" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "http://rickymason.net/blurb/main/search/",
data: { term: $("#filter").val()},
dataType: "json",
type: "POST",
success: function(data){
var resp = $.map(data,function(obj){
return obj.tag;
});
response(resp);
}
});
},
minLength: 2
});
Copy and paste the above code block in your firebug console and then try the autocomplete. It will work. I tried in your site and it worked.
Secondly you dont need both $(document).ready(function() { and $(function(){ at the same time as they accomplish the same thing.
Check this section of jQuery UI autocomplete
Expected data format
The data from local data, a url or a callback can come in two variants:
An Array of Strings:
[ "Choice1", "Choice2" ]
An Array of Objects with
label and value properties: [ { label: "Choice1", value: "value1" },
... ]
Reference: $.map
Looking at this question on SO you need to setup your label and value fields on the response return. Try either arranging your PHP JSON output to match or map the return with something this the following (untested).
response( $.map(data, function(item){
return {
label: item.tag,
value: item.tag
};
})