Appcelerator Titanium HTTPClient Post to PHP - Working Example


Zero Gravity Programming







Appcelerator/Titanium's HTTPClient is flexible and powerful, but I had a bugger of a time figuring out how to do a basic POST to a PHP page on a remote server from my iPad app. This seems like it would be a mainstream type of thing to do--not anything fancy, tricky, or unorthodox. Yet I couldn't find ANY working examples of how to do this. Not on Appcelerator's forums or docs, and not on any of the dozens of google searches I did.

Let's be clear: I found lots of code samples on how to use HTTPClient, but 99% of them were GETs instead of POSTs. Of the 1%, 99% of those used JSON. Fine, so I tried using JSON, but my form receivers in php ($_POST) did not correctly process this data. And besides, I don't need JSON, I just wanted a simple post. So after spending way too much time on this, I figured it out:
function transmit(){
    var xhr=Titanium.Network.createHTTPClient();    
    xhr.open("POST", serverURL);
 
    xhr.onload = function(){
     //alert("responseText: " + this.responseText);
     if(this.status == '200'){
        alert('Transmission successful!');
        //if(this.readyState == 4){
        //  alert('Response = ' + response);
        //}else{
        //  alert('HTTP Ready State != 4');
        //}           
     }else{
        alert('Transmission failed. Try again later. ' + this.status + " " + this.response);
     }              
    };
 
    xhr.onerror = function(e){alert('Transmission error: ' + e.error);};
 
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    var params = {
        Param1 : 'Jack',
        Param2 : 'Bauer'
    };
 
    xhr.send(params);
}


And the receiving PHP code is super easy:
$param1 = $_POST['Param1'];
$param2 = $_POST['Param2'];


If you need any custom programming done, including iPad, iPhone, Android, or traditional web development, please contact us.
Zero Gravity Programming