FCC wikipedia viewer not receiving data - javascript

I'm have some serious problems getting any response data through from the mediawiki api.
I'm trying to do the freecodecamp wikipedia viewer challenge and I'm coding it here:
https://codepen.io/dceaser334/pen/zpQXOJ
All i'm trying to do so far is GET the data and print it to the console using the following request:
$('.search-button').on('click', function() {
var searchInput = $('.search-input').val();
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=' + searchInput + '&format=json&callback=?', function(data) {
console.log(data);
});
});
All i'm trying to do so far is GET the data and print it to the console using the that request.
I'm getting this error in firefox:
Loading failed for the with source
“https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=jordan&format=json&callback=jQuery32105036538970753343_1518470620925&_=1518470620926”.
index.html:1
Nothing loads to the console and it seems like the request is blocked.
I've tried using origin=* which also makes no difference.
I'm a bit lost because this project has similar code for the GET request and works perfectly:
https://codepen.io/luckyguy73/pen/GqPzZO?editors=1010
$("#searchWiki").click(function(){
var q = document.getElementById("searchid").value;
$('#results').html('');
$.getJSON("https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=15&generator=search&origin=*&gsrsearch=" + q, function(data){
$('#results').append('<h2>Top 15 Wiki Search Results for "' + q + '"</h2>');
$.each(data.query.pages, function (i) {
$('#results').append("<p><a href='https://en.wikipedia.org/?curid=" + data.query.pages[i].pageid +
"' target='_blank'>" + data.query.pages[i].title + "</a></p>");
});
});
});
Any ideas on what I'm doing wrong here?
Thanks

I did it like this. Maybe you will be inspired by analyzing my code?
( function ( $ ) {
"use strict";
$(document).ready(function(){
function loadData() {
$(".information").text(""); // Reset data before new search.
$(function whiteFirst() {
const query = $(".wiki_query").val();
const myFirstWikiUrl = "https://en.wikipedia.org/w/api.php?action=opensearch&search=";
const mySecondWikiUrl = "&format=json&callback=wikiCallback";
const wikiUrl = myFirstWikiUrl + query + mySecondWikiUrl;
// MY WIKIPEDIA AJAX GOES HERE - TOP
const wikiRequestTimeout = setTimeout(function() {
$(".small-information").html("An error occurred! Application couldn't get Wikipedia resources!");
}, 5000); // This is 5 seconds!
$.ajax({
url: wikiUrl,
dataType: "jsonp",
type: "GET",
}).done(function(result) {
const itemsOne = [];
const itemsTwo = [];
const itemsThree = [];
$(result[1]).each(function(index, value) {
itemsOne.push(value);
});
$(result[2]).each(function(index, value) {
itemsTwo.push(value);
});
$(result[3]).each(function(index, value) {
itemsThree.push(value);
});
$(".information").hide();
$(".results").hide();
for (let i = 0; i < itemsOne.length; i++) {
$(".information").append("<a class='title' href=" + itemsThree[i] + " target='_blank'><div class='result'><p class='title' id='boldTitle'>" + itemsOne[i] + "</p><p>" + itemsTwo[i] + "</p></div></a>");
}
if (itemsOne.length === 0) {
$(".information").html("Nothing found!");
}
$(".results").show();
$("body,html").animate({
'scrollTop': $(".results").offset().top
}, 2000);
$(".information").fadeIn("slow");
clearTimeout(wikiRequestTimeout); // This will prevent timeout from happening!
});
// MY WIKIPEDIA AJAX GOES HERE - BOTTOM
});
return false;
};
$(".whiteButton").click(loadData);
$(".results").hide();
$(function() {
const offset = -50; // Optional offset
$(".back").click(function() {
$("html, body").animate({
scrollTop: $(".cover").offset().top + offset
}, 750);
});
});
});
} ( jQuery ) );

Related

AJAX search suggestions on user typing

The script makes an ajax call to a PHP file on input change, but the JSON isn't parsing and I don't know why
Here's the Javascript
input.addEventListener("input", (event) => {output.innerHTML = "Cerca " + document.getElementById("tophead-searchbar").value + " su Nevent";
var searchqueryajax = new XMLHttpRequest;
ajaxquerylink = "suggerimenti_query.php?query=" + document.getElementById("tophead-searchbar").value;
searchqueryajax.addEventListener("load", innerhtmlqueries());
searchqueryajax.open("GET", ajaxquerylink);
searchqueryajax.send();
function innerhtmlqueries() {
queriesarray = JSON.parse(searchqueryajax.responseText);
}
});
The input is document.getElementById("tophead-searchbar") and the output is the Result1, it says the value of the input
Here is the PHP Script:
$query = $_REQUEST["query"];
$queryresults = mysqli_query($name, "SELECT * FROM search_queries WHERE MATCH(ID, QUERY) AGAINST('$query') LIMIT 7");
if ($queryresults->num_rows > 0) {
$autocompleteresults = array();
while($row = mysqli_fetch_array($queryresults)) {
$results["ID"] = $row["ID"];
$results["value"] = $row["QUERY"];
$results["type"] = $row["TIPO"];
array_push($autocompleteresults, $results);
}
}
echo json_encode($autocompleteresults);
There are no PHP errors on the log and i don't see the PHP File on Network Tab of the browser F12 editor
I tried to do some things on Javascript code but i still don't notice the request on Network Tab
Edit: I also have another ajax call like this in the same file and it works
var checkajaxiflogged = new XMLHttpRequest();
checkajaxiflogged.addEventListener("load", checkajaxiflogged_function);
checkajaxiflogged.open("GET", "topbarprofileinformation.php");
checkajaxiflogged.send();
function checkajaxiflogged_function() {
topheadjsonresponse = JSON.parse(checkajaxiflogged.responseText);
document.getElementById("tophead-account-img").style.backgroundImage = "url('../beta/immagini_profilo/" + topheadjsonresponse.profiloimg + "')";
if (topheadjsonresponse.isloggedin == "yes") {
document.getElementById("tophead-accedi-btn").style.display = "none";
document.getElementById("tophead-account-img").style.display = "block";
document.getElementById("Immagine-Profilo-Menu-Principale").style.backgroundImage = "url('../beta/immagini_profilo/" + topheadjsonresponse.profiloimg + "')";
document.getElementById("Nome-Profilo-Menu-Principale").innerHTML = topheadjsonresponse.displayname;
document.getElementById("Username-Profilo-Menu-Principale").innerHTML = "#" + topheadjsonresponse.username;
}
}
You can use jquery for simplified get request
input.addEventListener("input", (event) => {
output.innerHTML = "Cerca " + document.getElementById("tophead-
searchbar").value + " su Nevent";
getData(); //Call the get function
});
// Ajax function to get data using jquery
function getData() {
let ajaxquerylink = "suggerimenti_query.php?query=" + document.getElementById("tophead-searchbar").value;
$.ajax({
url : ajaxquerylink,
type : "GET",
success : function(data)
{
let response = JSON.parse(data);
console.log(response);
}
});
}
I solved by myself, in this row
searchqueryajax.addEventListener("load", innerhtmlqueries);
I removed the () in innerhtmlqueries() and now the call response works
Thanks anyway for the support!

How can I conditionally allow or prevent submission execution?

The situation
I have a page in which I have multiple forms keeping track of the attendance and one progress_update.
On submit of the progress_update form I have got it so that ajax sends the attendance form submissions separately having used the preventdefault() method to stop the original submission, however I would like to on the condition that no errors were returned by the ajax methods allow the original submission that was originally prevented.
What I have so far:
The ajax function:
function send_attendance(name, lesson, form_id, i) {
var url = '/attendance/' + name + '/' + lesson
$('#error-' + i).hide('slow')
$('#error-' + i).html('')
$.ajax({
type: "POST",
url: url,
data: {
attended: $('#attended' + i).val(),
score: $('#score' + i).val(),
writing: $('#writing' + i).val(),
speaking: $('#speaking' + i).val()},
success: function(data) {
if (data.data.message == undefined) {
allow=false;
if (data.data.score[1] == undefined) {
var error_data = data.data.score[0]
} else {
var error_data = data.data.score[1]
}
$('#error-' + i).show('slow')
$('#error-' + i).html('<p style="color:red;">' + error_data + '</p>')
} else {
console.log(data.data.message) // display the returned data in the console.
}
}
});
}
The Intention:
The intention behind this ajax is to send the forms to a separate route for validation and then on success "receiving data.data.message == 'submitted'" pass to the next form in the loop, while on error set the allow variable to false and display the message in hopes to prevent the final form being submitted at the same time.
The call:
$('#update_form').submit(function (e) {
var allow = true;
for (var i = 0; i < studentcount ; i++) {
send_attendance(name=st[i], lesson=lesson, form_id='attendance-' + i, i=i)
}
if (allow == true){
} else {
e.preventDefault();
}
});
The Problem
In doing what I have done I have ended up with a situation of it either submits the ajax submitted forms and that is that preventing the submit form or it submits the form whether errors occured in the ajax that need to be displayed, now how do I get this to work in the way expected? I have tried the methods involved in these previous questions:
How to reenable event.preventDefault?
How to unbind a listener that is calling event.preventDefault() (using jQuery)?
which revolve around using bind and unbind but this doesn't seem to work as needed and results in a similar error.
Any advice would be greatly appreciated.
Edit:
I have adjusted the code based on the comment below to reflect, however it still seems to be evaluating the allow before the ajax have completed. either that or the ajax function isn't changing the allow variable which is set in the submit() call how could i get this to change the allow and evaluate it after the ajax calls are complete?
The Ajax call
function send_attendance(name, lesson, form_id, i) {
var url = '/attendance/' + name + '/' + lesson
$('#error-' + i).hide('slow')
$('#error-' + i).html('')
var form = $('#' + form_id)
$.ajax({
type: "POST",
url: url,
data: $('#'+ form_id).serialize(),
context: form,
success: function(data) {
console.log('done')
if (data.data.message == undefined) {
allow = false;
if (data.data.score[1] == undefined) {
var error_data = data.data.score[0]
} else {
var error_data = data.data.score[1]
}
$('#error-' + i).show('slow')
$('#error-' + i).html('<p style="color:red;">' + error_data + '</p>')
} else {
console.log(data.data.message) // display the returned data in the console.
}
}
});
The function is being called here:
$('#update_form').submit(function (e) {
e.preventDefault();
var allow = true;
var deferreds = [];
for (var i = 0; i < studentcount ; i++) {
deferreds.push(
send_attendance(st[i], lesson, 'attendance-' + i, i));
}
$.when(...deferreds).then(function() {
if (allow == true){
console.log('True')
} else {
console.log('False')
}
});
I also tried:
$('#update_form').submit(function (e) {
e.preventDefault();
var allow = true;
var deferreds = [];
for (var i = 0; i < studentcount ; i++) {
deferreds.push(
send_attendance(st[i], lesson, 'attendance-' + i, i));
}
$.when.apply(deferreds).done(function() {
if (allow == true){
console.log('True')
} else {
console.log('False')
}
});

Angularjs how to preserve url in function?

Hi I am developing one Angularjs application. I have three cascading drop downs. Based on the selected values in drop down i am binding div with data received from api(div with ng-repeat). I have implemented paging.
On page load i am binding first dropdown.
var arrMakes = new Array();
$http.get(url + 'api' + '/Vehicle/' + 'GetVehicleMake').success(function (data) {
$.map(data.data, function (item) {
arrMakes.push(item);
});
$scope.list = arrMakes;
var dynamicUrl = url + 'api' + '/Vehicle/' + 'Getcars/';
//bind data to Div randomly.
getcadetails(dynamicUrl);
}).error(function (status) {
});
function getcadetails(baseurl)
{
var arrallcarDetails = new Array();
$http.get(baseurl,{ params: $scope.pagingInfo }).success(function (data) {
$.map(data.data, function (item) {
arrallcarDetails.push(item);
});
$scope.carDetails = arrallcarDetails;
$scope.pagingInfo.totalItems = data.totalcount;
}).error(function (status) {
});
}
getcadetails is a function i am calling from different scenarios. For example,
ng-change event of first dropdown
$scope.getModel = function (selectedMake) {
var selectedMakeData = selectedMake.ID;
var arrModel = new Array();
$http.get(url + 'api' + '/Vehicle/' + selectedMakeData + '/GetVehicleModel').success(function (data) {
$.map(data.data, function (item) {
arrModel.push(item);
});
$scope.Modellist = arrModel;
var dynamicUrl = url + 'api' + '/Vehicle/' + 'Getcars/' + '?MakeID=' + selectedMakeData;
//bind data to Div randomly.
getcadetails(dynamicUrl);
}).error(function (status) {
});
}
In paging i have below function. This is executed when i click on page numbers for example 1,2, etc
$scope.pageChanged = function (currentPage) {
$scope.pagingInfo.pageNumber = currentPage;
getcardetails();
};
Here my problem starts. If i click on any page number $scope.pageChanged function executes. I will get page number to send it to server. after that i will call getcadetails(?). Now how can i get baseurl for getcadetails? Is there any way i can implement this in better way? Any help would be appreciated. Thank you.
i think u can define a variate for selectedMakeData, and define a function to create url. every time before invoke getcardetails() u should calculate the dynamicUrl.
code looks this:
var selectedMakeData = 0;
selection.addEventListener('change', () => {
selectedMakeData = newData;
});
$scope.pageChanged = function (currentPage) {
var url = getUrl();
$scope.pagingInfo.pageNumber = currentPage;
getcardetails(url);
};
function getUrl() {
// return url baseed on selectedMakeData
}

Issues in Uploading File using ajax in IE7 and IE8

I'm trying to upload a file in IE7 and IE8 browser using FileAPI library, but unfortunately it is not working. It is working in all the other browser but not in IE7, IE8 and it is my business requirement to make it work in IE7, IE8 too.
Here is my js code
jQuery(function ($){
$(document)
.on('click', '.imageLabel', function (evt){
imageUploadId = $(this).attr("id").split("_")[1];
previewImage = document.getElementById('previewHolderDiv_' + imageUploadId);
$("#imageError_" + imageUploadId).html("");
errorMessageUl = document.getElementById('imageError_' + imageUploadId);
removeImageIcon = document.getElementById('removeImage_' + imageUploadId);
})
var form = document.forms.vehicleDocumentForm;
var input = form.vehicleImage;
var uploadOpts = {
url: '/save-vehicle-document',
data: {},
name: 'vehicleImage',
activeClassName: 'upload_active'
};
var _onSelectFile = function (evt/**Event*/){
var file = FileAPI.getFiles(evt)[0];
if( file ){
_uploadFile(file, imageUploadId);
}
};
var _uploadFile = function (file){
uploadOpts.data = {"imageId" : imageUploadId};
var opts = FileAPI.extend(uploadOpts, {
files: {},
upload: function (){
form.className += ' '+uploadOpts.activeClassName;
},
complete: function (err, xhr){
//enableSellYourButtons();
form.className = (' '+form.className+' ').replace(' '+uploadOpts.activeClassName+' ', ' ');
var response = JSON.parse(xhr.responseText);
if( response.result == "fail"){
previewImage.html = "";
$("#imageError_" + imageUploadId).html("<li>" + response.message + "</li>");
} else {
$("#imageError_" + imageUploadId).html("");
$("#vehicleImageName_" + imageUploadId).attr("value", response.message);
}
}
});
opts.files[opts.name] = file;
FileAPI.upload(opts);
};
FileAPI.event.on(input, "change", _onSelectFile);
}); // ready
I'm getting an error
SCRIPT445: Object doesn't support this action
File: FileAPI.min.js, Line: 2, Column: 11608
My FileAPI version is 2.0.11
Any help would be greatly appreciated.
Thank you.
According to caniuse, the FileApi is not compatible with IE7/8.

Displaying images from JSON

Trying to display the cover art with the results. Something in the img src tag is causing the app not to load. If I just point the img to data.tracks[i].album.name (obviously not a real url, but enough to test if it's working) it pastes it in just fine, but the moment I change it to paste the url in place, it makes the whole app stop working.
$('#findTracks').click(function (e) {
e.preventDefault(); // override/don't submit form
$('#recommendations').empty();
var artist = $('#artist').val();
var userid = "";
var playlistid = "";
$.ajax({
url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
type: 'GET',
dataType: 'json',
success: function(data) {
if (data.tracks.length > 0) {
var tracksLength = data.tracks.length, html = '';
for (var i=0; i<tracksLength; i++) {
var href = '';
if (data.tracks[i].album.availability.territories.indexOf(' GB ') !== -1) { // data.tracks[i].href
href = data.tracks[i].href;
href = 'makeReq(\''+data.tracks[i].name + ' by '+data.tracks[i].artists[0].name+'\')';
html += '<li>' +data.tracks[i].name + ' by '+data.tracks[i].artists[0].name+ ' <img src="' +data.tracks[i].album.images[0].url+ '" />';html += '</li>';
html += '</li>';
}
}
$('#third').css('display', 'block');
$('#recommendations').append(html);
} else {
$('#recommendations').append('<li>No matches returned.</li>');
$('#third').css('display', 'none');
}
},
error: function(err) {
alert("The Spotify API failed to return a response.");
}
});
});
This is my first time ever coding in javascript so please go easy on me! lol
EDIT:
This seems to be running well! However, many of the songs do nothing when I click on them
For example, type "Don't Stop" and only "The Black Eyed Peas - Don’t Stop The Party" works out of the first ten...anybody know why?
also, anybody known why "if (data.tracks[i].album.availability.territories.indexOf(' GB ') !== -1)" is in there? If I take it out this all stops working...I am not in G.B.
If you look in the console you are getting the error
Uncaught TypeError: Cannot read property '0' of undefined
looking at the data the query returns we notice that data.tracks[i].album returns
{
"released": "2006",
"href": "spotify:album:2knAf4wg8Gff8q1bXiXCTz",
"name": "The Dutchess",
"availability": {
"territories": "MX"
}
}
there is no property images so when you call
data.tracks[i].album.images[0]
you get the undefined error, causing the script to halt execution.
I'm unfamiliar with the spootify api but taking a quick glance at the api theres the endpoint for get-album. Heres what I was able to come up with to get the album art
$.get("http://ws.spotify.com/search/1/track.json?q=Fergie",function(data){
var albumId = data.tracks[97].album.href.split(":")[2];
$.get("https://api.spotify.com/v1/albums/" + albumId,function(albumResponse){
var firstImage = albumResponse.images[0];
$('body').append($('<img/>',{
src : firstImage.url,
width : firstImage.width,
height : firstImage.height
}));
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body></body>
You should research more into how to get the album art since I'm unsure if this is the optimal solution.
The search endpoint you mentioned is different from the one your using.
One your using
url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
One you linked to
url: 'https://api.spotify.com/v1/search?q=' + artist + '&type=track,artist&market=GB',
Heres your solution with the change in endpoint
$('#findTracks').click(function(e) {
e.preventDefault(); // override/don't submit form
$('#recommendations').empty();
var artist = $('#artist').val();
var userid = "";
var playlistid = "";
$.ajax({
//url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
url: 'https://api.spotify.com/v1/search?q=' + artist + '&type=track,artist&market=GB',
type: 'GET',
dataType: 'json',
success: function(data) {
if (data.tracks.items.length > 0) {
data.tracks = data.tracks.items
data.artists = data.artists.items
var tracksLength = data.tracks.length,
html = '';
for (var i = 0; i < tracksLength; i++) {
var href = '';
href = data.tracks[i].href;
href = 'makeReq(\'' + data.tracks[i].name + ' by ' + data.tracks[i].artists[0].name + '\')';
html += '<li>' + data.tracks[i].name + ' by ' + data.tracks[i].artists[0].name + ' <img src="' + data.tracks[i].album.images[0].url + '" />';
html += '</li>';
html += '</li>';
}
$('#third').css('display', 'block');
$('#recommendations').append(html);
} else {
$('#recommendations').append('<li>No matches returned.</li>');
$('#third').css('display', 'none');
}
},
error: function(err) {
alert("The Spotify API failed to return a response.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Artist:
<input type="text" id="artist" />
<button id="findTracks">Find Tracks</button>
<div id="recommendations"></div>

Categories