Here's my code in a javascript function in a HTML file
var url = 'http://query.yahooapis.com/v1/public/yql';
var startDate = '2012-01-01';
var endDate = '2012-01-08';
var jsonData = encodeURIComponent('select * from yahoo.finance.historicaldata where symbol in ("YHOO","AAPL","GOOG","MSFT") and startDate = "' + startDate + '" and endDate = "' + endDate + '"');
$.getJSON(url, 'q=' + data + "&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json", function(){alert("done!");});
When i open the file in the browser, my other functions work except the above as it produces:
GET http://query.yahooapis.com/v1/public/yql?q=[object%20Object]&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json 400 **(Bad Request)** jquery-1.8.3.min.js:2
send jquery-1.8.3.min.js:2
v.extend.ajax jquery-1.8.3.min.js:2
v.(anonymous function) jquery-1.8.3.min.js:2
v.extend.getJSON jquery-1.8.3.min.js:2
drawChart
Should this:
$.getJSON(url, 'q=' + data + "&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json", function(){alert("done!");});
be this?
$.getJSON(url, 'q=' + jsonData + "&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json", function(){alert("done!");});
Just a heads up - I have a couple of projects (Java and JavaScript) which call this API. They usually work but occasionally fail with a 400 without any change to the code then work a few hours/days later, again, without changing the code. I think if there is some problem with the server it may return this rather than a correct error in the 500 range (server error - It's me, not you)
Errors in the 400 range should be a message from the server along the lines of "it's you, not me - fix your request before you send it again" but I don't think this is the case with this API.
In short - it may be them not you!
Related
I am trying to build a small app via cordova that sends data to a PERL-Script on a server. The debug and release build work fine on the genymotion emulator, however sending the data from Android phones does not work. There is no error message from the app (either, which is supposed to show up when the connection fails).
Running USB debugging, I do get the follwoing invoke error message (the savedataLastpage funtion is supposed to send the data):
Uncaught TypeError: Illegal invocation
at e (jquery-2.1.3.min.js:4)
at Ac (jquery-2.1.3.min.js:4)
at Function.n.param (jquery-2.1.3.min.js:4)
at Function.ajax (jquery-2.1.3.min.js:4)
at Object.saveDataLastPage (index.js:631)
at Object.renderLastPage (index.js:461)
at Object.recordResponse (index.js:597)
at HTMLButtonElement.<anonymous> (index.js:357)
at HTMLButtonElement.dispatch (jquery-2.1.3.min.js:3)
at HTMLButtonElement.r.handle (jquery-2.1.3.min.js:3)
The pertaining code is the following:
index.js:631
saveDataLastPage:function() {
$.ajax({
type: 'post',
url: '/URL/',
data: localStore,
crossDomain: true,
success: function (result) {
var pid = localStore.participant_id, snoozed = localStore.snoozed, uniqueKey = localStore.uniqueKey, pause_time=localStore.pause_time;
localStore.clear();
localStore.participant_id = pid;
localStore.snoozed = snoozed;
localStore.uniqueKey = uniqueKey;
localStore.pause_time=pause_time;
$("#question").html("<h3>Thank you, your responses have been sent.</h3>");
},
error: function (request, error) {
console.log(error);
$("#question").html("<h3>Error: Please check your internet connection.</h3><br><button>Send again</button>");
$("#question button").click(function () {app.saveDataLastPage();});
}
});
},
index.js:461
else {
var datestamp = new Date();
var year = datestamp.getFullYear(), month = datestamp.getMonth(), day=datestamp.getDate(), hours=datestamp.getHours(), minutes=datestamp.getMinutes(), seconds=datestamp.getSeconds(), milliseconds=datestamp.getMilliseconds();
localStore[uniqueKey + '.' + "completed" + "_" + "completedSurvey" + "_" + year + "_" + month + "_" + day + "_" + hours + "_" + minutes + "_" + seconds + "_" + milliseconds] = 1;
app.saveDataLastPage();
}
As stated before, on the genymotion emulator the ajax script works fine without the error and sends the data to the script.
I'm not sure why the emulator would work just fine but the error Uncaught TypeError: Illegal invocation suggests that it is a problem with the ajax post call. Specifically, the default setting of processing the data into a query string likely fails.
From the ajax documentation:
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
That means you can either turn off the processing processData: false which will post the data in the body of the request or you have to transform the localStore data into a proper object (from whatever it was before).
If it is like an object you can do the following:
var data = {};
for (var elem in localStore) {
data[elem] = localStore[elem];
}
or possibly in brief:
var data = {};
localStore.each(function(elem) { data[elem.name] = elem.value; });
I want to get a mail if an error occurs in my program. This works fine:
window.onerror = function(msg, url, line, col, error) {
prog = "fehler";
var urlJ = server + prog + querystrJsonO + "&qu=" + qu + "&msg=" + msg + "&line=" + line + "&col=" + col;
$.getJSON(urlJ, function(data) {});
};
But I get only linenumber 1.
My code is not minified. What can I do to get the linenumber of the error?
Try creating a XMLHttpRequest inside the function and send a get request to your server with a phone script ready to receive the parameters. Then you can use mail() function to send yourself mail regarding problem. Am using it hope it sounds well to you
I am using Yahoo Weather API.
Here is my code:
<script>
var callbackFunction = function (data) {
console.log(data);
var location = data.query.results.channel.location;
var condition = data.query.results.channel.item.condition;
var wind = data.query.results.channel.wind;
var units = data.query.results.channel.units;
document.getElementById('Weather-Info').innerHTML = 'The weather for ' + location.city + ', ' + location.region + ' is ' + condition.temp + units.temperature + ' with a wind speed of ' + wind.speed;
}
callbackFunction()
<script src="https://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20weather.forecast%20WHERE%20woeid%3D%222409681%22%20and%20u%3D%22f%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=callbackFunction"></script>
Everytime I go into the page I receive the following pop-up:
Unable to get property 'query' of undefined or null reference
But if I hit No, the data is still populated.. how is it populating data if it is telling me that a property is undefined? The YQL Weather API is a really complicated.
Why are you calling the callback function yourself? In any case, calling it without a parameter, means that data will be undefined and this is why you get the error.
I know nothing about Yahoo! weather API but this seems like a JSONP thing, so try removing this part:
callbackFunction()
since this will be called automatically once the script loads.
In NetSuite, I'm trying to create a form Portlet POST data to a RESTlet in JSON. I've checked the documentation and internet and all the examples I've been able to find are GET requests or they post to a backend Suitelet instead.
I've come to a point where I can make the request reach the RESTlet but it's not being formatted in JSON, so I get the following error:
Account: xxxxxxxxxxxxx
Environment: Production Date & Time: 6/11/2015 5:09 pm
Execution Time: 0.06s
Script Usage: 0
Script: gw_SS_FormBackend
Type: RESTlet
Function: postWMForm
Error: UNEXPECTED_ERROR
SyntaxError: Empty JSON string (null$lib#3)
I'm using the following code to set the submit button and it's working fine:
var headers = new Array();
headers['User-Agent-x'] = 'SuiteScript-Call';
headers['Authorization'] =
'NLAuth nlauth_account=' + cred.account +
', nlauth_email=' + cred.email +
', nlauth_signature=' + cred.password +
', nlauth_role=' + cred.role;
headers['Content-Type'] = 'application/json';
portlet.setSubmitButton(nlapiRequestURL(getRESTletURL(), null, headers, 'POST'), 'Submit', '_hidden');
My problem is I don't know how to convert the form data to JSON before submitting it.
I'd appreciate any help.
Why would you want to use a RESTlet? If you are in a portlet then you already have a valid NS session so you'd be better off using a Suitelet. A Suitelet you know is set up to handle JSON would be called thus:
nlapiRequestURL(suiteletURL', JSON.stringify{test:'it', when:new Date(), by:'Brett'}), {"content-type":'application/json'}, function(resp){console.log(resp.getBody());}, 'POST');
and your Suitelet code might include something like:
var body = request.getBody();
nlapiLogExecution('DEBUG', 'posted body', body);
var asJSON = JSON.parse(body);
var user = nlapiGetContext().getUser(); // system already knows who this is.
...
var obj = {
success:true,
stuff: asProcessed
};
response.setContentType('JAVASCRIPT');
response.writeLine( JSON.stringify(obj) );
Not quite as clean as a RESTlet but you avoid having to hack the credentials.
you can use JSON.stringify() function.
var headers = new Array();
headers['User-Agent-x'] = 'SuiteScript-Call';
headers['Authorization'] =
'NLAuth nlauth_account=' + cred.account +
', nlauth_email=' + cred.email +
', nlauth_signature=' + cred.password +
', nlauth_role=' + cred.role;
headers['Content-Type'] = 'application/json';
var myJsonHeader = JSON.stringify(headers);
portlet.setSubmitButton(nlapiRequestURL(getRESTletURL(), null, myJsonHeader, 'POST'), 'Submit', '_hidden');
Regards
I'm struggling with a scope question.
Basically, I am making an API request with jQuery's $.getJSON()
Then I intend to use the result to draw a graph with D3.js.
var url = 'http://query.yahooapis.com/v1/public/yql';
var startDate = '2013-09-06';
var endDate = '2014-03-06';
var req = encodeURIComponent('select * from yahoo.finance.historicaldata where symbol in ("YHOO") and startDate = "' + startDate + '" and endDate = "' + endDate + '"');
var dd = $.getJSON(url, 'q=' + req + "&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json", function(data) {
console.log(data);
console.log(data.query.results.quote[0]);
});
console.log("lol"); //works fine
console.log(data); //doesn't work
console.log(dd); //works
console.log(dd.data); //doesn't work
I am very confused.
How can I use the results of my query in d3.js?
Thank you very much
$.getJSON is asynchronous. This means that when you execute the code, it sends off the request. Then the code below it is executed -- nothing has come back yet. When the request returns, the handler function is called with the data. This is where you need to do everything you want to do with the data.
$.getJSON(url, function(data) {
// make graph
});
Note that D3 provides its own function for retrieving JSON:
d3.json(url, function(error, data) {
// make graph
});