XMLHttpRequest problem in BlackBerry 10 (QML) - qt

Hello a have a problem with my javascript.
Can you help me?
Thank everybody.
When I have:
var url = "http://naucse-python.now.sh" // error -> Redirect to http://naucse-python.now.sh/ (308)
var url = "https://naucse-python.now.sh" // nothing is displayed
When I have:
var url = "http://jsonplaceholder.typicode.com/todos/1" // everything is OK
var url = "https://jsonplaceholder.typicode.com/todos/1" // nothing is displayed
// main.qml
import bb.cascades 1.4
Page {
function sendRequest() {
var xhr = new XMLHttpRequest();
var url = "http://naucse-python.now.sh"
//var url = "http://jsonplaceholder.typicode.com/todos/1"
xhr.onreadystatechange = function() {
//if (xhr.readyState === XMLHttpRequest.DONE) {
//if (xhr.status === 200) {
console.log(xhr.responseText);
textArea.text = xhr.responseText;
//}
//}
};
xhr.open("GET", url, true);
xhr.send();
}
Container {
TextArea {
id: textArea
}
}
onCreationCompleted: {
sendRequest()
}
}

Related

AEM Site search query builder URL is not returning a different json

Am using AEM Site search component from core components. query builder URL is not returning a different json.
Once after searching with a text, am getting a json. Thereafter doing any search with new search text, am getting only the same json, not a new json. Only old response am getting in all search.
var request = new XMLHttpRequest();
if (self._hasMoreResults) {
var response;
var url = self._action + "?" + serialize(self._elements.form) + "&" + PARAM_RESULTS_OFFSET + "=" + self._resultsOffset;
request.open("GET", url, true);
request.onload = function() {
setTimeout(function() {
toggleShow(self._elements.loadingIndicator, false);
toggleShow(self._elements.icon, true);
}, LOADING_DISPLAY_DELAY);
if (request.status == 200 ) {
debugger;
var data = JSON.parse(request.responseText);
if (data.length > 0) {
self._generateItems(data, self._elements.results);
self._markResults();
toggleShow(self._elements.results, true);
} else {
self._hasMoreResults = false;
}
if (self._elements.results.querySelectorAll(selectors.item.self).length % self._properties.resultsSize > 0) {
self._hasMoreResults = false;
}
} else {
// error status
}
};
toggleShow(self._elements.loadingIndicator, true);
toggleShow(self._elements.icon, false);
request.send('');
}
};

YDN-DB - Delete DB then recreate and load when page is loaded/reloaded but not when refreshed

I'm converting some IndexedDB code to use YDN-DB and need some help in converting this. This code essentially deletes the DB if the page is loaded or reloaded but not when it is refreshed.
How would I accomplish that using YDN-DB?
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
var db;
window.refreshing = false;
$(document).ready(function(){
if(window.performance) {
if(performance.navigation.type == 0 ) {
// The db already exists so delete it and re-create it so we don't have stale records.
deleteDB();
} else {
window.refreshing = true;
open();
}
}
});
function deleteDB() {
var request = indexedDB.deleteDatabase("DocsDB");
request.onsuccess = function() {
open();
}
request.onerror = function(event) {
throw "Error in deleteDB.";
}
}
function open() {
var request = indexedDB.open("DocsDB");
var upgraded = false;
request.onupgradeneeded = function(evt) {
upgraded = true;
var dbnew = evt.target.result;
dbnew.onerror = function(event) {
console.log("IndexedDB error: " + evt.target.error.code);
};
var objectStore = dbnew.createObjectStore(
"docs", { keyPath: "id", autoIncrement: true });
objectStore.createIndex("docname", "DOC_NAME", { unique: false });
objectStore.createIndex("printdate", "PRINT_DATE", { unique: false });
}
request.onsuccess = function(evt) {
db = request.result;
if (!upgraded && !window.refreshing) {
throw "Not upgraded";
}
request.result.onversionchange = function(e) {
if (e.newVersion === null) { // An attempt is made to delete the db
e.target.close(); // Manually close our connection to the db
}
};
if(typeof db != 'undefined' && !window.refreshing) {
// We load the store with the records here, attempting to add records via ajax doesn't work
// looks like we'll ahve to load them via ajax before initialization?
var store = getObjectStore(db);
for (i=0; i<documents["Rows"].length-1;i++) {
store.add(documents["Rows"][i]);
}
}
}
request.onerror = function() {
throw "Error in open";
}
}
function getObjectStore(db, mode = 'readwrite') {
if(typeof db != 'undefined') {
var tx = db.transaction('docs', mode);
return tx.objectStore('docs');
} else {
return null;
}
}
To delete a database use, ydn.db.deleteDatabase("DocsDB").

How can i get POST raw body in Meteor restivus?

How can i get POST raw body in Meteor restivus?
tried something, but it's not working.
this is the code.
if(Meteor.isServer) {
var Api = new Restivus({
useDefaultAuth: true
});
Api.addRoute('test', {authRequired: false}, {
post: {
action: function() {
var response;
var readable = this.request;
var rawBody = "";
readable.on('data', function(chunk) {
rawBody += chunk;
});
readable.on('end', Meteor.bindEnvironment(function() {
//dosometing and insert into Collection
//make response data
}));
return response;
}
}
});
}
it's proceed return response and then readable.on('end'.. )
so, it's error by return null.
if i moved return response into readable.on('end'...), also same error.
i think if can wait POST return until readable.on('end'..) is finished, it will be work, but i don't know how.
You can use node-fibers's Future to wait until readable.on('end', ..) is called.
if(Meteor.isServer) {
var Future = Npm.require('fibers/future');
var Api = new Restivus({
useDefaultAuth: true
});
Api.addRoute('test', {authRequired: false}, {
post: {
action: function() {
var response;
var readable = this.request;
var rawBody = "";
var future = new Future();
readable.on('data', function(chunk) {
rawBody += chunk;
});
readable.on('end', Meteor.bindEnvironment(function() {
//dosometing and insert into Collection
//make response data
future.return(response); //response is what you want to return
// you can also throw error using future.throw(err);
}));
return future.wait();
}
}
});
}

Consuming image from API and displaying it on browser in meteor

I have a API that returns image and want to display the image on the browser. I am using iron:router package. On the client side user click on a link which is a basically a server side iron:route. The route makes call to API and should display the response of API on the browser.
client js : -
Template.images.events({
'click .image': function (event, template) {
event.preventDefault();
var docId = $(event.target).attr('data-docId');
var imageType = "raw";
var param = {"docId":docId,"imageType":imageType};
params = 'width=' + window.innerWidth;
params += ', height=' + window.innerHeight;
params += ', top=0, left=0'
params += ', fullscreen=yes';
var win = window.open("/Image/?param=" + encodeURIComponent(Base64.encode(JSON.stringify(param))), "_blank", params);
}
});
Iron:route : -
Router.route('/checkImage', function () {
var decoded = Base64.decode(decodeURIComponent(this.params.query.param));
var param = JSON.parse(decoded);
var docId = param.docId;
var content="";
Meteor.call('imageApi', docId, imageType, function (error, result) {
if (error) {
content = "";
} else
content = new Buffer(result);
});
if (content == "") {
this.response.writeHeader('200', {
'Content-Type': 'image/jpeg',
'Content-Disposition': "inline",
'Access-Control-Allow-Origin': '*'
});
this.response.write('<html><body><p>No content for image found.</p></body></html>');
this.response.end();
}
else {
this.response.writeHeader('200', {
'Content-Type': 'image/jpeg'
'Content-Disposition': 'inline; filename=image.jpg'
});
this.response.write(content);
this.response.end();
}
}, {where: 'server'});
Server method : -
imageApi: function (docId, imageType) {
var url = "API url with the paramters ";
var response;
try{
response = HTTP.call('GET', url, {
headers: {"Content-Type": "image/jpeg"},
responseType: "buffer"
});
}catch (error) {
logger.error("imageApi - Exception in image API " + error);
return false;
}
if (response.statusCode == 200) {
return new Uint8Array(response.content);
}
else {
logger.error"imageApi - Response issue: " + response.statusCode);
return "";
}
return "";
}
I am not able to display the image data on the browser. Do you think something is wrong in this approach or else if there is another way to render image.

Update dynamic data in service-worker.js

I have the below data coming in form of array from a url.
[{"title":"hey hi","body":"hello","url":"https://simple-push-demo.appspot.com/","tag":"new"}]
service-worker.js
it has the above url in fetch()
'use strict';
console.log('Started', self);
self.addEventListener('install', function(event) {
self.skipWaiting();
console.log('Installed new', event);
});
self.addEventListener('activate', function(event) {
console.log('Activatednew', event);
});
self.addEventListener('push', function(event) {
try{
console.log('Push message', event);
var ev = event;
//sample
return fetch("http://localhost/push-notifications-master/app/json.php").then(function(ev,response) {
response = JSON.parse(JSON.stringify(response));
return response;
}).then(function(ev,j) {
// Yay, `j` is a JavaScript object
console.log("j", j);
for(var i in j) {
var _title = j[i].title;
var _body = j[i].body;
var _tag = j[i].tag;
console.log("_body", _body);
}
ev.waitUntil(
self.registration.showNotification("push title", {
body: _body,
icon: 'images/icon.png',
tag: _tag
}));
});
return Promise.all(response);
}
catch(e){console.log("e", e)}
});
I am trying to see the above array data coming from that particular url in console.log("j",j);. but it shows undefined. How can i get dymanic data in sw.js Please Guide.
In your addEventListener('push' .... method, I think it might be better to wait for a response before parsing it.
Also, to be checked, but your php request should be in https (not checked by myself, but my request are on https).
Here how I do this :
event.waitUntil(
fetch('YOUR PHP URL').then(function(response) {
if (response.status !== 200) {
console.log('Problem. Status Code: ' + response.status);
throw new Error();
}
// Examine the text in the response
return response.json().then(function(data) {
if (data.error || !data.notification) {
console.error('The API returned an error.', data.error);
throw new Error();
}
var title = data.notification[0].title;
var body = data.notification[0].body;
var icon = data.notification[0].icon;
var notificationTag = data.notification[0].tag;
return self.registration.showNotification(title, {body: body,icon:icon, tag: notificationTag});
});
})
);
The json :
{"notification" : [{"title":"TITLE","body":"BODY","icon":"URL TO ICON","tag":"TAG"}]}
Hope it can be useful.

Resources