I am building a TVML application for Apple TV. When I run this code to make a request to a remote server I get this error: SyntaxError: JSON Parse error: Unexpected EOF. I am trying to run the code from the application.js file and populate the applications inital view. Any help is appreciated.
loadData("https:/xxx.xxx.net")
function loadData(url) {
var xhr;
var jsonData;
xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.onreadystatechange = function() {
if (xhr.status == 200) {
jsonData = JSON.parse(xhr.responseText);
console.log(jsonData);
};
};
xhr.open("GET", url, true);
xhr.send();
if (jsonData != undefined) { return jsonData }
};
Other devices like Roku use the same api and function correctly.
{
"playlists": [
{
"id": 8,
"title": "test",
"description": "new playlist test",
"cover_url": "http://598-1446309178.png"
},
{
"id": 9,
"title": "test1",
"description": "lives",
"cover_url": "http://754-1446309324.jpg"
},
{
"id": 10,
"title": "test2",
"description": "video games",
"cover_url": "http://6173-1446310649.jpg"
},
{
"id": 11,
"title": "test4",
"description": "little",
"cover_url": "http://dd6-1446312075.jpg"
}
]
}
You can debug your app using Safari.
Once your app is running, choose "Develop / Simulator / {your app}".
That part of your code looks OK, but check what xhr.responseText is, it may return empty.
Your other error is that you are making an async request when you use "true" below:
xhr.open("GET", url, true);
You need to supply a callback to your function and use that callback.
I am using error first callback style.
function loadData(url, callback) {
var xhr;
var jsonData;
xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.onreadystatechange = function() {
if (xhr.status == 200) {
try{
jsonData = JSON.parse(xhr.responseText);
} catch(e) {
return callback('json parsing error');
}
callback(null, jsonData);
console.log(jsonData);
};
};
xhr.open("GET", url, true);
xhr.send();
};
Related
I'm sending a JSON request (an applicative login but the kind of request doesn't matter) to a server with the following function:
function login() {
var payload = {
"api_key" : "", "cmd" : "login",
"params" : {}
}
payload["params"]["username"] = document.getElementById("uname").value
payload["params"]["password"] = document.getElementById("passwd").value
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:4000/api", true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
resp = JSON.parse(xhr.responseText);
console.log("resp.status=" + resp.status);
console.log("resp.[\"status\"]=" + resp["status"]);
}
}
xhr.send(JSON.stringify(payload));
}
I'm actually getting the correct reply in the responseText field. For example, if the credentials are wrong, I get
{
"status": "ko",
"errors": [
{
"cmd": "login",
"long": "Login error : 'user-20' has no access to the system",
"short": "login_error"
}
]
}
If the credentials are OK I get
{
"status": "ok",
... some additional data
}
Yet, I can't manage to get the status field : resp.status or resp["status"] are always undefined. Same if the call is done in asynchroneous mode (xhr.open("POST", "http://localhost:4000/api", false);) or if I don't JSON.parse() the reply, ie: resp = xhr.responseText;.
Update - 2017.09.06
I finally found a way to get it working, but I don't quite understand why it is so. I actually changed
resp = JSON.parse(xhr.responseText);
into
resp = JSON.parse(JSON.parse(xhr.responseText));
To figure this out, I printed typeof(xhr.responseText) which is a sting. Actually typeof(JSON.parse(xhr.responseText)) is also a string and this is why it has no fields like status. Eventually, parsing xhr.responseText twice gives an object from which I actually can retrieve my data.
If somebody has a clue about what is happening, I would be interested... I don't know if this is related, but the app server that is sending the JSON is the latest version of Elixir/Phoenix, ie, 1.5/1.3 and JSON encoding/decoding is done with poison.
This is because you have assigned the resp variable to responseText
resp = JSON.parse(xhr.responseText);
To get the response code
respCode = xhr.status
Or if you want both in the same resp variable you could do
resp = {
responseText: xhr.responseText,
status: xhr.status
}
Then you can access them as resp.responseText and resp.status
I´m trying to save customers metafields using the shopify admin api, i´m using this code
var data = {
"metafield": {
"namespace": "test",
"key": "testkey",
"value": "lorem ipsum",
"value_type": "string"
}
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "/admin/customers/0000000000/metafields.json", true);
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", 'Basic ' + btoa('myuser:mypass'));
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function () {
console.log(xhr.responseText);
};
xhr.send(JSON.stringify(data)); //RETURNS A CODE 301 WITHOUT RESPONSE MESSAGE
xhr.send(data); //RETURNS A CODE 400 WITH "error 419: unexpected token at 'object Object]'" MESSAGE
Please tell me What I missing?
Thanks a lot
It looks like you are trying to save the metadata to customer id 00000000 in your URL, typically you'll want to have that field supplied dynamically if this is going to be used in a utility tool. Your probably might be that ID is not pointing at an actual customer ID.
I am trying to access cross-domain data by using jsonp or XMLHttpRequest with GET method. My Code:
XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/ajax.php?code=BSE", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert(xhr.responseText);
}
xhr.send();
JsonP
$.ajax({
type: 'GET',
url: "http://example.com/ajax.php?code=BSE",
dataType: "jsonp",
jsonpCallback: "jsonp_callback",
crossDomain: true,
success: function(res){
console.log(res);
}
});
Both methods having same behavior. Whenever i am sending request its just keep loading (even i am not sure its sending request or not) and do nothing.
And my php code:
PHP Code:
header('content-type: application/json; charset=utf-8');
$dts=array('value'=>'123');
echo $_GET['jsonp_callback'] . '('.json_encode($dts).')';
The XMLHttpRequest will work just fine, no need for jsonp. In your manifest.json, make sure you request permissions for the domain you are posting to -- Chrome doesn't require permissions for XHR, but Firefox does. This error manifests in Firefox as a http code 404 in the XHR, but no activity in the network panel. If you get a http code 0, you have CORS or mixed content security issues as well.
{
"manifest_version": 2,
"name": "web extension",
"version": "1",
"permissions": [
"http://example.com/"
],
"content_scripts": [
{
// ...
}
]
}
Try using new XDomainRequest() in your xhr request. XDomainRequest is an implementation of HTTP access control (CORS).
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var url = 'http://example.com/ajax.php?code=BSE';
var method = 'GET';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
// Success code goes here.
};
xhr.onerror = function() {
// Error code goes here.
};
xhr.setRequestHeader('content-type', 'application/json; charset=utf-8');
xhr.send();
When I say console.log(getErrors) I receive this in the console:
XMLHttpRequest {statusText: "", status: 0, responseURL: "", response: "", responseType: ""...}
onabort: null
onerror: null
...
responseText: {"content":[{"id":1,"timeStamp":"2015-03-20T00:01:44.761","provider":"foo","providerId":null,"lineNumber":1,"summary":"foo","description":"foo: 1"}...
responseType: ""
responseURL: "http//localhost:8080/errors/findAll"
...
I know I'm getting the data because I can see it in responseText but when I say console.log(getErrors.responseText) I'm getting an empty string. I'm not sure what I'm doing wrong.
Javascript:
var getErrors = new XMLHttpRequest();
getErrors.open('GET', '/errors/findAll', true);
getErrors.send();
//var response = getErrors.responseText;
console.log(getErrors);
console.log(getErrors.responseText);
Here is my working code in Javascript:
getErrors = function(url, callbackFunction) // How can I use this callback?
{
var requestErrors = new XMLHttpRequest();
requestErrors.onreadystatechange = function()
{
if (requestErrors.readyState == 4 && requestErrors.status == 200)
{
callback(requestErrors.responseText); // Another callback here
}
}
requestErrors.open('GET', url);
requestErrors.send();
}
function callback(data) {
console.log(data);
}
getErrors('/errors/findAll', callback);
I am making extension for Chrome and I need to pass the url of active tab to file with php code. My manifest.json code:
{ "name": "demo",
"version": "1.0",
"manifest_version": 2,
"description": "Making your first Google Chrome extension.",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "chrome.html"
},
"permissions": [
"http://www.mysite.com/",
"tabs"
]
}
and AJAX code:
window.onload = function() {
var XHR = new XMLHttpRequest;
chrome.tabs.query({active:true,currentWindow:true},
function(tab){tabUrl = tab.url;});
XHR.open('GET', 'http://www.mysite.com/chrome/chrome.php?tab='+tabUrl+'', true);
XHR.onreadystatechange = function () {
if (4 == this.readyState) {
var status = this.status;
if (400 > status) {
var responseText = this.responseText;
if (responseText) {
document.getElementById('resultado').innerHTML = responseText;
}
}
}
};
XHR.send();
}
Thanks for help.
I think you should do it like this, because in your code, since tabs.query is asynchronous, when XHR.send(); gets executed tabUrl isn't set yet.
window.onload = function() {
var XHR = new XMLHttpRequest;
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tab) {
tabUrl = tab.url;
XHR.open('GET', 'http://www.mysite.com/chrome/chrome.php?tab=' + tabUrl + '', true);
XHR.onreadystatechange = function() {
if(4 == this.readyState) {
var status = this.status;
if(400 > status) {
var responseText = this.responseText;
if(responseText) {
document.getElementById('resultado').innerHTML = responseText;
}
}
}
};
XHR.send();
});
}