6

I want to post JSON data using HTTP request. I have read the official docs and I am working according to them. I am using the following code:

var xhrpost = Ti.Network.createHTTPClient();

    xhrpost.onload = function(){
        activityIndicator.hide();
        alert('Posted successfully');
        alert(JSON.stringify(this.responseText));
    }

    var posturl = 'http://qudova.com/api.php';

    xhrpost.open('POST', posturl);
    xhrpost.setRequestHeader("Content-Type", "application/json");
    xhrpost.setRequestHeader('charset','utf-8');
        var params = {
        ProjectID : picked_prj, 
        RoleID : picked_rol,
        FirstName: first.value,
        LastName: last.value,  
        Phone: phone.value,
        Email: email.value,
        City: city.value,
        State: stat_drp.getSelectedRow(0).title,
        Zip: zip.value,
        Notes: notes.value,
    };
    xhrpost.send(params);

If this is the correct way to post the JSON data. How would I check that data is posted ?? Will the url contain the posted data ??

I am getting null in the following alert that I added in the onload event.

alert(JSON.stringify(this.responseText));

I am working on Windows 7 , Testing on Android 4.2.2 .... Thanks in Advance.

nadeem gc
  • 484
  • 1
  • 8
  • 22

3 Answers3

9

When you set Content-Type to json, you need to stringify the input.

var xhr = Ti.Network.createHTTPClient();

xhr.open('POST', url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader('charset','utf-8');
xhr.send(JSON.stringify({
    prop: 'string',
    data: {
        embeddedProp: 1234
    }
}));

Tried this out and it worked, wasn't able to find it in the documentation.

joewright
  • 325
  • 3
  • 7
  • I've been struggling with the same problem, thank you for your answer. I don't undertand how come stuff like this is not documented... – damian May 23 '14 at 18:17
1

Just use JSON.stringify()

JSON.stringify({ ProjectID : picked_prj, RoleID : picked_rol, FirstName: first.value, LastName: last.value,
Phone: phone.value, Email: email.value, City: city.value, State: stat_drp.getSelectedRow(0).title, Zip: zip.value, Notes: notes.value, })

See docs updated.

andresmafra
  • 491
  • 7
  • 19
0

use JSON.parse

var params =JSON.parse({
        ProjectID : picked_prj, 
        RoleID : picked_rol,
        FirstName: first.value,
        LastName: last.value,  
        Phone: phone.value,
        Email: email.value,
        City: city.value,
        State: stat_drp.getSelectedRow(0).title,
        Zip: zip.value,
        Notes: notes.value,
    })

and send it . It may work...

sundar nataraj
  • 8,524
  • 2
  • 34
  • 46