How to use JSONP (AJAX to SSL) in WordPress, an EASIER way

I’ve already written about How to use JSONP in WordPress Development. I explain how it works, and why you would use it there.

At work we work with several domains and I’ve had to use quite a bit of JSONP, I’ve rethought how to use it, and made this micro-framework to make it a LOT easier. Mostly, I wrote this to solve the problem that I’m using a lot of AJAX, and don’t want the overhead of the .ajax call each time.

There are a lot of values you need to set when making a JSONP call in general, and specifically with WordPress, this greases those wheels.

The paradigm is all you do is execute:

wp_jsonp("wp_jsonp", "getStuff", {variable: "hello world"}, getStuff);

and the rest is taken care of on the JS side. I wrote it to be agnostic of the server-side processing as well, this gives you the benefit of a pseudo factory design pattern with your switch statement.

You can download the whole repo to peruse or play with if you like, I made some gists for easy embedding.

This is the guts of the operation, I created this javascript object that handles everything, you past the ajax event, method, parameters and a callback function. The plugin takes care of the nitty gritty details that are a pain to remember for getting jsonp to work.

It’s well commented, so read through and feel free to ask questions in the comments if you have any.

Here’s the example, you might say, wait a minute, don’t you get a callback from jQuery already? Sure, good luck using it. It’s a little funny ignoring that, but hey, this works nicely.

Maybe I’m overthinking / over-complicating things, I don’t know, once it’s set up you can move really quickly, isn’t that the point of a framework?

Just one important note: make sure to validate the hell out of things because you’re giving that JS function a LOT of power.

I’d love to hear your thoughts, if you have suggestions for improving it, by all means, please comment below!


    WPNYC: Typography – What You Should Not Do

    I had the privilege of giving at talk on typography at the New York WordPress Meetup. The video has been posted to WordPress.tv, I hope you enjoy!

    Note: This talk’s focus is on choosing fonts, not typesetting. There are some mis-uses of quotes and dashes here. Mostly due to bad habits developed as a result of their incompatibility with code.


      How I Rea[r]d – Audible has changed everything

      We all make resolutions as the new year comes around. Most don’t last a month, but half way through, mine seems to have stuck (tfoo tfoo) and I’ve been reading a book a week since January.

      Over the past few years I’ve discovered that while I’m coding I am most productive when I listen to things. When I’m working on something that takes a lot of brain power that tends to be Bach or Mozart, a little less brain needed — Led Zeppelin or The Beatles. However, two thirds of the time I’m doing things I’ve done ten times before, it takes expertise, but not much brain power. That’s when I listened to podcasts.

      TWO Free Books on Audible

      About a year and a half ago I decided to try Audible instead of podcasts, I had just finished the back log of This Week in Startups and my day was feeling empty.

      I rarely listen to podcasts now, I still have my few favorites, but I’ve been eating up all the books I’ve been missing, and discovering so many more I never knew I’d been missing. During my commute, during workouts and at work. I am a fanboy and am grateful.

      Check out my reading list, I’ll keep adding to it as the year goes on.

      I’ve decided to share my list now, because I’ve been feeling more and more a need to discuss what I’ve read. So if something jumps out at you on the list, leave a comment, or email me directly. I’d love to discuss.

      Note: since I am reading with my ears (rea[r]ding) I’m also considering literary audio performances and courses as a complete book. You may disagree that listening isn’t really reading, it’s not quite as it is passive. But the outcome is the same, I’ve consumed the literary work in it’s entirety.


        Typography, how to choose fonts for your site – WPNYC

        In this talk I covered what you should consider, and avoid, when choosing fonts for your site.

        Note: There are captions below the slides when it is in slideshow mode. For expedience, I resisted the temptation to mess with the caption styling.

        Also note: This talk’s focus is on choosing fonts, not typesetting. There are some mis-uses of quotes and dashes here. Mostly due to bad habits developed as a result of their incompatibility with code.


          Web Typography – A quick and dirty guide to Enqueuing Fonts in WordPress.

          This coming Tuesday I will be speaking at WPNYC, the official New York City WordPress Meetup, on the topic of WordPress and Typography.

          Having started out as a front-end developer, I have always been inspired by beautiful typography used properly. I will post my slides once the recording of the talk goes live, but for now, in preparation, I thought it would be nice to post something about how to actually use typefaces on your site that are not available by default.

          In my talk I will cover this topic as well as a provide a few tips on what to avoid when choosing and implementing your type choices.

          What’s available?

          We are living in a wonderful age of type. There are hundreds of thousands of fonts available online. Which should you choose? I’ll cover a little of that on Tuesday, but for now, I’ll leave it up to you. Here are, IMHO, the three most accessible options where you can find some interesting choices:

          1. TypeKit – Now owned by Adobe, a truly rich and easy to use platform. www.jackreichert.com proudly uses TypeKit fonts. Free account allows two fonts, which is just fine for most any creative designer to utilize.
          2. Fonts.com – While it’s a pretty site, navigation is clearly focused on being unfriendly towards people wanting to try the service before they buy. Here is the buried link to the free fonts.
          3. Google fonts – It got a lot of negative reviews at the beginning because, honestly, they weren’t very discerning. However, since then a lot of money and effort has been put into getting some quality fonts available.

          Notable mention: Font Squirrel, they don’t host font files, but it’s a great resource for finding affordable quality fonts. Their Webfont Generator is great for helping you find the ideal “bulletproof @font-face syntax“.

          Simply add the above into your stylesheet and you’re good to go using: body { font-family: corbert-regular<span class="pl-pds">', sans-serif; </span> }

          A note on “free” fonts

          “Free” often means you’re paying in some other manner. “Free” fonts are often knockoff fonts of well crafted classics. Why should you care? Because if you’re going through the trouble of caring about details to the level of which typeface you want to show your content through, you should care about the quality of that typeface.

          Alternatively, a free font may be designed by an amateur designer, who then releases it because it’s not quite professional yet.

          What’s missing? A lot goes into the crafting of a quality font.

          • Italics, aren’t simply a font tilted, and bold isn’t simply a stroke added to the font. If you’re okay with doing that, JUST STOP READING NOW. LEAVE. SERIOUSLY.
          • Kerning, each letter fits differently with each letter pair, a quality font will have the pairings programming in. Interestingly, pairings are effected by font-size as well.
          • Overall quality, cheap knockoffs and novices won’t take scaling, or details properly into consideration.

          Is “free” EVER OK? Yes. Over the past few years Google and Adobe have been commissioning fonts for open source projects. While Google Fonts once was a bastion of amateurism, it now has some high-quality complete font families. As with software, the open-source community has come to the rescue.

          How do I do it?

          Each of the above tools have their own way to create a collection of fonts, and all have great walk-throughs. Once you generate one replace the above code / paths with your custom generated one. Don’t forget to comment out, or remove what you’re not using.

          Now you just use the fonts as you would any other in your stylesheet.

          body { font-family: 'Josefin Sans', sans-serif; }

          Note: enqueue_script() by default will add the script to the head of your site. If the font provider states that you need to enqueue your script in the footer of your site WordPress has you covered:

          wp_enqueue_script( 'add_my_font', '//www.example.com/myfont.js', array(), 20150613, true ); 

          That “true” at the end will place the script into your site’s footer.

           


            How to recursively make a directory (folder) with PHP

            When I need to generate or save files in a web application it’s important that I keep all the files in an orderly fashion.

            Sometimes I think that there’s a fine line between impressionistic and messy.
            Lady Gaga

            Here’s the go-to code I use to generate the directory structure.

            You can find more solution on this StackOverflow thread.

            How it works

            is_dir() is a native PHP function that will say if a relative path is given is a directory or not. If the path doesn’t exist, it will return false.

            || – is the OR operator in PHP. If the path is a directory exists the function will return without moving over to the second part, because we’re saying do this OR that.

            mkdir() is a native PHP function that will create a directory at the path location that is given.

            The parameter $path is the path where the directory should be created.

            The parameter $permissions is the chmod() settings of directory being created.

            The ‘true’ creates the directory recursively. This means that you only need to create the path, and you don’t need to make sure the whole path exists. It will fill in the gaps.

            Why not just use mkdir() by itself?

            You can, but if you do, and the directory already exists, it will send out an error to the log. Nothing terrible with that, I just like keeping things clean.


              Don’t be TOO clever with your UX designs – Why I cancelled my Coin

              Edit: After reviewing Plastic, I decided to go with them. First and foremost, their security isn’t over-thinking things. Second, their card actually recharges, so you won’t have to buy a new one after a year+.

              * * *

              I was excited when Coin announced their campaign. I love technology, and this is a great example of innovation being used to make life easier. I have several credit cards, it’s good for your credit score, and keeping track of them is a pain and risky. I’d rather keep them safely at home and use secure device out in the wild.

              When I first received the notification to download the app I set it up. I had a little trouble setting up the Tap Code. I had a little musical training growing up, but that was a long time ago, and I never got around to learning Morse Code. I finally entered a code that was acceptable, but how do you write that down?

              Months later I saw that Coin was starting to ship so I tried to sign into my app to see when mine would come. I’d been waiting for it for a while and was excited.

              Tap Code: Damn. What was it again?

              IMG_0097

              I went to reset it, had trouble getting something complicated enough that was acceptable. Again. This time I tried noting it down in 1Password with dashes and dots.

              Later that day I decided to try signing in again. Even with the dashes and dots I couldn’t sign into the app.

              I applaud them for trying something new, but at that point I was starting to get concerned about ever being able to use my Coin. So I looked through the app, no there is no alternative to using the Tap Code.

              At that point I wrote to them asking them if there are plans for an alternative for people like me who can’t seem to get their innovative password alternative working. The email I received in response, I felt, was patronizing. It explained how to set up the Tap Code, and made me feel like an idiot. I’ll give them the benefit of the doubt, maybe they’ve had a bunch of people who couldn’t set it up, maybe due to my frustration I was reading into the tone of the email. The person clearly didn’t read my complaint and sent me an answer explaining what they thought I was asking about.

              Maybe I should learn Morse Code, but that wasn’t even the issue, I couldn’t get it working even after I had written down my code. I responded asking if they have plans integrating an alternative for people like me, and no they didn’t . So I requested a refund.

              With innovations, it’s important to make sure they work well, if you want people to use them. If your innovation is truly unique and different, It’s also important to make sure there are alternatives, if you want your users to be comfortable enough to try your innovation out.

              Even Apple had a password fallback when they first implemented the fingerprint reader. Now the password fallback is gone, but that was there for the first year+, until they ironed out all the details.

              In addition to being concerned about being able to use my coin at all, I was just as concerned about their approach to UX. I’m not an average user, and I couldn’t use their technology effectively. If they’re not responsive nor thoughtful about THIS innovation, what other aspects of their system and security are they NOT thinking through?

              At least I got my money back, but I’m disappointed. I wanted to use their tech.

              I don’t know how many people they testing this concept with. I couldn’t find many articles about the security benefits of tap codes over pins. Historically Tap Codes are interesting, but they’re for communicating, not for identity. I think it’s a real shame that their approach is bullheaded and unthoughtful.


                If you feel that this site is running snappier, you’re probably right.

                I went to 3 meetups this week: Codepen.io, WPNYC, and Web Performance NY.

                At two of them people mentioned Percona. So I thought I’d check it out. Digital Ocean has a great tutorial if you’d like to check it out: How To Install a Fresh Percona Server or Replace MySQL. I got stuck for a bit, but found a solution deep in the comments of a StackOverflow answer. It turns out that when I removed MySQL to install Percona it removed the php5-mysql module.

                Before installing it commando on my personal site, I tried it first in my dev box at work and got a 5x improvement in speed.

                This is not a scientific experiment, I implemented two other improvements as well:

                • Switched from W3 Total Cache to WP Super Cache.
                • Expanded my Digital Ocean instance as Percona recommends 1GB RAM.

                Hope this helps you’re reading experience at my digital home.

                Cheers!


                  “The Crystal Goblet or Printing Should be Invisible”

                  This metaphor is truly stunning and puts into words the careful balance between that must be maintained between content and container. This is as true for a site’s design and the content it contains as it is for typography and the text it contains.

                  “Imagine that you have before you a flagon of wine. You may choose your own favorite vintage for this imaginary demonstration, so that it be a deep shimmering crimson in colour. You have two goblets before you. One is of solid gold, wrought in the most exquisite patterns. The other is of crystal-clear glass, thin as a bubble, and as transparent. Pour and drink; and according to your choice of goblet, I shall know whether or not you are a connoisseur of wine. For if you have no feelings about wine one way or the other, you will want the sensation of drinking the stuff out of a vessel that may have cost thousands of pounds; but if you are a member of that vanishing tribe, the amateurs of fine vintages, you will choose the crystal, because everything about it is calculated to reveal rather than to hide the beautiful thing which it was meant to contain.

                  “Bear with me in this long-winded and fragrant metaphor; for you will find that almost all the virtues of the perfect wine-glass have a parallel in typography. There is the long, thin stem that obviates fingerprints on the bowl. Why? Because no cloud must come between your eyes and the fiery heart of the liquid. Are not the margins on book pages similarly meant to obviate the necessity of fingering the type-page? Again: the glass is colourless or at the most only faintly tinged in the bowl, because the connoisseur judges wine partly by its colour and is impatient of anything that alters it. There are a thousand mannerisms in typography that are as impudent and arbitrary as putting port in tumblers of red or green glass! When a goblet has a base that looks too small for security, it does not matter how cleverly it is weighted; you feel nervous lest it should tip over. There are ways of setting lines of type which may work well enough, and yet keep the reader subconsciously worried by the fear of ‘doubling’ lines, reading three words as one, and so forth.”

                  “The Crystal Goblet or Printing Should be Invisible”
                  from Beatrice Warde, The Crystal Goblet, Sixteen Essays on Typography, Cleveland, 1956


                    Learning to Walk in Space

                    When a child learns to walk, they take leaps beyond what their skill and strength should allow. They look out at all the people walking around them, and see what is possible. Their muscles may not be strong enough to fully support them, to balance and stand, but they see what is possible. They pull themselves up by a table leg and stand. They may bounce on their feet a few times in anticipation of walking, and then they leap over, stumble a few steps, and fall onto a couch, or into a parent’s arms.

                    These are a child’s first steps.

                    When we, humanity, started our space journey our technological muscles were only beginning to be formed. Germanium was still being used in transistors, and Apollo’s computers had approximately 64Kbyte of memory and operated at 0.043MHz.

                    Landing on the moon was that stumbling first step that a baby takes from the table, lunging towards a couch.

                    Since then we’ve been strengthening our muscles. We now have cars that can drive themselves and more computing power than we know what to do with in our own pockets.

                    We have more than reached the time when we need to let go from holding on to the safety of the coffee table. We need to let go, and take steps out into the universe.

                    We dreamt of hotels on the moon and we think that we failed because they don’t exist yet.

                    But those dreams were the dreams of a baby believing they’re walking because a parent is holding their hands up. Our technological muscles weren’t strong enough to support hotels on the moon.

                    Our technology has matured and now is the time to build those hotels. Solving the problems that we will need to solve, to have a manned base on the moon, will reverberate through our economy. Such a project will reap dividends beyond our imagination.

                    There are a lot of technological problems that will need to be solved for man to safely set up camp off our planet. How will we cheaply and efficiently get past lower orbit? What sort of life sustaining systems will we need to build to survive there? Are there building materials there? How much water can be found there?

                    Cellphone cameras, solar cells, and artificial limbs each were developed by NASA to solve a problem, and each became an industry in itself, generating jobs, creating wealth, and improving our overall quality of life. The solutions we create to set up camp on the moon will do the same.

                    We should do this in parallel to the missions planned to Mars. The moon is close and shouldn’t wait. What we learn there will apply further out and it should pay for itself in dividends.

                    We should send man back to the moon. We should build science stations on the moon.

                    We should build hotels on the moon.