I have a unique challenge: While on URL1(random wikipedia page), make an ajax request to URL2(100 most common words wikipedia page), create array from returned data to be used later.
I have to run this from the console while on "URL1" example:
So far I have been able to get very close with the following:
$.ajax({
url: 'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type: 'GET',
dataType: 'html',
success: function(data) {
Names = $.map($(data).find('.wikitable tr'), function() {
return $(this).find('td:last').text()});
console.log(Names);
}
});
But I'm getting blank values in my array.
While on URL2(link in the ajax request) the following code works perfect
var Names = $('.wikitable tr').map(function() {
return $(this).find('td:last').text() }).get(); console.log(Names);
I was gettin errors using this exact code because of the .get, after removing it, I got an array with the proper amount of elements, but they were all blank.
Thanks
Your logic is right, you are just using the wrong functions. $.map
and $().map
are different function with different contexts and different arguments.
Your problem should be solved if you use the correct map
function. Change
success: function(data) {
Names = $.map($(data).find('.wikitable tr'), function() {
return $(this).find('td:last').text();
});
console.log(Names);
}
to
success: function(data) {
Names = $(data).find('.wikitable tr').map(function() {
return $(this).find('td:last').text();
});
console.log(Names);
}
In the second form of map
, the this
keyword is set to DOM element.
I also noticed that would code is returning 105
texts instead of the 100
words in the table, as it is picking the table headers too. Another cool trick of .map
is that if you return null
, it will not include the value in the result. Therefore, you could something like
Names = $(data).find('.wikitable tr').map(function() {
return $(this).find('td:last').text() || null;
});
as a blank string evaluates to false
so the return
will return null
instead of ''
. Or, you could just make your selector more specific, such as:
Names = $(data).find('.wikitable tr td:odd').map(function() {
return $(this).text();
});
Could you also Inspect via F12, if any error is thrown.
XMLHttpRequest cannot load https://en.wikipedia.org/wiki/Most_common_words_in_English. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Just use the Js map to iterate over Jquery Objects(Html element Object)
$(data).find('.wikitable tr').map(function() {
return $(this).find('td:last').text();
JQuery map Works only on primitives Array not on object
$.map($(data).find('.wikitable tr'), function() {
return $(this).find('td:last').text();
});