posting JSON object to a URL

You must Login before you can answer or comment on any questions.

I was able to post a JSON object to a URL before upgrading to 1.7.1. After the upgrade, I can not do that any more. I tried to send JSON object with and without stringifying. It doesn't seem to work at all. Any ideas what could be the problem.

Here is a helper function which does the post:

(function (){
 
    tt.services.login = function (params) {
        Ti.App.fireEvent('app:show.loader');
        var method = 'POST';
        var url = 'http://'+appModel.serverName+':'+appModel.port+'/login';
        payload = (params) ? JSON.stringify(params) : '';
        //payload = (params) ? params : '';
        Ti.API.info('sending registration with params '+payload);
 
        var auth = 0;
        tt.services.helper(url, method, auth, payload, function(response){
           Ti.App.fireEvent("st.app:loginSuccessful", response);
        },function(xhr,error) {
            Ti.App.fireEvent("st.app:loginError", error);
        });
    };
 
    tt.services.helper = function(url, method, auth, params, successCallback, errCallback){
        var xhr = Ti.Network.createHTTPClient();
        xhr.setTimeout(60000);
        xhr.onerror = function(e) {
            errCallback(this,e);
        };
        xhr.onload = function() {
            var response= JSON.parse(this.responseText);
            successCallback(response);
        };
        // open the client
        xhr.open(method, url);
        xhr.setRequestHeader("Content-Type","application/json");
        xhr.setRequestHeader("Accept", "application/json");
        if (auth == 1){
          xhr.setRequestHeader('Authorization','Basic '+Ti.Utils.base64encode(tt.model.username + ":" + tt.model.password));
        }
        // send the data
        xhr.send(params);   
    };
 
})();

— asked 2 years ago by Mahantesh Nashi
6 Comments
  • What exactly is params?

    — commented 2 years ago by Henning Glatter-Gotz

  • It is a JSON object which I am trying to post to a URL.

    — commented 2 years ago by Mahantesh Nashi

  • Does the example in the answer below help? If not, can you post the code that creates 'params'?

    — commented 2 years ago by Henning Glatter-Gotz

  • Show 3 more comments

1 Answer

This works for me in 1.6.x and 1.7.x (please note that I no longer use 1.7.x because of stability issues - it crashes my app randomly)

...
 
var httpParams = {
    "param1":value1,
    "param2":value2
}
 
...
 
httpClient.open('POST', url, false);
httpClient.send(httpParams);

Your Answer

Think you can help? Login to answer this question!