Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

PhP From + Ajax + Json: Looking for help on understand process.

Hello Treehouse,

I am hoping someone can hep me out. I am looking to create a web app that does the following: Takes an input from a HTML Form (URL) and then via AJAX load new content based on information retrieved from an API (http://api.bering.dyndns.com/dnslookup/domain/youdomain.com). I may just be overthinking but I would love to talk this through or get an suggestions.

Thanks so much

Are you trying to use that API or just as an example?

6 Answers

No problem Ryley.

One way to take the input from a user and pass it to the API url is by creating a URL Generator function in your javascript file. The HTML doc is going to be more or less identical with the exception of an <input> like this:

<!-- ADD THIS TO THE BODY OF THE HTML OUTSIDE OF THE jsonDATA div -->
<form action="">
    <div id="buttons">
    <input id="apiKey" class="apiKey" type="text" placeholder="Please enter your API key" value="" />
        <input onclick="getAPIData()" value="Click here to get the API response text"/>
    </div>
</form>

<script type="text/javascript" src="js/urlgenerator.js"></script> <!-- INCLUDE THE URLGENERATOR.JS FILE -->

Now you can add a new file to your project called urlgenerator.js and fill it with something like this:

//create a url using the apikey which is inserted in to the input
function urlGenerator() {
    "use strict";
    var url = "http://api.bering.dyndns.com/dnslookup/domain/",
        apiToken = document.getElementById("apiKey").value, //this line takes the value that the user inserts for their apikey
        fullURL = url + apiToken;

    return fullURL;
}

Finally, you will need to update your GET request so that it uses the url which has been generated by the above function like this:

var xhr = new XMLHttpRequest();

// THIS GETS THE DATA FROM THE API URL
function getAPIData (){
    xhr.open('GET', urlGenerator() ,true);
    xhr.onload = function(e){
         if (xhr.readyState === 4 && xhr.status === 200) {
            outputAPIDATA(); //call the Print function here
            } else {
        window.alert(xhr.statusText);
            }
        };

    xhr.send(null);
}

As long as you have installed the CORS plugin for google chrome, this will all work perfectly and it is transferrable to a mobile application. If you're using PhoneGap for example, and you are live testing on your phone, you won't need a CORS plugin for it to work, it just will.

Yes that is the API I plan on using.

Do you have access to it because CORS is active and you won't be able to call from that API unless they have you listed.

I do have access to it.

I'm doing something very similar at the moment. It's a straight foward enough process. Here is a basic example of what you will need to do. (also the comment above about CORS is true so you will need to install the CORS extension for Google Chrome to show it working during testing: (https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US)

I'm not too familiar with PHP so I have done this with HTML and JS but from what I have seen HTML and PHP are pretty similar and really it is the JS that is the important part here:

The HTML Code

<!DOCTYPE html>

<html>

<head>
    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
    <!-- This is a wide open CSP declaration. To lock this down for production, see below. -->
    <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" />


    <link rel="stylesheet" type="text/css" href="css/index.css" />
    <title>Hello World</title>
</head>

<body>
    <div class="app">
        <h1>API Response</h1>
        <div id="jsonData">
            <button onclick="getAPIData()">Click here to get the API response text</button>
            <!-- THIS IS WHERE THE API WILL DISPLAY ON THE PAGE -->

        </div>
    </div>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript" src="js/app.js"></script>
    <script type="text/javascript">
        app.initialize();
    </script>
</body>

</html>

Here is the all important JS:

var xhr = new XMLHttpRequest();

// THIS GETS THE DATA FROM THE API URL
function getAPIData (){
    xhr.open('GET', 'http://api.bering.dyndns.com/dnslookup/domain/youdomain.com', true);
    xhr.onload = function(e){
         if (xhr.readyState === 4 && xhr.status === 200) {
            outputAPIDATA(); //call the Print function here
            } else {
        window.alert(xhr.statusText);
            }
        };

    xhr.send(null);
}



// THIS PRINTS THE RESPONSE TO THE PAGE
function outputAPIDATA(node_id, domain, results, nameserver, nameserver_ip, query_time, nameserver_used, nameserver_used_ip, test_time)/*pass the relevant aguments to the function*/{
    var response = xhr.responseText,
        jsonResponse = JSON.parse(response);

    // NOW YOU NEED TO LOOP OVER THE JSON REPONSE TO GET THE INFO YOU ARE AFTER
    for(var key in jsonResponse){
    document.getElementById("jsonData").innerHTML += "<h2>TEST: " + jsonResponse[key].node_id + "</h2>"
                                + "DOMAIN: " + jsonResponse[key].domain + "</br>"
                                + "QUERY TIME: " + jsonResponse[key].query_time + "</br>"
                                + "NAMESERVER USED: " + jsonResponse[key].nameserver_used + "</br>"
                                + "NAMESERVER USED IP: " + jsonResponse[key].nameserver_used_ip + "</br>"

        }
    }

When I first started doing this it took me ages to work it out so I hope this helps you get what you are after.

I forgot add how to get the data that is passed to the url from the form. If you need any help to get the data (i'm guessing maybe an API key?) from an input and passing it to a url, just shout and I'll let you know one way to do it.

Andrew that is awesome. I will sift through this when I get back in front a computer. I really appreciate the help. As for passing the URL as far as I know you basically just toss it on the end of http://api.bering.dyndns.com/dnslookup/domain/youdomain.com (replacing yourdomain.com) and get JSON back.

Andrew that worked perfectly. Thank you so very much!

No problem Ryley. I'm glad it worked for you.