Does the jquery .each method not run in parallel - so you have no guarantee what order things might come out? I might be mis-remembering but I think I hit this and realised I had to do a ye-olde for() loop instead. I might be talking nonsense though - it's Friday evening and I'm a bit frazzled ;-)
List/select box sorting
Hi,
I have a weird problem and am hoping someone can explain it to me but I'm not sure if it's a Laravel issue or JQuery :-)
I have a select box in a view. I'm populating the options for the select box from a database table so I'm pulling out the records I need with:
$companies = Company::orderBy('name')->lists('name', 'id')->toArray();
and then in the view I have:
{!! Form::select('company_id', [null=>'Please Select']+$companies ,null,array('id'=>'companyId')) !!}
Now that all works fine and the companies display in the correct order on the page.
What I'm trying to do now though is use ajax to populate the select box only when a button is pressed on the page. I've set up a route so my ajax request retrieves the companies using the same query as above and the data comes back and populates the select like this:
$.ajax({
type: "GET",
url: "/getCompanies",
async: false,
success: function (data) {
$('#companyId').empty()
$.each(data, function (i,value) {
$('#companyId').append($('<option>').text(value).attr('value', i));
});
}
});
The data comes back and populates the options through ajax but it is displayed in ID order rather than name order.
So here's where I'm confused! - If I dd($companies) on my original (non ajax) method the records are in ID order there too but they display on the page in name order. The ajax request is getting the same data but when it populates the options they're in ID order.
I'm guessing that maybe when I pass $companies to the view the collection has some kind of ordering meta data that determines how Laravel/Blade displays it but when pulled through ajax I'm just getting an array and it naturally sorts by the key (which is the ID)?
I'm tried all kinds of orderBy, sortBy and changing the sorting position in the chain but I just don't seem able to retrieve a list of IDs and names in name order through an ajax request.
Grateful for any advice!
Thanks, Steve
Please or to participate in this conversation.