I am building a simple program that search the each input word or number for image link on Google.
The below code contains two array link and search. The program loops through numbers inside search array,get the link respectively and stores it inside link array.
The result gathered on link array should be in order or synchronous with search array link.For example: Given two array x and y, the result of array x should be store inside array y in such a way that they are associate with each other respectively
$(document).ready(function () {
var input = '1 2 3 4 5 6 7 8 9 10';
var search = input.split(' ');
var link = new Array();
var j = 0;
for (var i = 0; i < search.length; i++) {
var look = new URL('https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=' + search[i] + '&callback=?');
$.ajax({
url: look,
dataType: 'json',
async: false,
success: function (data) {
link[j] = (data.responseData.results[0].url);
j++;
}
});
}
$('#show').click(function () {
$('#display').empty();
$.each(link, function (key, value) {
$('#display').append(value + '<br>');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="show">Show</button>
<div id="display"></div>
Result:
link =[https://pbs.twimg.com/profile_images/2478399688/6gyep59fumb340ima588_400x400.png,
http://world.new7wonders.com/content/uploads/2014/04/7.jpg,
http://upload.wikimedia.org/wikipedia/commons/9/92/Junction_4.svg,
http://static.comicvine.com/uploads/original/11111/111116692/3150494-7873411214-5.jpg.jpg,
http://upload.wikimedia.org/wikipedia/commons/thumb/e/e3/8_ball_icon.svg/2000px-8_ball_icon.svg.png,
http://chubbygirldiary.com/wp-content/uploads/2015/01/Day-9.png,
https://blognumbers.files.wordpress.com/2010/09/2.jpg,
http://cdn2.hubspot.net/hub/149308/file-391958040-png/three_reasons_individual_superior.png,
http://cdn2.hubspot.net/hub/391217/file-741970441-jpg/Blog_Images/6.jpg,
http://lextran.com/uploads/files/10.png]
The result of array link[i](i represent index) is not respectively associate with array search[i](i represent index) or they are not related
.
The link of array search[1](i.e number two index at 1) doesn't associate with array link[1],
(i.e
http://world.new7wonders.com/content/uploads/2014/04/7.jpg
, which is index at 1)
Expected result:
The data inside both array link and search should be related.For example the data of array search[2](2 represent index) should associate with data of array link[2](2 represent index)
After doing some research I found this question Is it possible to set async:false to $.getJSON call. I believe that the problem should be fixed, but it didn't.
I still don't understand why async:false is not behaving the way it should be.I am completely new to ajax. If it's not the problem with ajax, I would much appreciated if you would point out other bugs.
Thank you for your time.