How to fetch data from XMLHttpRequest to GridView QML - javascript

I am trying to show movies in a grid with 5 movies per row. I use a predefined movie list. I successfully fetched data from https://api.themoviedb.org/4/list/1.
Here is my code:
import QtQuick 2.15
import QtQuick.Window 2.15
Window {
width: 1920
height: 1080
visible: true
title: qsTr("Hello World")
Component.onCompleted: {
mojgrid.focus = true
}
function dobioResponseNapraviModel(response) {
console.log("dobioResponseNapraviModel", typeof response)
mojgrid.model=response
}
function request(){
console.log("BOK")
const xhr=new XMLHttpRequest()
const method="GET";
const url="http://api.themoviedb.org/4/list/1";
xhr.open(method, url, true);
xhr.setRequestHeader( "Authorization", 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI5YjBkOGVlMGQzODdiNjdhYTY0ZjAzZDllODM5MmViMyIsInN1YiI6IjU2MjlmNDBlYzNhMzY4MWI1ZTAwMTkxMyIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.UxgW0dUhS62m41KjqEf35RWfpw4ghCbnSmSq4bsB32o');
xhr.onreadystatechange=function(){
if(xhr.readyState===XMLHttpRequest.DONE){
var status=xhr.status;
if(status===0 || (status>=200 && status<400)){
//the request has been completed successfully
// console.log(xhr.responseText.results)
dobioResponseNapraviModel(JSON.parse(xhr.responseText).results)
}else{
console.log("There has been an error with the request", status, JSON.stringify(xhr.responseText))
}
}
}
xhr.send();
}
/* function request(url, callback) {
var xhr=new XMLHttpRequest();
xhr.open("GET", url, true)
xhr.onreadystatechange = function() {
if(xhr.readyState===4) {
callback(xhr.responseText)
}
}
xhr.open("GET", url)
xhr.setRequestHeader( "Authorization", 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI5YjBkOGVlMGQzODdiNjdhYTY0ZjAzZDllODM5MmViMyIsInN1YiI6IjU2MjlmNDBlYzNhMzY4MWI1ZTAwMTkxMyIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.UxgW0dUhS62m41KjqEf35RWfpw4ghCbnSmSq4bsB32o');
xhr.send()
}*/
GridView {
id:mojgrid
anchors.fill: parent
Keys.onUpPressed: {
request()
}
delegate: Rectangle{ id: rect; width:500;height: 400; color:'gray'
Image{ anchors.fill:parent
fillMode: Image.PreserveAspectFit
source:modelData.backdrop_path
}
Text{ text:modelData.original_title}
}
}
}
Here are the properties I need to show in GridView when I run the application:
But I get message that the image cannot be opened:
Does anybody have any idea what is wrong? Any help would be appreciated, thank you.

What you're missing is a model to store the data in. You are incorrectly trying to bind the GridView's model to a function. Instead, create an empty ListModel, and then when your request is complete, populate that model. The GridView will then update automatically when the model updates.
ListModel {
id: movieModel
}
GridView {
...
model: movieModel
}
Component.onCompleted: {
request()
}
function request() {
...
xhr.onreadystatechange=function(){
if(xhr.readyState===XMLHttpRequest.DONE){
var status=xhr.status;
if(status===0 || (status>=200 && status<400)){
// Parse response data and append it to your model
for (var i = 0; ...) {
movieModel.append( {...} )
}
}
}
}
}
UPDATE:
You've changed your question now. The reason you can't open those images is because you are not using the full path of the url. Your http request is apparently returning relative paths. So just prepend the base url to the image name.
source: "http://api.themoviedb.org/4/list/1" + modelData.backdrop_path

Related

JSON post request shows 405 not allowed error (using XMLHttpRequest())

here's my js code:
var myreq=new XMLHttpRequest();
myreq.open("GET","https://<username>.github.io/test/data/data.json",true);
myreq.onload =function(){
console.log(JSON.parse(myreq.response));
}
myreq.send();
const data={
"name": "jayant",
"job": "leader"
};
function here()
{
var myreq1=new XMLHttpRequest();
myreq1.onload = () => {
// print JSON response
if (myreq1.status >= 200 && myreq1.status < 300) {
// parse JSON
const response = JSON.parse(myreq1.responseText);
console.log(response);
}
};
myreq1.open("POST",'https://<username>.github.io/test/data/data.json');
myreq1.setRequestHeader('Content-Type', 'application/json');
myreq1.send(JSON.stringify(data));
}
Function here is called on a button click
and here's my JSON code:
[
{
"name1":"jayant",
"age":58,
"pass":"LetsLearnJson"
},
{
"name1":"jayant2",
"age":45,
"pass":"ok"
},
{
"name1":"jayant3",
"age":24,
"pass":"test"
},
{
"name1":"abcd",
"age":75,
"pass":"abcd"
}
]
I am getting this error when I try to post:
POST https://<username>.github.io/test/%22https://<username>.github.io/test/data/data.json%22 405
Please help. I have tried many things already available online but nothing seems to work
The 405 Method Not Allowed Error occurs when the web server is configured so that you cannot perform a specific action for a specific URL. It is an HTTP response status code that indicates that the request method is known to the server, but is not supported by the target resource.

XMLHttpRequest() Inside RequireJS Module

all. I'm working on a browser-based RPG for fun as well as programming education. I recently learned RequireJS—which is amazing—but during the revision of my code to AMD, I ran into an application breaking snag.
In my original implementation, I used an XMLHttpRequest() request to get the player's selected hero from my server via a GET call to a GetHero.php file. Asynchronous calls are great, but I struggling with the timing of the callback function and continuation of the game—i.e. the game continues before the callback, which results in an error.
My questions are:
1) How can I get the game to wait for the XMLHttpRequest() to return a value before moving to the next block of code?
2) When in my RequireJS AMD should I execute this function?
I tried turning off asynchronous in the .open() function, but since RequireJS uses similar calls, I don't think it works as it would in the synchronous execution of my code. I've also omitted the majority of the code to isolate the specific issue and heighten readability.
Thanks in advance to anyone willing to help me understand this!
main.js
require.config({
baseUrl: "assets/js",
deps: ["game"],
paths: {
jquery: "lib/jquery-3.3.1.min",
bootstrap: "lib/bootstrap.min",
game: "game",
hero: "models/hero",
getHero: "models/getHero",
stats: "models/stats",
heroClasses: "models/heroClasses"
},
shim: {
bootstrap: ["jquery"]
}
});
game.js
define(["hero", "bootstrap"], function (h) {
Hero = h;
console.log(Hero);
console.log(Hero.Stats.Get("str"));
console.log(Hero.Stats.GetInfo()); // <==== this fails
});
hero.js
define(["stats"], function (s) {
Stats = s;
return {
Stats: Stats
};
});
stats.js
define(["getHero"], function(myHero) {
var Info = myHero; // returns hero obj "{ name: "Hero", level: 1, etc..}"
var _HeroClasses = heroClasses;
var _GetInfo = function (arr) {
return Info;
};
return {
GetInfo: _GetInfo
};
});
getHero.js
define([], function () {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
return myObj;
}
};
xmlhttp.open("GET", "/game/assets/php/GetHero.php", false);
xmlhttp.send();
});
GetHero.php
<?php
// TODO create MYSQL call to load hero
echo '{ "id": 0, "name": "Ryan", "classId": 0, "level": 50, "exp": 251 }';
?>
Updated Code: (Working, but likely an ugly/poor solution)
-- game.js (Updated)
var a = new Promise(function (resolve, reject) {
document.getElementById("message").innerHTML = "Loading...";
Hero = h;
resolve(true);
});
a.then(function() {
Hero.Stats.GetInfo();
document.getElementById("message").innerHTML = "Ready";
})
.catch(function(err) {
console.error('There was an error 2!', err.statusText);
});
-- getHero.js (Updated)
define([], function () {
return function (method, url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
};
});

JSON file not loading properly [duplicate]

This question already has answers here:
Get JSON data from external URL and display it in a div as plain text
(7 answers)
How to get the response of XMLHttpRequest?
(4 answers)
Closed 7 years ago.
I want to read this JSON file, but the xmlhttp is returning empty.
This is the getJson() function that I am using. I am running this from my local machine.
var getJSON = function(dir) {
console.log(dir);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(xmlhttp);
}
xmlhttp.open("GET", dir, true);
xmlhttp.send();
};
Alberto,
Since you are using xmlHttp asynchronously, and assuming you want to save the response in a variable, you'll have to modify your getJSON function to accept a callback function and pass the result and/or an error to the callback. So getJSON should be something like this:
var getJSON = function(dir, callback) {
console.log(dir);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
if (xmlhttp.status == 200) {
console.log('request finished', xmlhttp);
// pass the response to the callback function
callback(null, xmlhttp.responseText);
} else {
// pass the error to the callback function
callback(xmlhttp.statusText);
}
}
}
xmlhttp.open("GET", dir, true);
xmlhttp.send();
}
To use the function, you'll want something like this:
var myReturnedJSON;
getJSON("http://gomashup.com/json.php?fds=geo/usa/zipcode/state/AL&jsoncallback=", function(error, data){
if(error) {
//handle the error
} else {
//no error, parse the data
myReturnedJSON = JSON.parse(data)
}
});
Now, the issue with this is that the source returns invalid JSON:
({
"result":[
{
"Longitude" : "-086.466833",
"Zipcode" : "35004",
"ZipClass" : "STANDARD",
"County" : "SAINT CLAIR",
"City" : "MOODY",
"State" : "AL",
"Latitude" : "+33.603543"
}
]}
)
For this to be valid, it should look like:
{
"result":[
{
"Longitude" : "-086.466833",
"Zipcode" : "35004",
"ZipClass" : "STANDARD",
"County" : "SAINT CLAIR",
"City" : "MOODY",
"State" : "AL",
"Latitude" : "+33.603543"
}
]}
The difference is in that the valid JSON is not wrapped in parentheses.
So, let's modify the callback function to strip out the first and last characters of the response:
function(error, data){
if(error) {
//handle the error
} else {
//no error, parse the data
myReturnedJSON = JSON.parse( data.substr(1, data.length - 2) );
}
}
I hope that helps!
- Oscar

Response in file upload with Jersey and ExtJS

I have a method which save an image file in the database as a BLOB file. The method works fine, but when I get the callback in ExtJS filefield component, it always goes through failure function and I don't know what I have to respond to go through success function, this is my code:
Server method:
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces({ MediaType.APPLICATION_JSON })
public ServiceResponse uploadFile(#QueryParam("id") Long iconId, FormDataMultiPart form) {
CatIcon icon;
if (iconId != null) {
icon = catIconBean.getOne(iconId);
} else {
icon = new CatIcon();
}
byte[] image = form.getField("iconBmp").getValueAs(byte[].class);
if (image.length != 0) {
MultivaluedMap<String, String> headers = form.getField("iconBmp").getHeaders();
String type = headers.getFirst("Content-type");
List<String> list = Arrays.asList("image/gif", "image/png", "image/jpg", "image/jpeg",
"image/x-icon", "image/bmp");
if (list.contains(type)) {
icon.setIconBmp(image);
icon.setType(type);
}
}
icon.setDescription(form.getField("description").getValue());
icon.setFileName(form.getField("fileName").getValue());
icon = catIconBean.saveIcon(icon);
ServiceResponse sr = new ServiceResponse();
sr.httpResponse = true;
return sr;
}
What I have to return in the code above?
Client:
uploadIcon : function(item, e, eOpts) {
var me = this;
var form = this.getDetail().getForm();
var valid = form.isValid();
if (!valid) {
return false;
}
var values = form.getValues();
if(values) {
form.submit({
url : myApplication.defaultHost() + 'icon/upload?id=' + values.id,
waitMsg : 'Uploading...',
success : function(form, action) {
me.onCompleteSaveOrDelete();
},
failure : function(form, action) {
me.onCompleteSaveOrDelete();
}
});
}
},
I write the same function, me.onCompleteSaveOrDelete(), in both callback functions to make it be called, that's the method which I want to be called in success.
Greetings.
UPDATE:
I did almost the same Alexander.Berg answered. The only difference was that I write #Produces({ MediaType.APPLICATION_JSON }) instead of #Produces({ MediaType.TEXT_HTML }), because I need Json Response. But when I debug in chrome and check the response, I get this:
In failure:
failure : function(form, action) {
me.onCompleteSaveOrDelete();
}
In action param, within responseText:
"{"data":"{\"success\":true}","httpResponse":true,"totalCount":0}"
But It's still going through failure...I think I'm very close, any help??
Greetings.
The fileupload in Extjs is more tricky, because it is using iframe and submit, not a real ajax request for uploading files.
Try this on Server method:
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.TEXT_HTML)
public String uploadFile(#QueryParam("id") Long iconId, FormDataMultiPart form) {
(...)
JSONObject json = new JSONObject();
json.put("success", true);
json.put("msg", "Success");
return json.toString();
}
this is because the upload accepts Content-Type text/html,
see Example at http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.form.field.File -> Example Usage -> Live Preview
Use Firefox browser with Firebug plugin and on Net tab the following URL -> http://docs.sencha.com/extjs/4.2.2/photo-upload.php
Response Headersview source
(...)
Content-Type text/html
(...)
Request Headersview source
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
(...)

Loading a script with the same variables than other and override

I`m using 2 different javascript files for two different languages, 1 file call lang.en.js that is in english and the other is lang.es.js, both files contains the same variables for example:
lang.es.js
var messages: {
settings: {
settings: "Opciones",
language: "Idioma"
}
}
lang.en.js
var messages: {
settings: {
settings: "Settings",
language: "Language"
}
}
So at first of my phonegap application i load only one of the files, i want to give an option to the user so he can change the language during the execution of the app, how can i override the other file or reload the entire app?.
Regards.
Use XHR to load the file as JSON and parse it. Something like this:
var messages = {};
var request = new XMLHttpRequest();
request.open("GET", "lang.en.json", true);
request.onreadystatechange = function(){
console.log("state = " + request.readyState);
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
messages = JSON.parse(request.responseText);
}
}
}
request.send();
and change you .js file to be a .json:
{
settings: {
settings: "Settings",
language: "Language"
}
}

Categories

Resources