Elliott James Elliott James - 1 month ago 13
Ajax Question

update a value BEFORE running a function containing ajax

On page load, the code below performs an api request and returns the result. I then have some code that on change of a selector updates one of the variables with the value of that selector and then re-requests the api using the function newsFeed();

My problem is the variable is not getting updated before the function has run.

How do you update a value before running a function containing ajax?

$(document).ready(function() {

var api = '//www.url.com'
var search = 'search?'
var orderBy = 'newest'

var url = api + search + orderBy

//API Call Setup
function newsFeed(data) {

$.ajax({
url: url,
success: function results(data) {
for (var i =0; i < data.response.total; i++) {
var content = '<li>' + data.response.results[i] + '</li>';
$('#news').append(content);
//end of for loop
};
}
});
}

newsFeed();

$("#selector").change(function(){
$('#news').empty(); //remove all child nodes
orderBy = $("#orderBy :selected").text();
newsFeed();
});
});

Answer

You're updating the orderBy variable, but then not updating the url with that. Move the declaration of url so it's in the same block as the AJAX call.

$(document).ready(function() {

    var api = '//www.url.com';
    var search = 'search?';
    var orderBy = 'newest';

    //API Call Setup        
    function newsFeed(data) {

        var url = api + search + orderBy; // This line has been moved

        $.ajax({
            url: url,
            success: function results(data) {
                for (var i =0; i < data.response.total; i++) {
                    var content = '<li>' + data.response.results[i] + '</li>';
                    $('#news').append(content);     
                };                   
            }
        });       
    }

    ...