Just after a little help if possible,
Im using the Codeigniter framework and i have managed to get jQuery autocomplete working, with information from a mysql database.
But have come a little bit stuck on getting the results of the auto complete to show other information in text field.
Im just trying to get my head around Jquery at the moment but have very limited knowledge of it so any help or pointers would be a great help.
My JS code
$(document).ready(function() {
$(function() {
$( "#Name" ).autocomplete({
source: function(request, response) {
$.ajax({ url: "<?php echo site_url('autocomplete/namesuggestions'); ?>",
data: { term: $("#Name").val()},
dataType: "json",
type: "POST",
success: function(data){
response(data);
}
});
},
minLength: 1
});
});
});
With Two input boxes with ids of Name and another of Address
Just to make things a bit more confusing i can get the address to appear in the Name and address to appear in the Name text box when it auto completes ??
Any Help would be greatly appreciated
You have to map the response for ajax responses and for fill other input box onselect you can use select: option in autocomplete like this
var source_name = {
source:function(request, response){
$.getJSON('your url and parameter as get',function(data){
if(data != null){
response($.map(data, function (item) {
return {
value: item.name,
addr: item.addr
}
}));
}
});
},
select: function(event, ui){
$('#addr').val(ui.item.addr);
}
};
$('#Name').autocomplete( source_name);
This will work fine if you are using jquery ui and if you return your json properly as to get values. Hope This helps you.
Related
Iam getting a value to the text box id using AJAX which is working fine.
<input type='text' id='selectuser_id' />
Javascript
$( "#customers" ).autocomplete({
source: function( request, response ) {
var countrycode = '<?php echo $agencyid; ?>';
$.ajax({
url: "http://localhost:8000/core/country/fetch_customers.php",
type: 'post',
dataType: "json",
data: {
search: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$('#customers').val(ui.item.label); // display the selected text
$('#selectuser_id').val(ui.item.value); // save selected id to input
var customerid = $("#selectuser_id").val(); //equals $q6[$t2] exactly
return false;
}
});
Now how will i pick this value to my PHP
<?php echo $selectuser_id; ?>
I tried many ways but not getting the result. Can someone help me on this?
Since you don't show us where you hold the data of the input field i will give you an example.
Javascript side (since you are also using jQuery) you can get the value of the input field by id like:
let myValue = $( "#selectuser_id" ).val();
Then inside your ajax call you can include your data just like you did for the search:
data: {
search: request.term,
myValue: myValue
}
In your fetch_customers.php file you should be able to access your post data like:
$_POST['myValue'];
I think this will be a weird one for you as I am at my wits end with this. On a screen I have in a table, I have a link being clicked that is setting off a javascript/ajax request. I have similar code in another screen that works perfectly as it heads down into the success part of the ajax call and runs code in the success portion of the call. For some reason though I can't seem to get this to work and when I debug it in chrome, I lose my breakpoints and it never seems to get into the success portion of the Ajax call.
#section scripts{
<script>
// Get the bond ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.updatelink').click(function () {
var bondid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Maintenance/Bond_Maint?handler=UpdateandReloadData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { bondid: bondid },
success: function (result) {
if (result.pass != undefined) {
document.forms[0].submit();
}
},
});
});
</script>
}
The ASP.net code behind that is calling does an update to the database and then passes back a variable containing Success as its message.
//-------------------------------------------------------------------------------
// Try to get and insert the data from a selected row and copy it
//-------------------------------------------------------------------------------
public ActionResult OnPostUpdateandReloadData(string bondid)
{
return new JsonResult(new { pass = "Success" });
}
I'm not sure how else to describe my issue other than when I debug my other code via the browser, it appears to take a different path than this code does and I cannot fathom why. For reference my other code looks like this:
#section scripts{
<script>
// Get the offender ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var offenderid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
if (result.path != undefined) {
window.location.replace(result.path);
}
},
});
});
</script>
}
Any help would be appreciated.
Okay guys so first off, thank you everyone for responding to my question. Frank Writte and Alfred pointed me into the right direction by looking for the status in the network tab for my calls. I found out that I was getting cancellations for my requests. After looking into that I found this article What does status=canceled for a resource mean in Chrome Developer Tools? that has an answer from FUCO that gave me what I needed to do. Apparently I needed to add event.preventDefault(); in front of my ajax call and all of a sudden my code worked. I'm not sure I completely understand why this works but I can't complain about the results. Again thank you everyone for trying to help. This one has been boggling my mind all morning.
I'm trying to use an external Json as source for the autocomplete Jquery UI plugin : http://jqueryui.com/autocomplete/
This code works fine:
var availableTags = ["aberdeen","aberystwyth","aberystwyth juniors"]
$( "#enter-your-parkrun" ).autocomplete({
open: function(e) {
var results = $.ui.autocomplete.filter(availableTags, e.term);
response(results);
valid = false;
},
select: function(e){
valid = true;
},
close: function(e){
if (!valid) $(this).val('');
},
source: availableTags,
});
$("#enter-your-parkrun").change(function(){
if (availableTags.indexOf($(this).val()) == -1){
$(this).val("");
}
});
but as I have almost 800 values, I need to use an external source. I've tried different things but I can't find a way to make it work:
$( "#enter-your-parkrun" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://tribesports.com/pages/parkrun-event-list",
dataType: "jsonp",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
},
minLength: 2,
delay: 400,
});
I'm not sure what q: request.term should be and if data should be parsed? I also need to add validation to make sure that only the values in the list can be accepted, it works on my first example, not too sure how to transfer this to my second code.
Thanks
request.term is what the user has typed so far, and should be passed to the server as a parameter in the AJAX call so that the server can filter the results.
In the .ajax call, dataType is the kind of data you're expecting back from the server. You have not shown it, but most probably is json, not jsonp. If it's JSON jQuery parses it automatically.
As to sending the term to the server,
if you use the GET method (which is the default), you have to include it in the query string, like this:
url: 'http://tribesports.com/pages/parkrun-event-list?term='+request.term
if you use other method (usually POST) you have to specify the method option in the jquery ajax call options, and also specify the contentType, which shuld be JSON: contentType: "application/json", and send the data in the requiredn format
As you can see this all depends on what's on the server.
I have this code I'm working on. The drop down in JSP looks like this:
<td>Product</td>
<td><select id="productCode" name="productCode" onchange="getSubProduct();" >
<option value="">-Select-</option>
</select></td>
The Loading of this particular drop down happens from a getProduct() function as follows:
function getProduct(){
var i=0;
$("#productCode")
.find('option')
.remove()
.end()
.append('<option Style="color:red;" value="">loading...</option>')
.val('');
$("#productCode").attr('style', 'color:red;');
$.ajax({
url: 'getProducts',
data: {ppID:$('#ppId').val(),region:$('#regionCode').val(),branch:$('#legalVehicleCode').val()},
type: 'GET',
dataType: 'json',
success: function(data, textStatus, xhr) {
var temp = new Array;
temp = data;
$("#productCode")
.find('option')
.remove()
.end()
.append('<option value="">-Select-</option>')
.val('');
$("#productCode").attr('style', 'color:black;');
for(i=0;i<temp.length; i++){
$("#productCode").append('<option value='+temp[i].productCode+'>'+temp[i].productShortDescription+'</option>');
}
},
error: function(xhr, textStatus, errorThrown) {
//getProduct();
alert(error);
}
});
}
Now my requirement is that, after I click search(shown below), I am supposed to be retaining the Search filter values in the next page(the search results page with a grid). This page has this form too.
<button class="btn btn-primary" type="button" onclick="javascript:buttonClicked1('search');retainSearch();"> Search</button>
Things I have tried:
1. Sending values of those ajax called fields from the controller and attempted to fill it up.
2. Running jquery code
$("#searchForm #productCode").val("${replayMessageBean.productCode}");
Nothing has worked. Kindly help me :(
Try removing double quotes from,
$("#searchForm #productCode").val("${replayMessageBean.productCode}");
OR save the value of ${replayMessageBean.productCode} into some hidden field like,
<input type="hidden" id="prodCode" value="${replayMessageBean.productCode}">
And access this value $('prodCode')
Did you try something more simple and useful as JQuery autocomplete?.
Using autocomplete you can add an ajax call and save the return values to be used in the search after that, even using a dropdown/input. Take a look:
http://jqueryui.com/autocomplete/
Here some code of mine.
function initialize(){
$( "#contactDetails_contactKeyForTenderingParty" ).autocomplete({
source: function(request, response) {
$.ajax({
url: 'contacts/organization/name/'+request.term + ".do",
dataType: "json",
success: function(data) {
response(data);
}
});
},
messages: {
noResults:'',
results: function() {}
},
minLength: 2,
select: function( event, ui ) {
update(ui.item);
return false;
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.legalName +"</a>" )
.appendTo( ul );
}
}
function update(governmentContact){
$('#a').val(governmentContact.basicAddress.houseNumber);
$('#b').val(governmentContact.basicAddress.city);
$('#c').val(governmentContact.contact.phoneNumber);
$('#d').val(governmentContact.contact.fax);
$('#e').val(governmentContact.basicAddress.zipCode);
$('#f').val(governmentContact.contact.email);
}
function expandDropdown(){
$("#dropdown").autocomplete('search', 'all');
}
I just sent 2 beans, one with the selected option and another with all the options.Basically 1 is a list and another is a single string. Then i froze the value with that string as "Selected" and the rest i popuated on the list normally. This solved my problem.
Sorry for the most simplest of questions but I can't seem to get anything to work. It's the first time I've really played around with AJAX.
I'm developing in codeigniter and I have a link that when clicked runs the controller: photo function: like and allows the logged in user to like the photo then redirects the user back to the photo and displays a slightly different version of the button showing that the user likes the photo.
<?php if ( $like_count > '0' ) { echo $like_count; } ?>
It works fine but I thought it would be cool to replace it with an ajax function so it's more of a fluid motion instead of navigating off the page and then back again.
Any help would be greatly appreciated.
$(".uk-button").click(function(e) {
e.preventDefault();
//Here you can add your ajax
$.ajax({
url: site_url + 'photo/like',
data: {
liked : 1
},
type: 'POST',
dataType: 'json',
async : false,
success: function(success_record) {
console.log(success_record,":success_record");
//You might receive your like count from PHP here
}
});
});
In your success record you would get your PHP record values. Based on that you can increment or decrement count in success function
You can do something like this:
$(document).ready(function()
{
$('.likeLink').on('click', funciton()
{
var obj = $(this);
var id = obj.attr('id'); //anything you want to pass to update your like somewhere
$.ajax(
{
type: 'POST',
url: 'YourFilePathWhereYouWillDoTheLike',
data:
{
id: id,
},
cache: false,
success: function(response)
{
obj.html("You have liked this!");
}
});
return false;
})
})