I am making an ajax request and working with the success data. The problem is that the URL receiving the request can only work with one word at a time. So, if the query being sent contains a space, it breaks.
How do I check the incoming query, and send a separate ajax request for each word (if it contains more than one), then work with the data for both?
function get_syn(query) {
var words = query.split(' ',2); // this is how I'm splitting it up. 2 words max
jQuery.each(words, function(index, item) { // I'm using each to loop through the words
$.ajax({
type: 'GET',
url: 'http://www.example.com?query='+item,
success: function (data) {
// do some stuff with the results...
} // end success function
}); // end ajax
}); // end for each words
// outside of the each loop, I can not access the data
} // end function
The problem is I need to work with the data from both words together. The only way I've figured out how to do this is by using async
but there HAS to be another way:
$.ajax({
type: 'GET',
async: false,
url: 'http://www.example.com?query='+item,
success: function (data) {
var json = $.parseJSON(data);
if (index == 0) { // first word
firstword_data = json.data['array'];
} else { // if second word (there will only be a max of 2)
secondword_data = json.data['array'];
testfx(firstword_data);
} // end if second index
} // end success function
}); // end ajax
}); // end for each words
alert(firstword_data); // this works
} // end function