Danielle Webb
Danielle Webb

Reputation: 25

Using a for loop in a jQuery AJAX request

I'm new to JavaScript and jQuery, so I'm not even sure this is possible

I'm trying to run an AJAX request in which a search runs through an array of titles so that I can then later store other information that is returned for later use. Can I put a for loop inside the query parameter to achieve this? My code is below but it's not returning anything right now.

$.ajax('http://api.themoviedb.org/3/search/movie', {
    type: 'GET',
    dataType: 'jsonp',
    data: {
        api_key: myApiKey,
        query: for (var i = 0; i < movies.length; i++) {
            console.log(movies[i]);
        },
        success: function (result) {
            console.log(result);
        }
    }); // end search ajax request

Upvotes: 0

Views: 80

Answers (1)

xdazz
xdazz

Reputation: 160843

You can't use for loop as a value of a object property.

If the api accepts an array to as the query parameter, then just pass the array to it.

        data : {
            api_key : myApiKey,
            query : movies
        }

If it accepts a string with comma splited string, then convert the array to string by join method.

        data : {
            api_key : myApiKey,
            query : movies.join()
        }

And if the api doesn't support multiple move search for one query, you have to make a ajax request inside a loop.

Upvotes: 1

Related Questions