[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 181
  • Last Modified:

api connect

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
Seven price
Asked:
Seven price
4 Solutions
 
Ray PaseurCommented:
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
 
leakim971PluritechnicianCommented:
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
 
GaryCommented:
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
 
Ray PaseurCommented:
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
 
Seven priceFull StackAuthor Commented:
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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now