Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Opulent Ceremony
Feb 22, 2012

necrotic posted:

The Library object (and subsequently Q.fn) is created one time;

I'm confused, how is Library being created once in this case? It looks like whenever you call Q() the Library constructor function is run and a new object is returned.

Adbot
ADBOT LOVES YOU

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

CuddleChunks posted:

I'd love some help with learning how to pull data from a remote JSON API into my silly little page.

code:

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
  <title>A JSONP example</title>
</head>
<body>
  <div id="test">default.</div>
<script>
$(document).ready(function () {
	var url = "http://www.macvendorlookup.com/api/v2/";
	url += "00026f123456";
	url += "?callback=?";
    $.getJSON(url, null, function( data ) {
        document.getElementById('test').innerHTML = data.contents;
    });
});
</script>
</body>
</html>

Nothing happens in the Chrome debugger so I guess it's probably failing silently. At least it's not a syntax error that it's spitting out this time. :v:

On my phone, so somewhat guesswork, but typically the callback parameter is the name of the function that the returned script will invoke with the JSON data. In your case you're giving it ? which isn't a legal function name, nor do you have a function defined to receive it.

Furthermore, JSONP isn't JSON, so getJSON will likely choke on the script file that comes back.

Typically JSONP is used to avoid cross-site woes, by putting the URL in a <script> tag. When the script is loaded, it calls the specified — and hopefully defined!—function with the desired data. If the API server works with cross-site XHR then you don't need to use JSONP (which would be preferable), but if it doesn't then getJSON isn't going to fly either.

Xenoveritas
May 9, 2010
Dinosaur Gum
That's just how jQuery.getJSON works. It looks for "callback=?" in your query and generates a function name for the callback to hit. (Actually, I think it looks for just "=?" so you can name the parameter whatever you want.)

I'd check to make sure your endpoint is really JSONP. Check the network pane. You should see that jQuery generated a request that looks like:

GET http://www.macvendorlookup.com/api/v2/00026f123456?callback=jsonp1249635980723

And that you get a response that looks something like:

JavaScript code:
jsonp1249635980723({
  "your": "data here"
})
Actually, what you should see is that jQuery injected a <script> element into the document that looks like:

HTML code:
<script src="http://www.macvendorlookup.com/api/v2/00026f123456?callback=jsonp1249635980723"></script>
But that should still generate the request in the network pane.

If you don't see that, the endpoint doesn't support JSONP and that's not going to work.

Checking the API docs you linked to, it looks like it in fact doesn't support JSONP. So just remove the ?callback=? part and what (hopefully) will happen is that it does support CORS and regular AJAX will work without the need for JSONP.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Oh! That's a...delightful bit of magic.

Thanks, sorry for the noise.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
It doesn't support JSONP or CORS. You're poo poo out of luck, outside of emailing the guys.

Xenoveritas
May 9, 2010
Dinosaur Gum
Well, or writing a local proxy running on the same domain. The great traditional solution to a problem that by all rights shouldn't exist in the first place. gently caress you, SOLR. Er, what were we talking about again?

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Xenoveritas posted:

Well, or writing a local proxy running on the same domain. The great traditional solution to a problem that by all rights shouldn't exist in the first place. gently caress you, SOLR. Er, what were we talking about again?

You could always just roll with --disable-web-security in Chrome or enabling access to datasource across domains in IE security settings if this is just a personal thing.

CuddleChunks
Sep 18, 2004

Suspicious Dish posted:

It doesn't support JSONP or CORS. You're poo poo out of luck, outside of emailing the guys.

Thanks to everyone who peeked at this. I was going nuts trying to get it to work and am too new to this JSON stuff to know the difference between my own messup and the remote site.

Sheesh. "Here's our API! You can totally use it duders!" HOW???? I'll send them a message. Thanks again for the info everyone.

Xenoveritas
May 9, 2010
Dinosaur Gum

Bruegels Fuckbooks posted:

You could always just roll with --disable-web-security in Chrome or enabling access to datasource across domains in IE security settings if this is just a personal thing.

It is not.

The whole cross-domain origin restriction is so stupid. Especially when it leads to things like JSON-P. "Well, we can't get raw text from another domain for 'security reasons,' so let's instead inject arbitrary code from that other domain because that we are allowed to do!" (I could see restricting cross-domain requests to GET, but the whole AJAX cross-domain restriction is so pointlessly stupid.)

CuddleChunks posted:

Sheesh. "Here's our API! You can totally use it duders!" HOW???? I'll send them a message. Thanks again for the info everyone.

Presumably the intention is that you do it from code that's outside the browser, which doesn't have to deal with cross-domain restrictions.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

The cross domain stuff is pretty important, so that I don't make a bunch of XHRs from my random blog and use your established Facebook/gmail/bank/intranet credentials to act on your behalf.

necrotic
Aug 2, 2005
I owe my brother big time for this!

Opulent Ceremony posted:

I'm confused, how is Library being created once in this case? It looks like whenever you call Q() the Library constructor function is run and a new object is returned.

A new object is allocated, but the prototype of that object is already allocated in the IIFE. If you did the entire thing in Q() the object and the prototype would be allocated for each call.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

CuddleChunks posted:

Sheesh. "Here's our API! You can totally use it duders!" HOW???? I'll send them a message. Thanks again for the info everyone.

JSON isn't restricted to Javascript. I've accessed JSON endpoints with Python and PHP. It's such an established format that every language has libraries for handling it.

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker

CuddleChunks posted:

Thanks to everyone who peeked at this. I was going nuts trying to get it to work and am too new to this JSON stuff to know the difference between my own messup and the remote site.

Sheesh. "Here's our API! You can totally use it duders!" HOW???? I'll send them a message. Thanks again for the info everyone.

Save this as passthrough.php in the same folder you have your html:
php:
<?
echo file_get_contents('http://www.macvendorlookup.com/api/v2/'.
                       preg_replace('/[^a-z0-9\:\-\.]/i', '', $_GET['mac']));

?>
And change the javascript url statement to this:
JavaScript code:
    var url = "passthough.php?mac=";
    url += "00026f123456";
Tada. I'm guessing that your host has php enabled, but that's a pretty safe bet.

Xenoveritas
May 9, 2010
Dinosaur Gum

Subjunctive posted:

The cross domain stuff is pretty important, so that I don't make a bunch of XHRs from my random blog and use your established Facebook/gmail/bank/intranet credentials to act on your behalf.

So don't send cookies on cross-domain requests. That's not what it's intended to protect against anyway, the cross-domain restriction is intended to prevent me from reading data on other sites using your credentials. I can send any GET request to any URL I want anyway, I just can't read the results. Really I can do the same thing with POSTs using embedded <iframe>s and forms.

CORS is an acceptable solution, it's just annoying it took so long to arrive. (Although it's old enough now that pretty much every browser supports it.)

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Being able to read data is a pretty big deal, it's not about destructive GET. Even if dropping cookies/basic-auth/client certs/etc for all cross-domain XHR was desirable, which it's not really, lots of intranet content is protected simply by network perimeters and not additional auth.

Microsoft randomly invented XDomainRequest to do anonymous requests, but even then they needed a positive signal from the server that the response was allowed to be exposed to the requesting script.

loquacius
Oct 21, 2008

I've been searching around on this with little success and figured I might as well ask here: is there any amount of Javascript/JQuery trickery (or PHP if it's really necessary, I GUESS) which would allow me to set an element which is inside an iframe to stay in a fixed position relative to the browser window? All the usual methods appear to just make things stay in one position relative to the iframe rather than to the window, which doesn't help.

I've fooled around with the idea of using JQuery to spit the object's markup into the parent document, but that's not a good solution since the iframe's content comes from a different server than the outer document and there's a lot of code on that server which the elements are reliant on and which I really don't want to have in two different places.

spiritual bypass
Feb 19, 2008

Grimey Drawer

loquacius posted:

I've fooled around with the idea of using JQuery to spit the object's markup into the parent document, but that's not a good solution since the iframe's content comes from a different server

That won't work, either, since you can't read the contents of an iframe on another server.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

You can if they share a common eTLD+1 and they both set document.domain.

Xenoveritas
May 9, 2010
Dinosaur Gum
Which frame do you have control over and why do you want to do this in the first place?

I suspect that if you have control over both frames the answer is "yes." You can use window.postMessage to send messages between a parent document and iframes within it. From this you could either play around with keeping the element inside the iframe by updating scrolling positions or simply have the iframe send a message to the parent with the data necessary to recreate the element itself.

I don't remember what properties are accessible via window.frameElement but that's another thing that might be useful.

loquacius
Oct 21, 2008

Yeah, I control both frames. The reason I'm trying to do this is that there's a UI element which I want to always be in one place on the screen, but the fact that it's located inside the iframe (and dependent on code hosted on the iframe's server) is kind of making that surprisingly difficult to pull off. Passing messages back and forth between the windows is a possible solution (which I'll check into when I get into work tomorrow); thanks!

qntm
Jun 17, 2009
Can someone explain to me how Chai's chained assertion stuff works? I don't see how a line of JavaScript code like expect(false).to.not.be.ok; can actually do anything without making ok() into a function call.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

qntm posted:

Can someone explain to me how Chai's chained assertion stuff works? I don't see how a line of JavaScript code like expect(false).to.not.be.ok; can actually do anything without making ok() into a function call.

They've defined a getter on the "ok" property that actually runs the assertion when you get its value.

It seems unnecessary to me (much like that whole programming style), but it does "work". Just so long as no-one goes around inspecting any of those intermediate values in a debugger.

qntm
Jun 17, 2009
Dang, I didn't know that just getting a property could have side-effects like that. Now I have to think carefully before even removing seemingly dead code like if(thing.property) { /* empty block */ }.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



qntm posted:

Dang, I didn't know that just getting a property could have side-effects like that. Now I have to think carefully before even removing seemingly dead code like if(thing.property) { /* empty block */ }.

Welcome to the wonderful world of getters and setters!

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
I really dislike when frameworks do "cute" stuff like that without immediately explaining what they're doing behind the scenes.

One example is Angular using toString() on functions and then parsing the function arguments to determine the dependencies to inject.

enthe0s
Oct 24, 2010

In another few hours, the sun will rise!
If I can have an array and want to check the previous two elements, what's the correct way to assign a value of 0 to those indexes that are potentially out of bounds?

JavaScript code:
for(var i = 0; i < homeValues.length; i++) {
	var rightNeighbor = homeValues[i];
	var leftNeighbor = (homeValues[i-2]>-1) ? homeValues[i-2] : 0;
	var currentValue = (homeValues[i-1]>-1) ? homeValues[i-1] : 0;
}

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
If you can be sure that all the valid values in your array are numbers, then you can do (homeValues[i-2] || 0);

JamesieAB
Nov 5, 2005
I'm trying to write a little chrome extension that will simply open a new tab and load a webpage into it. Can anyone show me what my manifest and js file should look like to get me started?

CuddleChunks
Sep 18, 2004

Edit: guess I didn't understand what he was trying to do.

CuddleChunks fucked around with this message at 00:05 on Nov 11, 2014

qntm
Jun 17, 2009

enthe0s posted:

If I can have an array and want to check the previous two elements, what's the correct way to assign a value of 0 to those indexes that are potentially out of bounds?

JavaScript code:
for(var i = 0; i < homeValues.length; i++) {
	var rightNeighbor = homeValues[i];
	var leftNeighbor = (homeValues[i-2]>-1) ? homeValues[i-2] : 0;
	var currentValue = (homeValues[i-1]>-1) ? homeValues[i-1] : 0;
}

I'm curious because what you asked for doesn't quite match up with your code. Suppose your array has four elements [3, 16, 28, 399], do you want to iterate like this ("previous two elements"):

code:
0, 0, 3
0, 3, 16
3, 16, 28
16, 28, 399
or like this ("left and right neighbours"):

code:
0, 3, 16
3, 16, 28
16, 28, 399
28, 399, 0
?

In the first case, following Suspicious Dish's advice, you want:

JavaScript code:
for(var i = 0; i < homeValues.length; i++) {
    var prevValue2   = (homeValues[i - 2] || 0);
    var prevValue1   = (homeValues[i - 1] || 0);
    var currentValue = homeValues[i];

    // do something
}
In the second, you want:

JavaScript code:
for(var i = 0; i < homeValues.length; i++) {
    var leftNeighbor  = (homeValues[i - 1] || 0);
    var currentValue  = homeValues[i];
    var rightNeighbor = (homeValues[i + 1] || 0);

    // do something
}
In either case, user CuddleChunks' code is wrong and should be ignored.

waffle enthusiast
Nov 16, 2007



Is there a good JavaScript library to scrape web/date data? I want to scrape this drop-in hockey calendar. Since it doesn't look like I can get it in JSON, I'm going to have to parse the HTML table manually.

My first inclination is to turn the HTML into JSON and then parse it that way, but I was curious if there's a better way or a library that will do this for me.

The plan is to write all my various web scrapers in Node (one for each hockey rink that doesn't provide JSON), then turn the data into JSON that I serve up with Angular, if that matters. This is one of my "learn JavaScript" projects.

ostills
Oct 10, 2012

Dangerllama posted:

Is there a good JavaScript library to scrape web/date data? I want to scrape this drop-in hockey calendar. Since it doesn't look like I can get it in JSON, I'm going to have to parse the HTML table manually.

My first inclination is to turn the HTML into JSON and then parse it that way, but I was curious if there's a better way or a library that will do this for me.

The plan is to write all my various web scrapers in Node (one for each hockey rink that doesn't provide JSON), then turn the data into JSON that I serve up with Angular, if that matters. This is one of my "learn JavaScript" projects.

Have you looked at http://cheeriojs.github.io/cheerio/? It's basically jQuery for the server.

waffle enthusiast
Nov 16, 2007



ostills posted:

Have you looked at http://cheeriojs.github.io/cheerio/? It's basically jQuery for the server.

This looks exactly like what I need. Thanks!

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

Wheany posted:

I really dislike when frameworks do "cute" stuff like that without immediately explaining what they're doing behind the scenes.

One example is Angular using toString() on functions and then parsing the function arguments to determine the dependencies to inject.

For me the key thing is if it's immediately obvious that they're doing something cute when reading code using it. It doesn't matter how well documented something is if the code doesn't give me any reason to think I need to look at the documentation. IMO the Chai example is pointlessly clever, but it's not something I'm going to blow four hours on trying to figure out why some perfectly ordinary operation isn't working before discovering that it's because of well-hidden magic.

loquacius
Oct 21, 2008

Another question related to my previous issue: I have scroll event listeners in place that make changes to the page depending on where the user has scrolled. If I scroll around using a laptop touchpad (or tablet touchscreen), the scroll event fires and the listeners do their job as long as my fingers are still touching the pad/screen. If I "flick" my way around the page with a quick swipe, though, neither the "scroll" event nor the "touchmove" event seems to fire. Is there another event I should be listening on to deal with swipes or am I SOL?

necrotic
Aug 2, 2005
I owe my brother big time for this!

loquacius posted:

Another question related to my previous issue: I have scroll event listeners in place that make changes to the page depending on where the user has scrolled. If I scroll around using a laptop touchpad (or tablet touchscreen), the scroll event fires and the listeners do their job as long as my fingers are still touching the pad/screen. If I "flick" my way around the page with a quick swipe, though, neither the "scroll" event nor the "touchmove" event seems to fire. Is there another event I should be listening on to deal with swipes or am I SOL?

Probably SOL? I have had an awful time trying to interact with touchpads/screens and scroll/touch events.

Xenoveritas
May 9, 2010
Dinosaur Gum
You can always do the tried-and-true method of setInterval and constantly polling the scroll position. Although I still have to ask: why does this element need to be fixed? Is the iframe really necessary? Are you sure you can't move everything to one page and use REST+CORS to get whatever data you need for the other domain? Because position:fixed is far superior to trying to duplicate it in JavaScript.

loquacius
Oct 21, 2008

Yeah, for the record I ended up just declaring defeat there and setting the size of the iframe and outer frame relative to the window size such that the user never gets too lost and it minimized the negative effects of things scrolling at the wrong times. In closing, dealing with legacy code is a huge pain in the rear end.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
I guess this isn't strictly a Javascript question, but it is related: When using Spy-JS in Idea, is there a way to find traces that have executed a particular line?

Adbot
ADBOT LOVES YOU

IT BEGINS
Jan 15, 2009

I don't know how to make analogies
This is maybe a more vague best-practices related question, but I'm having some trouble organizing my code for a particular feature. I have an input text box that a user can fill in that's also controlled by a list on checkboxes/customer names. The functionality I have is that when the user clicks on a checkbox/customer name, that value is added to the input box - multiple customers can be selected, with commas as a delimiter. I also allow the user to type in a customer name manually, and update the checkboxes if he has typed a valid name.

My issue is that right now, I'm basically making a form with a bunch of click handlers going back and forth. It's not particularly reusable, and I am going to be adding several more controls like this to the page, so I'd like this JS not to turn into like 50 "$(elt).on('click', ...)" lines. Any tips?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply