Search code examples
javascriptjavajsontitaniumappcelerator

HTTPClient call is not returning correct JSON data in Appcelerator Titanium app


Everytime i try to get my info from a JSON i get an error.

function buscar(e){
    var url = 'https://www.dotscancun.com/createjson.php?id=100001';
    var xhr = Ti.Network.HTTPClient({
    onerror: function(e){
        Ti.API.info(this.responseText);
        Ti.API.info(this.status);
        Ti.API.info(e.error);
        },
        timeout: 5000
    });   
    xhr.open('GET',url);
    xhr.send();
    xhr.onload = function(){ 
        var json = JSON.parse(this.responseText); 
        alert(json);
    };
};

This is the Code.

The error is:

[LiveView] Client connected
[ERROR] :  TiHTTPClient: (TiHttpClient-8) [1340,1340] HTTP Error (java.io.IOException): 404 : Not Found
[ERROR] :  TiHTTPClient: java.io.IOException: 404 : Not Found
[ERROR] :  TiHTTPClient:    at ti.modules.titanium.network.TiHTTPClient$ClientRunnable.run(TiHTTPClient.java:1217)
[ERROR] :  TiHTTPClient:    at java.lang.Thread.run(Thread.java:818)

Error 404 it means that the website didnt exist, but if you copy the url it works, what is wrong?


Solution

  • The error message you have posted in your question is not related to your JSON query. Rather it's related to your Android device log output. So you can simply ignore that call.

    You are coding it wrong because:

    • You are not creating a proper HTTPClient object. You are using Ti.Network.HTTPClient instead of Ti.Network.createHTTPClient
    • onload method should be defined before open() call.

    Here's the correct code for your question:

    function buscar(e){
        var url = 'https://www.dotscancun.com/createjson.php?id=100001';
    
        var xhr = Ti.Network.createHTTPClient({
            onerror: function(e){
                Ti.API.info(this.responseText);
                Ti.API.info(this.status);
                Ti.API.info(e.error);
            },
    
            timeout: 5000,
    
            onload : function(){
                alert(this.responseText);
    
                // parse it for further use
                var tempJSON = JSON.parse(this.responseText);
            }
        });
    
        xhr.open('GET',url);
        xhr.send();
    }