1

Im struggling with this js code for some reason. I can't access variables inside the ajax function. I tried solving this by placing the "formatted" variable above the ajax function but I can't access it from inside. How do I solve this?

angular.module('ireg')
.controller("compoundSearchController", function(){
    var vm = this;
    vm.searchText = "Enter your search here...";
    vm.compounds = getJSON();

    function getJSON(){
        var formatted = "initial";  

        console.log(formatted); // equals initial

        $.ajax({url: "http://localhost:8080/ireg/app/php/returnAllCompounds.php", success: function(result){
            formatted = jQuery.parseJSON( result );
            console.log(formatted); //equals the correct object
        }})

        console.log(formatted); // equals initial
        return formatted;
    }

    console.log(vm.compounds); // equals initial

});
Chris Chevalier
  • 620
  • 1
  • 7
  • 20

2 Answers2

1

Asynchronous behavior of AJAX calls is the reason of difference between actual behavior and expected behavior.

Update your code to

var formatted = "initial";  

$.ajax({url: "http://localhost:8080/ireg/app/php/returnAllCompounds.php", success: function(result){
    formatted = jQuery.parseJSON( result );
    vm.compounds = formatted;
}})
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
  • ( http://imgur.com/wLUbeqt ) As you can see outside of the ajax function the variable is still initial? Is something outside of the provided code you believe? I only reference it here. – Chris Chevalier Jun 27 '15 at 15:15
  • Again we are trying to access "formatted" prior to response received of AJAX. If you move the console.log inside the ajax callback function, you will be able to see the updated value i.e. from line no. 14 to line no. 12 as per your screenshot. – Nikhil Aggarwal Jun 27 '15 at 16:00
0

You could not get response of ajax call outside it success because they are asynchronous in nature. You need to use their call back to get that like success or you could also use .then function which get call when ajax call gets resolved.

NOTE

Don't mix jQuery ajax with AngularJS that will mess up with digest cycle, you need to force it manually, Do replace ajax with $http

Update

Below is angular version $.ajax

    $http.get("http://localhost:8080/ireg/app/php/returnAllCompounds.php")
    .success(function(result){
        formatted = jQuery.parseJSON( result );
        console.log(formatted); //equals the correct object
    }});
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299