Solved

api connect

Posted on 2014-12-26
5
159 Views
Last Modified: 2014-12-28
Yes I am trying to learn to connect to a api, every way I try does not seem to connect using jquery. Np with angular but I need to connect with jquery to retrieve the value.

http://jsfiddle.net/sevensnake/ck5Lvbdj/1/
0
Comment
Question by:sevensnake77
5 Comments
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 40519734
There might be a couple of issues here.  You can use Chrome Developer Tools to find out about the issues.
https://developer.chrome.com/devtools
https://www.codeschool.com/courses/discover-devtools

Here is one problem that I encountered:
XMLHttpRequest cannot load http://api.upcdatabase.org/json/4eb8f4e4a25fb798c3c5f13fe96261e6/077633047375. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://iconoun.com' is therefore not allowed access.
To get around that, I copied the API response to my server at this URL:
http://iconoun.com/demo/temp_sevensnake77.php

Next I used JavaScript alert() to visualize the data.  I could see that I was getting the JSON string this time.  So I added the jQuery.parseJSON() method to the script and was able to get it to work.
http://iconoun.com/demo/temp_sevensnake77.html

Going forward, you might find that you need JSONP to handle the cross-origin request.

<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>E-E Q_28587196</title>

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
    $.get("http://iconoun.com/demo/temp_sevensnake77.php", function(data) {
	    var jobj = $.parseJSON(data);
	    $(".my-id").append(jobj.number);
	    $(".my-content").append(jobj.itemname);
    });
});
</script>

</head>
<body>

<div>
<p class="my-id">The ID is </p>
<p class="my-content">The content is </p>
</div>

</body>
</html>

Open in new window

HTH, ~Ray
0
 
LVL 82

Assisted Solution

by:leakim971
leakim971 earned 125 total points
ID: 40519741
Test page : http://jsfiddle.net/tx7d4fqj/

More info :
https://developer.yahoo.com/javascript/howto-proxy.html
https://jsonp.nodejitsu.com/

$(document).ready(function() {
    var api_endpoint = "http://api.upcdatabase.org/json/4eb8f4e4a25fb798c3c5f13fe96261e6/077633047375";
    window.mycallback = function(data) {
        alert("test");
       $('.my-id').append(data.number);
       $('.my-content').append(data.itemname);
    };
    $.ajax({
        url: "https://jsonp.nodejitsu.com/?callback=mycallback&url=" + encodeURIComponent(api_endpoint)
    });
});

Open in new window

0
 
LVL 58

Assisted Solution

by:Gary
Gary earned 125 total points
ID: 40520087
Forget the first junk comment here - not living in the real world or answering the real question of a cross domain request - hey I totally ignored this is for a different domain so just copied the reponse to my server so it worked - jaysus!

Here's leakim's fiddle working (who actually made a real world working sample)
http://jsfiddle.net/895k30sc/

But that relies on a third party to deliver you the results which is not an ideal situation

Because you are hitting the cross domain policy and upcdatabase.org fails with json requests to the URL your best best is to use a proxy

That means you make a request to your server with the UPC number and your server makes the request to upcdatabase.org and returns the data to the browser.

This has the benefit of not exposing your API key which is a bad thing to make public since anyone can use it.

So your ajax, instead of making a direct request to upcdatabase.org, makes a request to your server passing the UPC number - lets say the page is called process_upc.php
Then in process_upc.php use the sample code here to make the real request to upcdatabase.org and then just echo out the results

Your code as it is in the fiddle will remain the same, the only difference will be the url
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 40520415
Gary, as I wrote right at the top, "There might be a couple of issues here."  One of the issues was a cross-domain request.  That was solved by this script (which also enabled us to hide the API key).
<?php // temp_sevensnake.php
error_reporting(E_ALL);

/**
 * EXPECTED RESPONSE:
 * JSON: {"valid":"true"
 *       ,"number":"077633047375"
 *       ,"itemname":"SUNBEAM TEXAS GAINT"
 *       ,"alias":""
 *       ,"description":"SUNBEAM TEXAS GAINT"
 *       ,"avg_price":""
 *       ,"rate_up":0
 *       ,"rate_down":0
 *       }
 */

// THE API
$url = 'http://api.upcdatabase.org/json/4eb8f4e4a25fb798c3c5f13fe96261e6/';

// PROVIDE THE ABILITY TO GET OTHER KEYS BY CHANGING THE URL
$get = !empty($_GET['q']) ? $_GET['q'] : '077633047375';
echo file_get_contents($url . $get);

Open in new window


The other issue was that the jQuery script did not parse the JSON, so it did not have access to the JSON object properties.  I think it's OK for us to overcome the issues one step at a time, and it's also OK to show the author of the question the logic and steps we take as we try to help debug something.

Anyway, I'll sign off on this question now, since I think it's adequately answered and explained.
0
 
LVL 9

Author Closing Comment

by:sevensnake77
ID: 40521295
Thanks, I gave ray the best solution because I seen he done it in php and that gave me and idea, so I done it in C# But thanks again.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

by Julian Matz As of jQuery (http://jquery.com/) 1.4 the .live() method (http://api.jquery.com/live/) supports custom events as well as some standard JavaScript events that it previously didn't support. Among these is the submit event. Unlike …
Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now