$.getJSON SyntaxError: missing ; before statement, why? - javascript

I am having a problem with some code. Here is what the JSON response looks like:
{"cars":"1","bikes":"1"}
Here is the jQuery code:
$(function() {
$.getJSON('https://myurlhere.com?filename=aapl-c.json&callback=?', function(data) {
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector: {
selected: 1
},
title: {
text: 'AAPL Stock Price'
},
series: [{
name: 'AAPL',
data: data,
tooltip: {
valueDecimals: 2
}
}]
});
});
});
Here is the error I'm getting:
SyntaxError: missing ; before statement {"cars":"1","bikes":"1"}
What am I doing wrong here?

From the $.getJSON documentation:
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead.
This is the cause of your problem as your return data is in JSON format, not JSONP. You just need to remove that property from the querystring of the request:
$.getJSON('https://myurlhere.com?filename=aapl-c.json', function (data) {
// the rest of your code...
});

Related

How can I replicate this ajax call using an Angular $resource?

I am attempting to make calls to the Mockaroo API.
This example they use in the docs works when I make the same call from my angular app (this probably goes without saying - but I did replace the api key here with my own api key - the same is true for the attempts below as well)
Working Example (using $.ajax)
var fields = [{
name: "yearsEmployed",
type: "Number",
min: 1,
max: 30,
decimals: 0
}, {
name: "department",
type: "Custom List",
values: ["R+D", "Marketing", "HR"]
}, {
name: "dob",
type: "Date",
min: "1/1/1950",
max: "1/1/2000",
format: "%m/%d/%Y"
}];
var url = 'http://www.mockaroo.com/api/generate.json?key=abcd1234' +
'&fields=' + encodeURIComponent(JSON.stringify(fields));
$.ajax(url, {
dataType: 'jsonp',
contentType: 'application/json',
success: function(data) {
console.log('yearsEmployed', data.yearsEmployed);
console.log('department', data.department);
console.log('dob', data.dob);
}
});
However, I would like to use an angular $resource, but when I try replacing the $.ajax portion of the example above using any of these methods, I get errors. What is the correct method to accomplish this?.
Attempt #1
// using fields variable from above example
var url = 'http://www.mockaroo.com/api/generate.json?key=:key' +
'&fields=:fields';
var params = {
key: 'abcd1234',
fields: fields
}
return $resource(url, params, {
all: {method:'JSONP', isArray: false }
});
Attempt #1 error:
GET http://www.mockaroo.com/api/generate.json?key=abcd1234&fields=%5Bobject%20Object%5D,%5Bobject%20Object%5D,%5Bobject%20Object%5D
Attempt #2
// using fields variable from above example
var url = 'http://www.mockaroo.com/api/generate.json?key=:key' +
'&fields=:fields';
var params = {
key: 'abcd1234',
fields: fields
}
return $resource(url, params, {
all: {method:'POST', isArray: false }
});
Attempt #2 error:
XMLHttpRequest cannot load http://www.mockaroo.com/api/generate.json?key=abcd1234&fields=%5Bobject%20Object%5D,%5Bobject%20Object%5D,%5Bobject%20Object%5D. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 400.
Attempt #3:
// using fields AND url variables from example above
return $resource(url, {}, {
all: {method:'POST', isArray: false }
});
Attempt #3 error
XMLHttpRequest cannot load http://www.mockaroo.com/api/generate.json?key=abcd1234&fields=%5B%7B%22name…ax%22%3A%221%2F1%2F2000%22%2C%22format%22%3A%22%25m%2F%25d%2F%25Y%22%7D%5D. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
Attempt #4:
// using fields AND url variables from example above
return $resource(url, {}, {
all: {method:'JSONP', isArray: false }
});
Attempt #4 error:
Refused to execute script from 'http://www.mockaroo.com/api/generate.json?key=abc31234&fields=%5B%7B%22name…ax%22%3A%221%2F1%2F2000%22%2C%22format%22%3A%22%25m%2F%25d%2F%25Y%22%7D%5D' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.
Edit #1
Updated Attempt #1
var params = {
key: 'abcd1234',
fields: JSON.stringify(fields)
}
Updated Attempt #1 Error:
Refused to execute script from 'http://www.mockaroo.com/api/generate.json?key=abcd1234&fields=%5B%7B%22name…2,%22max%22:%221%2F1%2F2000%22,%22format%22:%22%25m%2F%25d%2F%25Y%22%7D%5D' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.

Highchart with external CSV (in external domain)

I can draw charts with JSON values, in another domain. I use ajax, and a callback to make crossdomain and get values.
function drawChart() {
var options = {
chart: {
renderTo: 'chart01',
marginRight: 0,
marginTop: 60,
type: 'column',
options3d: {
enabled: true,
alpha: 15,
beta: 15,
viewDistance: 25,
depth: 90
}
},
plotOptions: {
column: {
depth: 90
}
},
title: {
text: 'CSV Values'
},
xAxis: {
title: {
text: '',
margin: 0
},
categories: []
},
yAxis: {
title: {
text: 'Title'
},
},
tooltip: {
enabled: false
},
series: []
};
$.ajax({
url: "http://<external_path>/json.asp?callback=?",
data: 'show=impression',
type: 'post',
dataType: "json",
success: function (data) {
var intSeries = data.length;
var cont = 0;
if (intSeries > 0) {
intSeries--;
options.xAxis.categories = data[cont]['data'];
while (cont < intSeries) {
options.series[cont] = data[cont + 1];
cont++;
}
var chart = new Highcharts.Chart(options);
}
}
});
};
In json.asp (in another server) I return json values with callback:
Response.ContentType = "application/json"
dim strJSON
strJSON = "" & _
"[" & _
"{" & _
"""name"": ""General Values""," & _
"""data"": [""Porcentaje""]" & _
"}, {" & _
"""name"": ""Value 1""," & _
"""data"": [34.60436]" & _
"}, {" & _
"""name"": ""Value 2""," & _
"""data"": [12.30343]" & _
"}, {" & _
"""name"": ""Value 3""," & _
"""data"": [53.30423]" & _
"}" & _
"]"
response.write request.QueryString("callback") & "(" & strJSON2 & ")"
It works fine. My problem is to run charts using an external CSV or XML. I've proved some ways, but I always get an error 401 Unauthorized. I change from dataType: "json" to dataType: "text" or dataType: "xml" (CSV and XML mode), and with the new external path, but it doesn't work.
How I would get values from an external CSV or XML file?? I can't put on my server that files, so I need it was in another server.
UPDATE:
I've added on my server to enable CORS with this values:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Authorization
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Origin: *
and I've modified ajax method:
$.ajax({
url: "http://<external_path>/test.csv",
type: 'post',
dataType: "text",
xhrFields: {
withCredentials: true
}
//-- I've tried to authenticate without success
//beforeSend: function (request){ request.setRequestHeader( ""Authorization"", btoa('<user>:<pass>')); },
success: function (data) {
//---- Code to get values ----//
}
});
After the changes, I go on with 401 error.
One way is to run a simple proxy on your server which fetches the data for you. i.e. you request the data from your proxy process, which requests the data for from the remote system and returns it to you.
This problem is a classic example of needing to get round cross-domain restrictions. There are plenty of questions and answers about this topic on StackOverflow.

How to use select2 with remote data if the data items don't provide the "id" and "text" fieldnames?

I have a select2 dropdown, which is configured for using with remote data. However, my remote datasource provides the search results in a format which seems to be not compatible with select2. The remote data is for example like this:
...
items: [ { value: 1, displayText: "First" }, { value: 2, displayText: "Second" } ]
...
but select2 seems to expect the "id" and "text" fields instead. I've checked all options, and tried to play with formatSelection, formatResult callbacks, but had no success until now, I always get javascript errors about "item.text" being undefined.
I cannot provide a jsFiddle because the web API is not public unfortunately.
Is there a way to configure select2 for using a custom "id" and "text" field? Or what else could be a good workaround for this scenario?
Ok, I figured it out almost immediately after I posted my question. Probably this is not the most efficient way to do this, so I'm still happy if someone has a better answer.
I managed to do a conversion in the results callback in the ajax options.
$("#mySelect").select2({
minimumInputLength: 3,
ajax: {
url: '/',
params: {
type: 'POST',
dataType: 'json',
},
quietMillis: 200,
data: function(term, page) { // page is the one-based page number tracked by Select2
return {
search: term,
pageSize: 10,
pageIndex: page-1,
};
},
results: function(data, page) {
var more = (page * 10) < data.Total; // whether or not there are more results available
return { results: $.map(data.Results, function(e, i) {
return { id: e.value, text: e.displayText, data: e };
}), more: more };
}
}

Unable to properly update Flot graph on ajax response

I have a graph that is properly generated when the page loads. That code is:
<body>
<div id="placeholder" style="width:800px;height:400px;"></div>
<script type="text/javascript">
$(function () {
$.plot($("#placeholder"),
[ { data: %s } ],
{ xaxes: [ { mode: 'time' } ],
yaxes: [ ] })
});
</script>
Which works fine. I have a button that executes jquery and makes a request to get a new json data structure. I've validated that the json being returned is indeed proper json. I'm attempting to graph the result with:
<script type="text/javascript">
$(function() {
$("#button").click( function()
{
//alert('button clicked');
$.ajax({
url: '/graph',
type: 'POST',
dataType: 'html',
data: {
start_date: $('#start_date').val(),
end_date : $('#end_date').val(),
ticker : $('#ticker').val()
},
success: function(result) {
var placeholder = $("#placeholder");
$.plot(placeholder,
[ { data: result } ],
{ xaxes: [ { mode: 'time' } ],
yaxes: [ ] });
}
});
}
);
});
Which redraws the graph, but it's empty and the y-axes is the default -1.0 through 1.0 and the x-axes is a single time entry of 00:00:00.
I've tried to use the setData() and draw() method calls but they don't fix the issue.
There are no javascript errors being thrown as shown by firebug.
So, what am I doing wrong?
TIA!
Are you sure the response is valid? Your dataType is 'html', so unless you're doing something with a script tag, then the response is just a string. If you're returning JSON directly, then you need to use dataType 'json'.

Loading Highcharts series from XML using jQuery

I am trying to populate a highchart series from an xml source using jQuery. The XML file is an export from RRDTool and has the following format:
<data>
<row><t>1347559200</t><v>2.1600000000e+01</v></row>
<row><t>1347562800</t><v>2.1504694630e+01</v></row>
<row><t>1347566400</t><v>2.1278633024e+01</v></row>
.
.
.
</data>
My approach was to load the data using jQuery and push the series to the chart:
$.ajax({
type: "GET",
url: "data/data.xml",
dataType: "xml",
success: function(xml) {
var series = { data: []
};
$(xml).find("row").each(function()
{
var t = parseInt($(this).find("t").text())*1000
var v = parseFloat($(this).find("v").text())
series.data.push([t,v]);
});
options.series.push(series);
}
});
I end up getting the following error:
Unexpected value NaN parsing y attribute
I created a JSFiddle to demonstrate the code: http://jsfiddle.net/GN56f/
Aside from the cross-domain issue, the error is due to there being an existing empty series in the plot options. The initial series in the options should be set to:
series: []
instead of:
series: [{
name: 'Temperature',
data: []
}]
The subsequent call to options.series.push(series); merely adds a new series leaving the empty one unchanged.
Problems:
you forgot var before declare options and chart
forgot ; after end options
Hava you tried to log options before pass to Highcharts ? You're passing the following series.
That's the expected result ? I think no.
series: [{
name: 'Temperature',
data: []
}, {
data: [// data from xml]
}]
You're creating the chart before complete the request, so options.series.data.push will not work, you have to use setData to update dynamically, but there's a problem, you don't know how long the request you take, so I suggest you to create the chart inside the success.
Try the following.
success: function(xml) {
$('row', xml).each(function() {
options.series.data.push([t,v]);
});
//#todo: declare chart as global before the ajax function
chart = new Highcharts.Chart(options);
}

Categories