0

I have a ruby server running which returns a JSON in the following format :-

{"id":7,"user_name":"logix_5","first_name":"sadf","last_name":"sdgdg","email":"lo@hi.com","password":"l5","phone_number":"123876","user_type":"Manager","job_title":"dfhst","created_at":"2016-05-24T02:52:23.000Z","updated_at":"2016-05-24T06:52:28.000Z"}

when we go to the link http://192.168.68.211:3000/vlapi/login?user_name=logix_5&password=l5

I want to be able to access the JSON data from the website and extract data from it using pure JS. I Have tried the following code :-

 var res =  new XMLHttpRequest();
 var url = "http://128.199.68.211:3000/vlapi/login?  user_name=logix_5&password=l5"   
 res.open("GET",url,true)
 res.send()
 document.write("Working")  
 document.write(res.responseText)

I have tried the code given in How to get JSON from URL in Javascript? and few other similar questions but the "res.responseText" is not returning anything. What have i missed in the code.

Note : The code has to be integrated along with QML

Edit: I tried to modify the code given in https://stackoverflow.com/a/35970894/5608864 to

getJSON("http://192.168.68.211:3000/vlapi/login?user_name=logix_5&password=l5",
    function(err, data) {
      if (err != null) {
        alert("Something went wrong: " + err);
      } else {
        alert("Your query count: " + data.query.id);
      }
    });

Still nothing is being printed in the console.

Edit I used https://www.hurl.it/ to make a GET request to "http://192.168.68.211:3000/vlapi/login?user_name=logix_5&password=l5"

it returns some thing like this as response

Cache-Control: max-age=0, private, must-revalidate
Connection: Keep-Alive
Content-Length: 252
Content-Type: application/json; charset=utf-8
Date: Tue, 24 May 2016 11:07:15 GMT
Etag: W/"30fc28a52d407ac1074eb62d7da0b5d0"
Server: WEBrick/1.3.1 (Ruby/2.3.1/2016-04-26)
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: c7a0d898-da00-4325-99ff-3164d9e03cf4
X-Runtime: 0.017905
X-Xss-Protection: 1; mode=block
BODY view raw

{
"id": 7,
"user_name": "logix_5",
"first_name": "sadf",
"last_name": "sdgdg",
"email": "lo@hi.com",
"password": "l5",
"phone_number": "123876",
"user_type": "Manager",
"job_title": "dfhst",
"created_at": "2016-05-24T02:52:23.000Z",
"updated_at": "2016-05-24T06:52:28.000Z"
}

Is this any helpful to debug the problem. Can you please leave a code snippet to get the JSON.

Community
  • 1
  • 1
ANIRUDH NJ
  • 59
  • 2
  • 8
  • Your request is async, so you need to use `res.onreadystatechange` to check for the response: [How to get the response of XMLHttpRequest?](http://stackoverflow.com/questions/3038901/how-to-get-the-response-of-xmlhttprequest) – t.niese May 24 '16 at 10:36
  • You say you've looked at the other question but your code doesn't look like the [code in the other question](http://stackoverflow.com/a/35970894/542251)??! Why? – Liam May 24 '16 at 10:36
  • 1
    Possible duplicate of [How to get JSON from URL in Javascript?](http://stackoverflow.com/questions/12460378/how-to-get-json-from-url-in-javascript) – Liam May 24 '16 at 10:37
  • @Liam i tried the code given in the link but still was not able to correct the problem – ANIRUDH NJ May 24 '16 at 11:16

5 Answers5

1

Ajax requests are asynchronous, so res.responseText is not set when it's called. You have to use an event handler:

res.addEventListener('load', function () {
    console.log(res.responseText)
})
Daniel Diekmeier
  • 3,401
  • 18
  • 33
0

You have spaces in url.

Change this line:

var url = "http://128.199.68.211:3000/vlapi/login? user_name=logix_5&password=l5"

To:

 var url = "http://128.199.68.211:3000/vlapi/login?user_name=logix_5&password=l5" 
Ygalbel
  • 5,214
  • 1
  • 24
  • 32
0

First problem I see with your code is remove the leading spaces before user_name parameter.

Then I would convert your answer in an object, when the answer is back:

res.addEventListener('load', function () {
    console.log(res.responseText);
    obj = JSON.parse(res.responseText);
})
  • @Liam give me a break, it is not a race. –  May 24 '16 at 10:41
  • If you put an incorrect answer it will get downvoted. That's how this site works. You should prob read [How do I write a good answer?](http://stackoverflow.com/help/how-to-answer) – Liam May 24 '16 at 10:42
0

Both the URLs which you have mentioned in your questions are different even though both doesn't return anything accept an error message site can not be reached which occurs in case if your server from where you are trying to get the response is unavailable try turning it on or maybe some programmatical error on server side. It should work

VishAl
  • 388
  • 3
  • 17
0

Please ensure first, that the json response is valid. You can use http://jsonlint.com/ for that.

For QML I usually use for clean code and re-usability a set of three functions: a helper, a caller and a callback function.

In this short example, I used the yahoo link from the other SO question above. By clicking at the "Hello World", the caller jsonYahoo runs and in jsonYahooCallback the response contains the answer as a string, while the result contains the parsed json.

Result:

before in qm after in qml

Code:

import QtQuick 2.3
import QtQuick.Window 2.2

Window {
    visible: true

    MouseArea {
        anchors.fill: parent
        onClicked: {
            jsonYahoo()
        }
    }

    Text {
        id: hello
        text: qsTr("Hello World")
        anchors.centerIn: parent
    }

    function jsonYahoo() {
        var url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback"
        var data = ''
        request(url, data, jsonYahooCallback)
    }

    function jsonYahooCallback(success, response) {
        var result = JSON.parse(response)
        if (success === true) {
            console.log(response)
            hello.text = result.query.created
        } else {
            console.log("request failed")
        }
    }

    function request(url, data, callback) {
        var xhr = new XMLHttpRequest()
        xhr.open('POST', url, true)
        xhr.setRequestHeader('Content-Type', 'application/json')
        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status && xhr.status === 200) {
                    callback(true, xhr.responseText)
                } else {
                    callback(false, xhr.responseText)
                }
            }
        }
        xhr.send(data)
    }
}
admirableadmin
  • 2,669
  • 1
  • 24
  • 41