Gabriel Tortomano Gabriel Tortomano - 7 months ago 10
Javascript Question

ajax request in angular and php

I'm trying to start a simple web page in which I wanna load data to a combobox from a request to my php script; The problem that I'm having is that when I load the page it doesn't load, but if i assign the function to a button it does but i have to press it twice for it to start working... I just can't figure out why that's happening, I have the next code in my html:

<div class="form-group">
<label class="col-md-6 col-xs-12" for="pref-perpage">Categoría:</label>
<select id="pref-perpage" class="col-lg-9 lindo">
<option ng-repeat="result in search.vendor">{{result.nombreCategoria}}</option>
<option selected="selected">[ Seleccione ]</option>
</select>
</div> <!-- form group [Categoria] -->


this is my javascript:

search.buscar = function()
{

$.ajax({
url: "Busqueda.php",
type: "get",
success: function(response) {
search.vendor.push({'nombreCategoria':response});
var JSONObject = JSON.parse(response);

for(var x in parsed){
search.vendor.push(parsed[x]);
}


and the kind of data that I want to fill the array with would be something like:

search.vendor = [{'nombreCategoria':'data'}];


If've also tried the $http method from angular but it does the same; I fill the combobox with fake data manually and I have no problem!

server response: [{"nombreCategoria":"ACCESORIOS"},{"nombreCategoria":"CPU"},{"nombreCategoria":"IMPRESORA"},{"nombreCategoria":"MONITOR"}]

Answer

I'm working with Gabriel in this project. The soluction was to add the method $scope.$apply(); after the .push() method...

So, the function looks like this:

search.buscar = function() {
    $.ajax({
        url: "Busqueda.php",
        type: "get",
        success: function(response) {
            search.vendor.push({'nombreCategoria':response});
            var JSONObject = JSON.parse(response);
            for(var x in parsed) {
                search.vendor.push(parsed[x]);
                $scope.$apply();
            }
        }
    });
}

By the way... I found the solution here (stackoverflow)