I am trying to pull in book data upon a user form submission from the ISBNdb API. I am using JSON in the url as required. As of now I am using the form to search by books category (see about halfway down page). When I enter a search term, I get 2 errors in the console:
Resource interpreted as Script but transferred with MIME type
text/plain:
"http://isbndb.com/api/v2/json/J6FR9HT6/books?jsoncallback=jQuery1111037271023145876825_1404698815454&q=science&_=1404698815455".
jquery.min.js:4 Uncaught SyntaxError: Unexpected token :
I see the q=science that I am expecting, but what is all the other stuff jQuery seems to be adding? Any help MUCH appreciated!
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('form').submit(function (event) {
event.preventDefault();
var searchTerm = $('#search').val();
// the AJAX part
var isbndbAPI = 'http://isbndb.com/api/v2/json/J6FR9HT6/books?jsoncallback=?';
var bookOptions = {
q: searchTerm
};
function displayBookData(data) {
var bookHTML = '<ul>';
$.each(data.data,function(i,book) {
bookHTML += '<li>';
bookHTML += book.title;
bookHTML += '</li>';
}); // end each
bookHTML += '</ul>';
$('#book-results').html(bookHTML);
}
$.getJSON(isbndbAPI, bookOptions, displayBookData);
}); // end submit
}); // end ready
</script>
</head>
<body>
<form>
<label for="search">Type a search term</label>
<input type="search" name="search" id="search">
<input type="submit" value="Search" id="submit">
</form>
<div id="book-results"></div>
</body>
</html>
UPDATE
It seems to receive the JSON back okay, and I can see the results in the console. Still confused as this is all new to me. Also, I may not be displaying it as HTML correctly either.
The url at original post did not include a parameter required by the api :
error: "'query' or 'q' is a required parameter"
See ISBNdb API -- Version 2
Request URL: http://isbndb.com/api/v2/xml/mykey/books?q=science
Try
$.getJSON("https://query.yahooapis.com/v1/public/yql?q=select"
+"* from json where url='http://isbndb.com/api/v2/json/J6FR9HT6/books?q=science'"
+"&format=json&diagnostics=true&callback=?"
, function(data, textStatus, jqxhr) {
console.log(data.query.results.json.data);
$.each(data.query.results.json.data, function(index, value) {
$("<li>", {"text" : value.title +", "
+ (value.author_data
? (value.author_data.name
? value.author_data.name
: value.author_data.id)
: void(0)) }).appendTo("ul");
});
})
.fail(function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
});
jsfiddle http://jsfiddle.net/guest271314/bZBLf/
The API you mentioned does not support JSONP. As its documentation states, it only supports JSON, YAML, and XML.
Response Formats
The API will serialize it's return data in one of 3 different formats:
Json - /api/v2/json/my-api-key
Yaml - /api/v2/yaml/my-api-key
XML - /api/v2/xml/my-api-key
jQuery tries to treat the returned JSON file as a JS file, but it isn't thus causing the error.
Your server-side either needs to change its content-type to give you JSON, or you need to get the data back and treat it as text, then convert to JSON.
It looks like you are trying to request JSONP though ... not sure if you can/how easy it will be to pull it down as text and then convert it and still get the callback to run.
Related
If this is a re-post of an already existing. I looked a bunch of different issue already posted about this but didn't feel any matched my issue. If there is one please link it.
I'm trying to learn AJAX and have a form that takes two inputs a serverName, and a isLive. As well as a button to add a server to the list. I already made a json file that has two servers in it and when I GET info from it to update the list it lists the server's serverName and isLive fine. When I go to POST information all I get back when the list is updated is undefined.
Using console logs I know that the information is being passed from the form to Object to be sent by AJAX and that it seems to trigger the success function, but when I look there is nothing added to the Json and it says the fields are undefined.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Ajax</title>
</head>
<body>
<h1>Server List</h1>
<ul id="servers">
</ul>
<h4>Add a Server</h4>
<p>Server Name: <input type="text" id="serverName"></p>
<p>Offline or Online: <input type="text" id="isLive"></p>
<button id="add-server">Add!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="main.js"></script>
</body>
</html>
main.js
$(function() {
var $servers = $('#servers');
var $serverName = $('#serverName');
var $isLive = $('#isLive');
$.ajax({
type : 'GET',
url: 'servers.json',
success: function(servers) {
$.each(servers, function(i, server) {
$servers.append('<li>Server: '+ server.serverName +', Status: '+server.isLive+'<li>');
});
},
error: function() {
alert('Error loading server status!');
}
});
$('#add-server').on('click', function() {
var server = {
serverName: $serverName.val(),
isLive: $isLive.val(),
};
console.log(server);
$.ajax({
type: 'POST',
url: 'servers.json',
data: server,
success: function(newServer) {
$servers.append('<li>Server: '+ newServer.serverName +', Status: '+newServer.isLive+'<li>');
},
error: function(){
alert('error saving server');
}
});
});
});
servers.json
[{"serverName":"vanilla","isLive":"offline"}, {"serverName":"SkyFactory","isLive":"Online"}]
You can't modify a file in the server with JavaScript. Check this may help:
Use JQuery to Modify external JS File
I am trying to make a REST call with AJAX in this html page. First, the user enters a term in a search bar on the / page, and is redirected to /test, but the ajax call gets cut short. The API works fine when run on the console. I am just struggling to get the data over to the /test page so I can style it and display it for the user. I am using node.js btw.
The full error I am getting is:
Uncaught SyntaxError: Unexpected token < hello.js:1
It is referring to the doctype declaration.
I noticed something when I inspected the web page.
<p> ID Passed: hello.js </p>
this is in the hello.js file...for some reason. The search term still gets rendered fine. It will say ID Passed: election
test.hbs
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="hello.js"></script>
<h2>This is the test!!!</h2>
<p>ID Passed: {{ output }} </p>
<p2 id = "tweets">
</p2>
hello.js
$(document).ready(function() {
$.ajax({
type: "GET", //I have tried deleting both type and dataType and still fails
dataType: "json", //I have also tried changing this to jsonp. No dice.
url: './srch.js'
}) //Push the data from calling srch.js into the "tweets" id on test.hbs
.done(function(data) {
document.getElementById("tweets").innerHTML=data;
})
.fail(function() {
alert("Ajax failed to fetch data")
})
});
srch.js -> where the API is stored.
var Twit = require('twit');
var config = require('./views/config');
var sentiment = require('sentiment');
var T = new Twit(config);
var params = {
q: "election", //I know that the search term from the user isnt put in, I just want to see it print something on the page at all.
count: 1,
type: 'recent'
};
T.get('search/tweets', params, gotData);
function gotData(err, data, response) {
console.log(err);
//Output only the text of the json data returned by the search, and perform sentiment analysis with the sentiment module.
for(var i = 0; i<data.statuses.length; i++) {
document.write("Tweet " + (i + 1) + ":")
document.write("***********************")
document.write(data.statuses[i].text)
document.write(sentiment(data.statuses[i].text).score)
document.write("***********************")
}
}
I think you are getting back html instead of json. I see that sometimes when url is invalid or when you are not authenticated so you get back html markup.
I would double check the return of the ajax call and display it in the console.
I am new to html and javascript.As far as i know the following code should give an alert when i press "Get JSON Data" button.But the page is not giving me any response.Any help is greatly appreciated.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://127.0.0.1:5000/2", function(result){
if (result.length == 0){
alert("nothing") ;
}
if (result.length){
alert("success") ;
}
// $("div").append(myObject);
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
I suspected that should be the Cross-domain issue. That is why I asked for the console log. you have couple of choices:
config the cross-domain headers from your servlet/backend response.
(ex: if you're using a Servlet:)
response.setHeader('Access-Control-Allow-Origin','*');
use jsonp call back
$.getJSON("http://example.com/something.json?callback=?", function(result){
//response data are now in the result variable
alert(result);
});
The "?" on the end of the URL tells jQuery that it is a JSONP
request instead of JSON. jQuery registers and calls the callback
function automatically.
use $.ajax with CORS enabled or with jsonp
ex:
$.ajax({
url: surl,
data: {
id: id // data to be sent to server
},
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback"
});
// Named callback function from the ajax call when event fired.
function jsonpcallback(rtndata) {
// Get the id from the returned JSON string and use it to reference the target jQuery object.
var myid = "#" + rtndata.id;
$(myid).feedback(rtndata.message, {
duration: 4000,
above: true
});
}
or else, download and configure "CORS.jar" in your server side which will allow the cross-domain requests.
HOW ?
Hope you can get some idea. follow which suits for you ..
Replace the JSON call with
$.getJSON("http://127.0.0.1:5000/2", function(result){
if (result.length == 0){
alert("nothing") ;
}
if (result.length){
alert("success") ;
}
// $("div").append(myObject);
}).fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err )
});
That way you can see what goes wrong. The javascript looks OK, I suspect it's a server issue.
You could also try getting back JSON from some random source, like http://1882.no/API/business/get/results.php?q=skole&page=0
Can't get the json value by getjson from google map api
HTML
<html>
<head>
</head>
<body>
<input data-mini="true" data-theme="a" id="search" name="search" placeholder="Search for Restaurants" type="search">
<input data-inline="true" id="submit" onclick="getRestaurants()" type="submit" value="Go">
</body>
</html>
JS
function getRestaurants()
{
var search=$("#search").val();
var prestring="restaurant+in+";
var jsonRList="https://maps.googleapis.com/maps/api/place/textsearch/json?query="+prestring+search+"&key=API_KEY";
var xmlRList="https://maps.googleapis.com/maps/api/place/textsearch/xml?query="+prestring+search+"&key=API_KEY";
alert(jsonRList);//working
//NOT working
$.getJSON(jsonRList, function (data) {
alert(data.results[0].name);//returns nothing
alert("hello2");//returns nothing
});
//working
var data = '{"name": "abc","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';
var json = JSON.parse(data);
alert(json.phoneNumber[0].number);
alert("hello3");//working
//NOT working
$.ajax({
url: 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=kolkata&key=API_KEY',
dataType: 'jsonp',
success: function(data){
alert(data);//returns nothing
alert("ajax");//returns nothing
}
});
alert("hello4");//working
//Not working
$(document).ready(function(){
$("submit").click(function(){
$.getJSON( jsonRList, function( data ) {
alert(data);//returns nothing
alert("hello5");//returns nothing
});
});
});
}
Inside $.getjson or $.ajax not executing anything.
Another approach that is not working
$("button").click(function() {
....
https://jsfiddle.net/sphakrrokr/r9xbctnr/
Two reasons I could identify for you not getting a response from Places API -
1) You are using data type JSONP instead of JSON while the API will return results in JSON format.
2) Even though you wish to use JSONP and not JSON, you did not implement a callback in order to parse results into JSONP.
For normal use case, I would recommend to use JSON over JSONP.
Check these resources for difference between the two:
Relevant question 1
Relevant question 2
Official docs
I have 41 JSON objects, each with the same scheme.
These objects are fairly large, and so I would like to load the object conditionally into a JavaScript script, when selecting an <option> from a <select> menu with an id of myPicker.
So far, I have set up jQuery to handle changes on the <select>:
$('#myPicker').change(function() {
alert('Value change to ' + $(this).attr('value'));
$('#container').empty();
init();
});
The function init() draws stuff in div called container.
When I change myPicker, I want init() to behave like init(value), which in turn tells init to load one of 41 JSON objects from a file (based on value).
Is loading a chunk of JSON from a file (located on the server-side) doable in this case, or do I need to use a server-side script handling Ajax form submissions and responses, etc.?
EDIT
I wrote the following code:
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$('#cellTypePicker').change(function() {
alert('Value change to ' + $(this).attr('value'));
$('#container').empty();
initFromPicker($(this).attr('value'));
});
});
function initFromPicker(name) {
// pick default cell type from picker, if name is undefined
if (typeof name === "undefined")
name = 'AG10803-DS12374';
var jsonUrl = "file://foo/bar/results/json/" + name + ".json";
alert(jsonUrl);
$.ajax({
url: jsonUrl,
dataType: 'json',
success: function(response){
alert("Success!");
},
error: function(xhr, textStatus, errorThrown){
alert("Error: " + textStatus + " | " + errorThrown + " | " + xhr);
}
});
init(); // refills container...
}
</script>
<body onload="initFromPicker();">
...
The line alert("Success!"); never gets called.
Instead, I get the following error:
Error: error | Error: NETWORK_ERR: XMLHttpRequest Exception 101 | [object Object]
I am checking the value jsonUrl and it appears to be a proper URL. The file that it points to is present and I have permissions to access it (it is sitting in my home folder). Is there something I am still missing?
Let me make sure I understand your question. I think you want to:
have a handful of files out there that contain JSON objects
depending on which option is selected a particular file is loaded
the contents of the file is JSON and
you want to be able to use the JSON object later on in other javascript
If this is the case then you would just need to do something like:
$('#myPicker').change(function() {
$('#container').empty();
init($(this).val());
});
function init(jsonUrl){
$.ajax({
url: jsonUrl
dataType: 'json'
success: function(response){
// response should be automagically parsed into a JSON object
// now you can just access the properties using dot notation:
$('#container').html('<h1>' + response.property + '</h1>');
}
});
}
EDIT: Exception 101 means the requester has asked the server to switch protocols and the server is acknowledging that it will do so[1]. I think since you're using file://foo/bar/... you might need to toggle the isLocal flag for the $.ajax function [2], but honestly, I'm not sure.
[1] http://en.wikipedia.org/wiki/Http_status_codes#1xx_Informational
[2] http://api.jquery.com/jQuery.ajax/
Below is a complete working example that pulls a JSON object from Twitter, so you should be able to copy/paste the entire thing into a file and run it in a browser and have it work. If your server is configured correctly and your .json files are in the document_root and have the appropriate permissions, you should be able to swap them out for the Twitter URL and have it work the same way...
<!doctype html>
<html>
<head>
<title>My Super Rad Answer</title>
</head>
<body>
<form id="my-form">
<select id="cellTypePicker">
<option value=''>No Value</option>
<option value="AG10803-DS12374">AG10803-DS12374</option>
</select>
</form>
</body>
<!-- Grab the latest verson of jQuery -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
// Wait until the page is fully loaded
$(document).ready(function(){
$('#cellTypePicker').change(function() {
// Grab the value of the select field
var name = $(this).val();
if (!name) {
// Make sure it's not null...
// This is preferred over using === because if name is
// anything but null, it will return fale
name = 'AG10803-DS12374';
}
// Right now I'm overwriting this to a resource that I KNOW
// will always work, unless Twitter is down.
//
// Make sure your files are in the right places with the
// right permissions...
var jsonUrl = "http://api.twitter.com/help/test";
$.ajax({
url: jsonUrl,
dataType: 'json',
success: function(response){
// JSON.stringify takes a JSON object and
// turns it into a string
//
// This is super helpful for debugging
alert(JSON.stringify( response ));
},
error: function(xhr, textStatus, errorThrown){
alert("Error: " + textStatus + " | " + errorThrown + " | " + xhr);
}
});
});
});
</script>
</html>
You can use $.ajax() for this - or one of the shortcuts, e.g. $.getJSON():
$.getJSON('somefile', function(data) {
// here, data is javascript object represented by the json in somefile
});