WyoBuckeye
WyoBuckeye

Reputation: 305

jQuery JSON beginner trying to create simple server request

I'm somewhat experienced in using JavaScript but not in dealing with jQuery and JSON.

I'm trying to create a tool that will get data from our database so that I can create new way of display our data.

If I enter the following URL into a browser, I get a response that I have identified as JSON that displays on the page:

**URL:** http://osuc.biosci.ohio-state.edu/hymDB/OJ_Break.getSpmInfo?cuid=OSUM%20110110&callback=test

**Response:** test({"spmInfo":{"cuid":"OSUM 110110","alt_ids":[],"loc_name":"Mad River near State Route.....

I've been playing around trying to build something simple that will show information from the database, but I have thus far been unsuccessful in even getting my page to display anything relevant. Any help and advise would be greatly appreciated.

Here's my code:

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="json.js"></script>
<script type="text/javascript" src="getdb.js"></script>
</head>
<body>
<button type="button" onclick="getinfo()">click</button>
<h6 id="objinfo"></h6>
</body>
</html>

JavaScript:

function getinfo(){
    $.getJSON('http://osuc.biosci.ohio-state.edu/hymDB/OJ_Break.getSpmInfo?cuid=OSUM%20110110&callback=test', function(data) {
  $('#objinfo').html(JSON.stringify(data));
});}

Here is a link to JSFiddle Link

Thanks in advance.

Upvotes: 0

Views: 1054

Answers (2)

WyoBuckeye
WyoBuckeye

Reputation: 305

I found an explanation of making 3rd party JSON requests that has helped me immensely. Scroll down to the section "Retreiving JSON From Third Party Servers", which is about 2/3 down the page. Thanks to MetalFrog for his help.

http://www.hunlock.com/blogs/Mastering_JSON_%28_JavaScript_Object_Notation_%29#quickIDX9

Upvotes: 1

MetalFrog
MetalFrog

Reputation: 10523

It's important to note that until your JSON is valid, setting the correct header will not matter. I grabbed your response from the url in your example and ran it through JSONLint to validate it.

http://jsonlint.com/


Here's a simple function I use to dump an array of data as a JSON response:

/**
 * @param $content Array of data to json_encode
 * @param bool $nocache If true, sets a no-cache header
 */
public function jsonOutput($content,$nocache = false)
{
    if( $nocache === true )
        header('Cache-Control: no-cache, must-revalidate');

    header('Content-type: application/json');
    print json_encode($content);
    exit();
}

Upvotes: 1

Related Questions