2

i have a html select box that needs to be populated using jquery ajax with select options that come from a php (Laravel) database query. I tried many approaches but no result, i only get 'undefined' as result. The Laravel script:

public function loturi($articol) {
$loturi = DB::select("select mgla_lotto from MG_V_DispoLottiBarcode d
join MG_AnaArt art on art.MGAA_Id = d.MGAA_Id join MG_LottiAnag  l on         
l.MGLA_Id = d.MGLA_Id where MGAA_MBDC_Classe IN ('SEM','FIN') and mbmg_id = 55 
and mgaa_matricola in (select  child.MGAA_Matricola component
from DB_Legami join MG_AnaArt  child on child.MGAA_Id = DBLG_Com_MGAA_Id
join MG_AnaArt  p on p.MGAA_Id = DBLG_MGAA_Id
where p.MGAA_Matricola = '$articol')  and mgla_datacreazione > '2014-01-01'
group by mgla_lotto having sum(dispo) > 0");
return compact('loturi');
}

The result is this:

{"loturi":[{"mgla_lotto":"1282\/15"},{"mgla_lotto":"1316\/15"},{"mgla_lotto":"1339\/15"},{"mgla_lotto":"1349\/15"},{"mgla_lotto":"1354\/15"},{"mgla_lotto":"1404\/15"},{"mgla_lotto":"1405\/15"},{"mgla_lotto":"1412\/15"}]}

The jquery script is this:

$(document).ready(function() {
$("#cod").change(function(){
var cod_articol = $("#cod").val();
$.ajax ({
url: "/internal/" + cod_articol ,
datatype: "json",
success: function(data) {
$.each(data, function(value){
$("#lot").append('<option id="' + value.index + '">' + value.name +   
'</option>');
      })
     }
   });
 });
});
1
  • Do you want as 1282 as index and 15 as name from 1282/15 ? Commented Jul 9, 2015 at 10:43

1 Answer 1

3

Hi here is your answer.

change

$.each(data, function(value){

to

$.each(data.loturi, function(value){

and use below syntax

$.each(data.loturi, function( index, value ){
    $("#lot").append('<option value="' + index + '">' + value.mgla_lotto  + '</option>');
}

Go to the link to see the example i have made for you.

https://jsfiddle.net/ovht7fkh/2/

Sign up to request clarification or add additional context in comments.

4 Comments

I seem to get closer, now i get a list of select options equal to the number of query results but they are all [object Object]
Please see the edited answer. There is the solution for your code.
will you appreciate/accept the answer if it works for you?
it is also useless to use id attribute inside of option

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.