XMLHttpRequest ERROR in QML Blackberry 10 - json

I'm trying to get movie data for BlackBerry 10 apps.
I don't know where I'm making a mistake.
Please, can you help me?
Thank you all.
import bb.cascades 1.4
Page {
onCreationCompleted: {
sendRequest();
}
function sendRequest() {
var data = "{}";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://api.themoviedb.org/3/search/movie?include_adult=false&page=1&query=hulk&language=en-US&api_key=YOUR_API_KEY_HERE");
xhr.send(data);
}
}

You need to use the onreadystatechange EventHandler.
Also, you don't need to pass data when making a GET request.
I have removed the withCredentials line as it isn't needed in this example.
You can learn more on XMLHttpRequest here :
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
onCreationCompleted: {
sendRequest();
}
function sendRequest() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
var json = JSON.parse(xhr.responseText);
var results = json.results;
var count = results.length;
console.log("There are " + count + " results :");
json.results.forEach((value, index) =>
{
console.log(index + " - " + value.title);
});
}
};
xhr.open("GET", "https://api.themoviedb.org/3/search/movie?include_adult=false&page=1&query=hulk&language=en-US&api_key=YOUR_API_KEY_HERE");
xhr.send();
}
Here's an example of using XMLHttpRequest I've made a long time ago :
https://github.com/RodgerLeblanc/Markup/blob/master/assets/main.qml

Related

How can i make the HTML file open in Chrome while the calling browser is Explorer

I have this HTML (attached).
It is called by a web app that still works on I.E (for at least one or two months) due to some problems we have with the vendor.
The web app calls this HTML and it is opened in I.E also.
I need this HTML to be opened in Chrome.
Is there a way i can do this by adding something to the HTML itself?
<html>
<head>
<script>
async function setSRC(){
try{
var xhr;
const params = new Proxy(new URLSearchParams(window.location.search),
{
get: (searchParams, prop) => searchParams.get(prop),
});
var docId = params.docId;
var url = "``http://wsp-exttest.lcardtest.corp:4440/rest.oms/MaxRestService/getPDF?docId=``" + docId;
let response = await new Promise(resolve => {
xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function(e) {
resolve(xhr.response);
};
xhr.onerror = function () {
resolve(undefined);
console.error("** An error occurred during the XMLHttpRequest");
};
xhr.send();
})
//
var j = JSON.parse(xhr.responseText);
var pdfData = j[0].content;
var letterFrame = document.getElementById("letterFrame");
letterFrame.src = "data:application/pdf;base64," + pdfData;
/*letterFrame.onreadystatechange = () => {
if (letterFrame.readyState === 'complete') {
alert(letterFrame.readyState);
letterFrame.src = "data:application/pdf;base64," + pdfData;
}
};*/
}
catch(e)
{
if(confirm("Load faile: " + e.message + "click ok to retry"))
setSRC();
}
}
</script>
</head>
<body onload="setSRC()">
<iframe id="letterFrame" width="1200px" height="800px" onload=""></iframe>
Reload
</body>
</html>
Reload

OnHistoryStateUpdated creates chrome extension only when accessing Facebook

The code was changed to this code after using the on-updated event several times.OnHistoryStateUpdated is exactly what condition?
background.js
chrome.webNavigation.onHistoryStateUpdated.addListener(function (details) {
var domain = details.url;
var google = 'https://www.google.co.kr/';
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status === 200 || xhr.status === 201) {
console.log(xhr.responseText);
} else {
console.error(xhr.responseText);
}
};
xhr.open('POST', 'http://soylatte.kr:3000/image/check');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('url=' + domain);
})

Node Server receive XmlHttpRequest

I'm using the following code to send a session description (tiny JSON code - http://www.ietf.org/rfc/rfc2327.txt).
function sendMessage(message) {
var msgString = JSON.stringify(message);
console.log('C->S: ' + msgString);
path = '/message?r=67987409' + '&u=57188688';
var xhr = new XMLHttpRequest();
xhr.open('POST', path, true);
xhr.send(msgString);
}
I'm not sure how to go about retreiving the JSON on my Node.js server.
Here's a code that can handle POST request in node.js .
var http = require('http');
var server = http.createServer(function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var POST = JSON.parse(body);
// POST is the post data
});
}
});
server.listen(80);
Hope this can help you.

Fileupload using Filereader in chrome

I have to upload a file from the local memory of application (HTML5 File api). Onselect, the user should be able to upload directly without any question. The idea is to manage download/upload seamless to the user. Here is the code :
$("body").on("click", ".upload-file", function(e){
var fileToUpload = $('input:radio[name=optionsRadios]:checked').val();
var formData = new FormData();
$('input:radio[name=optionsRadios]:checked').parent().parent().parent().remove();
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.TEMPORARY, 50*1024*1024, initFS, errorHandler);
var reader = new FileReader();
function initFS(fs){
fs.root.getDirectory('/', {}, function(dirEntry){
var dirReader = dirEntry.createReader();
dirReader.readEntries(function(entries) {
for(var key = 0; key < entries.length; key++) {
var entry = entries[key];
if (entry.isFile){
var name = entry.name;
if(name == fileToUpload){
getAsText(entry.toURL());
formData.append('file', entry.toURL);
break;
}
}
}
}, errorHandler);
}, errorHandler);
}
function errorHandler(){
console.log('An error occured');
}
function getAsText(readFile) {
alert ("getting as text :" +readFile);
var reader = new FileReader();
// Read file into memory as UTF-16
reader.readAsText(readFile, "UTF-16");
// Handle progress, success, and errors
reader.onprogress = updateProgress;
reader.onload = loaded;
reader.onerror = errorHandler;
}
function loaded(evt) {
// Obtain the read file data
alert("loaded file");
var fileString = evt.target.result;
// Handle UTF-16 file dump
if(utils.regexp.isChinese(fileString)) {
//Chinese Characters + Name validation
}
else {
// run other charset test
}
// xhr.send(fileString)
}
var serverurl = "/fileserver/uploadFile?selpath="+fileToUpload;
var xhr = new XMLHttpRequest();
xhr.open('POST', serverurl);
xhr.onload = function () {
if (xhr.status === 200) {
console.log('all done: ' + xhr.status);
} else {
console.log('Something went terribly wrong...');
}
};
xhr.send(formData);
});
Now, I am trying to read the file as text (its a bad practice but wanted to find someway to make it work) but it doesn't throw any events. Can you please help me to find where I am going wrong ?

Multiple File Upload in codeigniter using HTML5 and XHR

I'm working on multifile upload using html5 and xhr, as you can see I'm sending requests in loop which is a bad
concept but I'm not able to upload files when I send it outside the loop and only the last file gets upoaded.
Where am I going wrong?
$('#uploadimg').on('click', function(e) {
var files = document.getElementById('files').files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/ajaxuploader/upload/uploadimg');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('all done: ' + xhr.status);
} else {
console.log('Something went terribly wrong...');
}
};
xhr.send(formData);
}
// now post a new XHR request
});
Codeigniter
public function uploadimg (){
$config['upload_path'] = FCPATH . 'uploads/' ;
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc';
$config['remove_spaces'] = 'TRUE';
$this -> load -> library('upload', $config);
//$this->upload->initialize($config);
foreach ($_FILES as $k => $f) :
$this -> upload -> do_upload($k);
endforeach;
//$this->index();
}
Its seems the first thing you should look at is your js for loop. ID's should be unique so I would rule that approach out.
I would maybe loop each input field, check to see if the attr type == file, then append that to your formData object.
var inpts = document.getElementsByTagName('input');
for(var i=0; i < inpts.length; i++)
{
if(inpts[i].getAttribute('type') == 'file')
{
formData.append('myFiles[]', inpts[i].files[0]);
}
}
On the server side I would look at your foreach loop, maybe a for loop might suffice.
for($i=0; $i < count($_FILES); $i++){
$this->upload->initialize(); //new initialization for each file
$this->upload->do_upload($_FILES[$i]);
continue;
};
Hi guys i figured out the problem codeigniter is working fine, the problem is in the jquery. this is the line causing the problem. "formData.append(files[i].name, files[i]);" Thanks for all for takign efforts to solve my issue
$('#uploadimg').on('click', function(e) {
//console.log(files);
// files = document.getElementById('files').files;
var formData = new FormData();
$(files).each(function(i) {
formData.append(files[i].name, files[i]);
})
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/ajaxuploader/upload/uploadimg');
xhr.onload = function(data) {
console.log(xhr.responseText);
};
xhr.send(formData);
});