Querying Wikipedia API sometimes causes html to disappear - javascript

Currently attempting to build a Wikipedia viewer as per the Free Code Camp project. You can see the whole CodePen here. Now, in my console I can see that sometimes, I get a response with the data I was looking for. Other times, I get no response at all, and still other times running the search causes all of the content on my page to simply disappear. I thought initially it might be a caching issue, but there are instances where it will successfully run multiple searches in a row then either stop or disappear; and others where it will not receive any data at all.
When I have these malfunctions, the console does not display any errors, so I don't have any feedback about what's going wrong.
Here's the relevant code:
function wikiSrch(){
var srchParam = "";
var srchRes;
$("#searchB").click(function(){
srchParam = $("#inpt").val();
$.getJSON("https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + srchParam + "&format=json&callback=?", function(data){
console.log(JSON.stringify(data));
});
});
}
$(document).ready(function(){
wikiSrch();
})

Related

Searching data using Youtube API

Extremely new at this, but wanted to try to build something. Decided on a simple landing page that would assist in pulling Youtube videos. Got my API key and got to building. Ran into a few issues. Found out that it can't call from a local HTML file, so worked out another way to test, but now I have another issue.
I have the following code set to run when a button is pressed, submitting the text in form as the variable topic.
function search() {
var hdi = "how do i ";
var request = gapi.client.youtube.search.list({
part: 'id',
q: hdi + topic,
});
request.execute(onSearchResponse);
};
function onSearchResponse(response){
var responseString = JSON.stringify(response, " ", 2);
console.log(responseString);
}
But I cannot seem to get the response I'm looking for. The JSON data I get seems to correspond to medley of search engines (Yahoo, duck duck go, ect) instead, not the JSON data for the YouTube search.
Here is a CodePen, if that assists more. I have some code commented out that I'm waiting to work on until I get this part implemented. Thanks for any help you can give me!
https://codepen.io/billsobill/pen/OvxNON

Node/Javascript Redirect Not Working?

I have built a form to add some dummy data to a Mongo collection for testing purposes. The function to add the data seems to be working ok in that the data is being added ok, but, for some reason, the redirect command at the end of the function is not doing its thing. The data comes from a bog standard HTML form. Here is the code for adding the data:
router.post('/addacc',function(req,res){
var sljEdate = "";
var pljEdate = "";
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/stc';
MongoClient.connect(url,function(err,db){
if(err){
console.log("Connection Error");
}else{
console.log("connected to mongo");
var collection = db.collection('account');
var query = {accountID: req.body.acc_id,companyName: req.body.acc_name,companyEmail:req.body.acc_email,companyPhone:req.body.acc_phone,companyPostCode:req.body.acc_postcode,
photographers: {phtID:"",phtName:"",phtPhone:"",phtEmail:"",phtLoc:"",preferredContact:"",lastJob:"",pljEpoch:pljEdate,phtNotes:""},
schools: {schoolID:"",schoolName:"",schoolPhone:"",schoolEmail:"",schoolPostCode:"",lastJob:"",sljEpoch:sljEdate,notes:""}};
collection.insert(query,function(err,result){
if(err){
console.log("Error inserting Account record",err);
}else{
console.log("Data Insert Success");
res.redirect("/forms");
}
db.close();
});
}
});
});
I added lines to log to the console in a few places so that I could check progress and they all fire, including the final 'Data Insert Success' one. The res.redirect which follows it, however, does nothing. In the browser the URL remains as '/addacc', though the node console shows a subsequent GET for the '/forms' URL.
I've tried a few variations for the redirect, using e.g. res.send("test") just to try and output something, also a res.render function, but none of them seem to work.
I'm pretty sure that I have missed something simple, but I've been staring at the code for too long and I can't see anything wrong with it. In fact, I've had nearly identical code working lots of times. The only thing I'm doing differently this time is that I'm inserting into a Mongo collection which includes embedded documents, but the data insert is not the problem as the data gets in fine.
Help please!
Ok, it seems that the Node problem above was a bit of a red herring. The redirect is actually working ok (MrWillihog's comment above is duly noted for future reference anyway). I thought it must be as all the response codes on the npm console checked out fine. The problem is actually to do with the rendering of the Jade template. Specifically something to do with the the file layout.jade which I use to set out the HTML head. For some reason (yet to be determined) things work fine when calling the /forms page directly in the URL. The file forms.jade starts in the standard way with
extends layout
block content
With the opening BODY tag in layout.jade the page fails to load properly when called from the redirect: the layout.jade file renders (I put an H1 in there to check), but forms.jade doesn't.
I moved the BODY down in to forms.jade (under block.content) and it started working though, interestingly, the URL in the address bar remains as '/accadd'
Again I'm a bit stumped as I have used this pattern quite a few times with no issue. I'm guessing that I've just forgotten something simple. I'll keep digging until I find the answer, but at least now I should be looking in the right place.

ASP.NET MVC/jQuery/AJAX: link fails to work first time, but works second time (after page reloads)

Preface
For this question, I have a MVC partial view. The view has a section which displays a list of documents. Each document has a hyperlink: when clicked, the hyperlink takes the user to a second page view displaying additional information.
The link is inside an unordered list:
<a style="text-decoration:underline;" onclick="sendToDocketSearch('#currentDocument.DktYear','#currentDocument.DktSequence','#currentDocument.DktSubActionID');">#currentDocument.DktYear.ToString().PadLeft(2, '0') - #currentDocument.DktSequence.ToString().PadLeft(5, '0')</a>
When the user clicks the link, it takes them to a sendToDocketSearch javascript function (to prepare to search for the document):
var sendToDocketSearch = function (yearOfDocket, sequenceOfDocket, dktSubActionIDOfDocket) {
jQuery.ajax({
type: "POST",
url: "#Url.Action("DocketSearchOnDemand")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ docketYear: yearOfDocket,
docketSequence: sequenceOfDocket,
DktSubActionID: dktSubActionIDOfDocket,
userIsAuthorized: '#Model.userIsAuthorized' }),
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
submitForm();
}
Note that the page/view/form is submitted after the following controller method is run:
public ActionResult DocketSearchOnDemand(string docketYear, string docketSequence, decimal DktSubActionID, bool userIsAuthorized, PortalIndexView viewmodel)
{
System.Web.HttpContext.Current.Session.Add("userIsAuthorized", userIsAuthorized);
string docketSearch = docketYear + "-" + docketSequence;
System.Web.HttpContext.Current.Session["DocketSearchOnDemand"] = docketSearch;
if (DktSubActionID > 0)
{
System.Web.HttpContext.Current.Session["DktSubActionID"] = DktSubActionID.ToString();
System.Web.HttpContext.Current.Session["searchingCustomID"] = true;
}
else
{
System.Web.HttpContext.Current.Session["DktSubActionID"] = "1";
System.Web.HttpContext.Current.Session["searchingCustomID"] = false;
}
return View(viewmodel);
}
The above controller method runs; then, because the form is submitted, the HttpPost action for the page takes place. When running it on my local PC, the link is clicked and the next page is loaded without drama.
Problem
The problems start when I upload the code to the dev/test server. I don't know how to use breakpoints while troubleshooting an active website, so I follow along with the browser developer tool to monitor network traffic.
When clicking the link when running the website on my localserver, the process continues:
the hyperlink takes me to a method where I pass information to be searched
the page/view/form is submitted
the controller redirects where I have to go.
When I click the link on the site and it's on the server, the first click is completely ignored - network traffic shows that it tries to navigate to the controller via the javascript function above, but the failure happens so fast I can't even take a screenshot of it. The page reloads a second time at this point.
When I click on the same link a second time, it works without fail.
I believe the view/javascript/controller code works because it works the second time (and on subsequent attempts). It just flagrantly fails the first time on the server; after that, the user is fine. I'd like to prevent that "first-time" failure, however, and I'm wondering what the problem could be...
Bad timing
I may be passing the information too early (or too late for my website/server to process it properly). The page does it correctly the second time, so maybe I'm just "jumping the gun" by not waiting a little longer for page-loading processes to sort themselves out. (Maybe I can fiddle around with the $(document).ready() javascript portion of the first page to "delay" allowing people to click a link.)
Code error
I'll be glad to admit bad code if I'm genuinely messing something up. Maybe it's my javascript function, or maybe it's the code in my controller; at any rate, something is making the first pass of that function call be rejected. Maybe my code is bad because the problem doesn't happen the second time, and I'm getting a false sense of security (i.e. there are problems with my code that the system is willing to forgive after the page has thoroughly loaded).
Server problem/miscellaneous
I'm wondering if I missed something when I uploaded my latest changes, or if I should have contacted my network team in case there are permissions that need to be activated for the site to work smoothly. I'm already in touch with them regarding something else, so I might take advantage of the opportunity today.
There is an alternative in place that could help me prevent this problem from happening, but I want to find out why the "first-time" failure happens. Other similar actions fail the first time on the site, and I'd like to apply the insights from fixing this issue to them.
Thank you for looking at this issue. Have a great day.
Are you sure you want to call submitForm(); before your jQuery.ajax has finished? your ajax call is async so it will hit submitForm(); before it has had time to finish. should submitForm(); be in your success event instead?

Show what I am listening to on Spotify

I am using this plugin to enable me to display what I am currently listening to live on my website: https://github.com/derekmartinez18/Simple-Ajax-Spotify-Now-Playing
A piece of JavaScript will run on page load, which connects to the PHP which via API checks what I am listening to, grabs the title etc, if successful sends back to the JavaScript and displays via HTML.
I've echoed out what the PHP is getting and can see it's correctly grabbing all the recent songs, names etc. Therefore because nothing is appearing on the page maybe it's the JavaScript. I've pasted it below with pastebin link to php too.
JavaScript
<script type="text/javascript">
function get_spotify() {
$.ajax({
type: 'POST',
url: '/Scripts/last.fm.php',
data: { request: 'true' },
success: function(reply) {
$('.now-playing').html("<p>" + reply + "</p>");
}
});
}
window.onload = get_spotify;
</script>
Pastebin of PHP - http://pastebin.com/eZUH6BNU
A snippet of the API output which is being past over to the PHP (it's huge so didn't paste it all.):
{"recenttracks":{"track":[{"artist":{"#text":"LMFAO","mbid":"ed5d9086-e8cd-473a-b96c-d81ad6c98f0d"},}
Live Link - http://bit.ly/1ewTe8l
Based on the example you have given below your question, the problem is that there is no element with a class of now-playing.
Your page seems to have been cut short, perhaps due to an error, but the ajax request fires and in the console I can see the response (the url is actually echoed before that as well):
I am currently listening to 01. Circles Around The Sun by Dispatch on Spotify.
Adding a <div class="now-playing"></div> should do the trick.
Edit: Note that your key is visible in the response as you are echoing the url you are making a request to. It might be a good idea to change the key when you have solved your problem.

Script error: "Unable to get value of the property 'split': Object is null or undefined

I searched around, and couldn't find an answer to my question. I'm very new at coding, and at work, we have an application that current names that are logged in, and what they are doing.
Recently, they have changed from jquery 1.4.1 to jquery 1.8.3. Ever since then, I cannot get the results to process correctly, because of the following error;
"Unable to get value of the property 'split': Object is null or undefined"
I have the code setup to grab the results and split them;
function processAgents(xData, status) {
var avail = xData.responseText.split("|")[0];
var acw = xData.responseText.split("|")[1];
var total = xData.responseText.split("|")[2];
var breaks = xData.responseText.split("|")[3];
var pending = xData.responseText.split("|")[4];
The application is setup to open as an HTA file which opens up the PHP script.
Any help would be appreciated, please let me know if I left anything out!
Thanks!
EDIT 1
I did some more investigating, and it looks like I'm not getting data from my process request. This is how it is currently setup
function updateAgents() {
var ts1 = new Date().getTime();
$.ajax({
url: "http://SERVER/AgentSrc.php?x=" + ts1,
complete: processAgents
I'm not sure if this is processing correctly since they went to jquery 1.8.3.
EDIT 2
So after looking into it more, it doesn't appear that the script is getting the data from the server, even though I have access. If I make a local file and put the information in it, it will pull the information and split it, but if I point to the path of the file on the server, it won't get the information. But the strange thing is, if I run it using jquery 1.4.1, it pulls the data fine, but can't display it. But with 1.8.3, it doesn't allow me to pull it from the server.
thanks again!
This will give some clarity
xData.responseText.toString().split("|")[0];
(split is part of string not jQuery)
Here is a possible explanation: in earlier versions of jQuery, ajax calls returned an xmlHttpRequest (XHR) object. Recent versions return a promise (jqXHR) instead.
See this page for more details.

Categories