jquery json data autocomplete not working - javascript

I'm facing an issue with jquery autocomplete. I need that after autocompleting the results on click it converts to a link with item.value:
My actual json encode return is:
[{value: "34"}, {label: "Producto 12"}]
$(function() {
$("#producto").autocomplete({
select: function (e, ui) {
$("#producto").val(ui.item.label);
window.location.href = item.value;
return false;
},
source: function (request, response) {
$.ajax({
url: "<?php echo base_url('index.php/vista/autocompletar'); ?>",
data: request,
success: function (data) {
var ParsedObject = $.parseJSON(data);
response($.map(ParsedObject, function (item) {
return {
label: item.label,
};
}))
}
});
}
});
});
Solution:
Changed the json encode to work like this:
{value: "14", label: "afasdasd"}
And did changed the autocomplete jquery code for this one:
$(function(){
$("#producto").autocomplete({
source: "<?php echo base_url('index.php/vista/autocompletar'); ?>",
minLength: 2,
select : function(event, ui){
// convierto en link el resultado y al hacer click me dirija a la vista del producto
location.href = "<?=base_url()?>index.php/vista/detalle/" + ui.item.value;
}
});
});

Related

Post array from javascript to symfony controller by using ajax

Since One week i try to post 2 array from Js to my php controller by using Ajax but when i try to get it in my controller it is null so i don't know what to do.
This is my javascript function. It is based from a form when the user enter a departur and an arrival addresses. With this i use an api to geocoding it and i put it into two array coordonneeDepart ans coordonneeArrive but when i post it it don't work, my variable are null in my php i don't see why in when i console.log it in my js it is ok the coordinate are into my array !
If someone can help me it would be very kind ! I hope i have been clear !
$(document).ready(function() {
var coordoneesDepart=new Array(2);
var coordoneesArrive=new Array(2);
var connexion = $('.routeConnexion').data('routeController');
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
coordoneesDepart[0]= position.coords.latitude;
coordoneesDepart[1] = position.coords.longitude;
$.ajax({
url:"https://api-adresse.data.gouv.fr/reverse/?lon="+coordoneesDepart[1]+"&lat="+coordoneesDepart[0],
success: function (data){
document.getElementById("form_cp1").value= data.features[0].properties.postcode;
document.getElementById("form_adresse1").value=data.features[0].properties.name;
}
})
});
}
$("#form_cp1").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://api-adresse.data.gouv.fr/search/?postcode="+$("input[name='form[cp1]']").val(),
data: { q: request.term },
dataType: "json",
success: function (data) {
var postcodes = [];
response($.map(data.features, function (item) {
// Ici on est obligé d'ajouter les CP dans un array pour ne pas avoir plusieurs fois le même
if ($.inArray(item.properties.postcode, postcodes) == -1) {
postcodes.push(item.properties.postcode);
return { label: item.properties.postcode + " - " + item.properties.city,
city: item.properties.city,
value: item.properties.postcode
};
}
}));
}
});
}
});
$("#form_adresse1").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://api-adresse.data.gouv.fr/search/?postcode="+$("input[name='form[cp1]']").val(),
data: { q: request.term },
dataType: "json",
success: function (data) {
coordoneesDepart[0] =data.features[0].geometry.coordinates[1];
coordoneesDepart[1] =data.features[0].geometry.coordinates[0];
console.log(coordoneesDepart);
response($.map(data.features, function (item) {
return { label: item.properties.name, value: item.properties.name};
}));
}
});
}
});
$("#form_cp2").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://api-adresse.data.gouv.fr/search/?postcode="+$("input[name='form[cp2]']").val(),
data: { q: request.term },
dataType: "json",
success: function (data) {
var postcodes = [];
response($.map(data.features, function (item) {
// Ici on est obligé d'ajouter les CP dans un array pour ne pas avoir plusieurs fois le même
if ($.inArray(item.properties.postcode, postcodes) == -1) {
postcodes.push(item.properties.postcode);
return { label: item.properties.postcode + " - " + item.properties.city,
city: item.properties.city,
value: item.properties.postcode
};
}
}));
}
});
}
});
$("#form_adresse2").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://api-adresse.data.gouv.fr/search/?postcode="+$("input[name='form[cp2]']").val(),
data: { q: request.term },
dataType: "json",
success: function (data) {
coordoneesArrive[0] =data.features[0].geometry.coordinates[1];
coordoneesArrive[1] =data.features[0].geometry.coordinates[0];
console.log(coordoneesArrive);
response($.map(data.features, function (item) {
return { label: item.properties.name, value: item.properties.name};
}));
}
});
}
});
$.ajax({
method:"POST",
url:connexion,
contentType: "application/json",
data: JSON.stringify({
depart: coordoneesDepart,
arrive: coordoneesArrive,
}),
})
});
here it is my controller
/**
* #Route("/connexion", name="app_login")
*/
public function login(Request $request, AuthenticationUtils $authenticationUtils, SessionInterface $session, EntityManagerInterface $entityManager): Response
{
$user=$this->getUser();
$form = $this->createForm(LoginType::class);
$trajet = $session->get('trajet');
$depart = $request->request->get('depart');
dump($depart);
// if ($this->getUser()) {
// return $this->redirectToRoute('target_path');
// }
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
if($user!==NULL){
$id=$user->getId();
$trajet->setUserId($id);
$entityManager->persist($trajet);
$entityManager->flush();
}
dump($trajet);
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
'form' => $form->createView(),
]);
}
It seems that you send json data, then you can get them by doing :
$data = file_get_contents('php://input');

jQuery ajax autocomplete result box too small or with numbers

I am trying to complete jQuery UI autocomplete with ajax. I am using CI 3.1.5 and I get tiny result box or just number of results.
This is my ajax:
$(".addClient").each(function() {
$(this).autocomplete({
autoFocus: true,
minLength: 2,
source: function (request, response) {
$.ajax({
url: "<?php echo site_url('search');?>",
type: "GET",
data : { 'input_data' : request.term},
success: function (data){
// console.log(data);
var parsedData = JSON.parse(data);
console.log(parsedData);
var result = [];
parsedData.forEach(function (value, index) {
result.push({label:value.name, value:index.name });
});
response(result);
},
error:function(error){
console.log('error');
}
});
},
});
});
The results are in tiny box.
I also tried this:
$(".addClient").each(function() {
$(this).autocomplete({
autoFocus: true,
minLength: 2,
source: function (request, response) {
$.ajax({
url: "<?php echo site_url('search');?>",
type: "GET",
data : { 'input_data' : request.term},
success: function (data){
// console.log(data);
var parsedData = JSON.parse(data);
console.log(parsedData);
var result = [];
parsedData.forEach(function (value, index) {
result.push({label:value.name, value:index });
});
response(result);
},
error:function(error){
console.log('error');
}
});
},
});
});
The box contains just the numbers of the objects.
This is my jSon response:
[{"NAME":"888"},{"NAME":"****"},{"NAME":"****"},{"NAME":"****"}]
Edit:
Thank you Jaromanda X, you were right about this: NAME !== name!
Now I can see the suggestions in the autocomplete box, but when I choose one of the result in the input field I get:
[object Object]
What I am doing wrong? Thank you for your time.
JSON.parse parses strings,
Therefore before parsing the data convert data into string and then parse it using JSON.parse(),
In order to convert to string rather use JSON.stringify(),
Also i am doubting if you are receiving array in the promise to function forEach loop,
Check that, if it is not an array rather use for(var obj in parsedData).
Also if you just want to directly push data to some array, you don't need to parse it if you are receiving array in the promise,
directly execute
var result = [];
parsedData.forEach(function (value, index) {
result.push({label:value.name, value:index });
});
Hope it helps !
Thanks and Regards
Thank you Jaromanda X. This is the working code:
$(".addClient").each(function() {
$(this).autocomplete({
autoFocus: true,
minLength: 2,
source: function (request, response) {
$.ajax({
url: "<?php echo site_url('search');?>",
type: "GET",
data : { 'input_data' : request.term},
success: function (data){
// console.log(data);
var newData = JSON.stringify(data);
console.log(newData);
var parsedData = JSON.parse(data);
console.log(parsedData);
var result = [];
parsedData.forEach(function (value) {
result.push({label:value.NAME, value:value.NAME });
});
response(result);
},
error:function(error){
console.log('error');
}
});
},
});
});

Autocomplete with json data

I have two problems with this code:
json example:
{"json_list": [{"label": "Porto Rico", "value": 33}, {"label": "Portugal", "value": 32}]}
$("#user_country_name").autocomplete({
source : function(request, response) {
$.getJSON("/users/autocomplete/" + request.term, function(data) {
response(data.json_list);
});
},
});
First when I choose a country the selected value in the input box should be the label and not the value. Because the user should see the country and not the id.
Second, how can I populate the hidden field $("#user_country_id") for the id of the chosen country?
Use the select method
select: function( event, ui ) {
event.preventDefault();
$("#user_country_name").val(ui.item.label);
}
What you need to do, is to parse the json response. if you have any problems to get access use console.log().
$( "#w-arrival-search" ).autocomplete({
select: function (e, ui) {
$("#w-arrival-search").val(ui.item.label);
return false;
},
minLength: 3,
source: function (request, response) {
$.ajax({
url: 'http://localhost:8080/mvn/autocomplete',
data: request,
success: function (data) {
var ParsedObject = $.parseJSON(data);
response($.map(ParsedObject, function (item) {
var results = item.iata_code + " - " + item.city_name;
return {
label: results
};
}));
}
});
}
});

Why jQuery autocomplete select not work?

When I input 5 in the customer_code input area. It list the values.The problem is that when I select an entry, the 'id' value should show in the customer_name area.But it didn't!
[{"id":"5","code":"code005","name":"\u9867\u5ba2\u540d005"},{"id":"15","code":"code015","name":"\u9867\u5ba2\u540d015"},]
the json return by php is like above.and
$(function() {
$( "#customer_code" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "/management/order/auto",
dataType: "json",
data: {code: request.term},
success: function(data) {
var suggestions = [];
$.each(data, function(i, val) {
suggestions.push({
label: val.code,
// label: val.name,
});
});
response( suggestions );
},
});
},
select: function(e, ui) {
alert(ui.item.name);
// $('#customer_name').val(ui.item.name);
// $('#customer_name').val(ui.item.value.name);
// return false;
},
});
});
my html page is like this
<?php echo Form::input('customer_name', Arr::get($basic, 'customer_name'), array('id' => 'customer_name')); ?>
<?php echo Form::input('customer_code', Arr::get($basic, 'customer_code'), array('id' => 'customer_code')); ?>
The select callback is currently part of the settings for the $.ajax() request, which won't use it:
// ...
$.ajax({
url: "/management/order/auto",
// ...
success: function (data) {
// ...
},
select: function (e, ui) {
// ...
}
});
// ...
It should instead be part of the options for .autocomplete(), outside of the function for source.
$( "#customer_code" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "/management/order/auto",
// ...
success: function () {
// ...
}
});
},
select: function (e, ui) {
// ...
}
})

How to populate extra fields with jQuery autocomplete

I am passing complex JSON data to jQuery autocomplete plugin. And it is working fine so it shows the list of Products.
Now I want to get somehow Price that is already included into JSON data and when I select product from autocomlete list I would like to populate input tag with Price.
I really cannot get if it is possible to do. What I know that data is already in JSON but how to get it?
Any clue?
Here is JS for jQuery autocomplete plugin
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
}
});
});
}
To make clear item.LastPrice has Price data.
And HTML
#Html.AutocompleteFor(x => x.ProductUID, Url.Action("AutocompleteProducts", "Requisition"), true, "Start typing Product name...", Model.Product.Name)
In your ui.item object you should be able to find the the Price property in there and then set the value in the select function.
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
price: item.LastPrice // you might need to return the LastPrice here if it's not available in the ui object in the select function
};
}));
},
..
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name'),
unitPriceEl = $('#price');
$('#' + hiddenFieldName).val(ui.item.UID);
unitPriceEl.val(ui.item.LastPrice); //set the price here
}
Thanks to dcodesmith!!! I am gonna mark his solution like an answer but just in case I will share my final code that is working fine now.
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
lastPrice: item.LastPrice
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
var unitPriceEl = $('#UnitPrice');
unitPriceEl.val(ui.item.lastPrice);
console.log(ui.item.lastPrice);
}
});
});
}

Categories