Learn what Felgo offers to help your business succeed. Start your free evaluation today! Felgo for Your Business

XMLHttpRequest Element

XMLHttpRequest Element

Contained in the QML Global Object (online link here), an asynchronous web request can be initiated. The result can then be parsed as a JSON or XML result. Here is an example of sending a JSON-encoded JS object with a POST request:

 function saveLevelRemote() {
   var httpRequest = new XMLHttpRequest();

   // levelData can be an arbitrary JavaScript object
   var postData = JSON.stringify(levelData);

   httpRequest.open("POST", url, true);
   httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   httpRequest.onreadystatechange = function() {
       if (httpRequest.readyState == httpRequest.DONE) {
           console.debug("the level has been saved on the web server");

           var serverResponse = httpRequest.responseText;
           // the response from server is needed to get the created id, which was created from the server!
           // only when currentLevelId is set, the existing level can be updated!

           console.debug("saveLevelRemote() httpRequest result:", serverResponse, ", request: ", url, "postData:", postData);
           if(!serverResponse) {

               nativeUtils.displayMessageBox("Failed to save level to server");
               return;
           }

           nativeUtils.displayMessageBox("Your level has been saved");

           var result = JSON.parse(serverResponse);
           // the result has the following format: {"levelId":12345}
           var currentLevelId = result.levelId;
           console.debug("the read id from the saved level is", currentLevelId);

       }
   }
   httpRequest.send(postData);
 }

And here is an example for parsing a GET request:

 function getAllLevelsRemote() {
       var httpRequest = new XMLHttpRequest();
       // the 3rd parameter is the asynchronous flag, see here: http://www.w3.org/TR/XMLHttpRequest/#the-open-method
       httpRequest.open("GET", serverUrl, true);
       httpRequest.onreadystatechange = function() {
           if (httpRequest.readyState == httpRequest.DONE) {

               var serverResponse = httpRequest.responseText;
               console.debug("getAllLevelsRemote() httpRequest result:", serverResponse);

               if(!serverResponse) {
                   nativeUtils.displayMessageBox("Failed to load levels from server");
                   return;
               }

               // example result: [{"lastModificationTime":"2012-05-06T23:06:41+02:00","levelName":"Test","levelId":1}]
               var result = JSON.parse(serverResponse);
           }
       }
 }
Qt_Technology_Partner_RGB_475 Qt_Service_Partner_RGB_475_padded