I’ve never used ASIHTTPRequest before, nor have I dealt with posting anything from an iPhone to a web service before. I’d like to eventually save the posted variables to a database, but I am unsure if they are being posted properly at this time. When I run the following script in Xcode, I see the correct html code with inserted variables logged in the debug window. My concern is that I don’t see the same thing when I access the page in the browser. My guess is this is to be expected, but I’m not completely sure. Here is what I am doing:
string1 = [[NSString alloc] initWithString:@"Did this"];
string2 = [[NSString alloc] initWithString:@"come through?"];
NSString *urlString = @"http://www.myurl.com/post_test.php";
NSURL *url = [NSURL URLWithString: urlString];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:string1 forKey:@"String1"];
[request setPostValue:string2 forKey:@"String2"];
NSString *response = nil;
[request startSynchronous];
NSError *error = [request error];
if (!error) {
response = [request responseString];
NSLog(@"Response GOOD: %@", response);
}
else {
NSLog(@"Response BAD: %@", error);
}
This prints the html code from the web page with the uploaded variables correctly, but if I go to the page in my browser the php variables are null. Here is the small php script:
<?php
$received = array();
$received = $_POST;
$print_received = print_r($received, TRUE);
echo "<pre>$print_received</pre>";
$var1 = $received['String1'];
$var2 = $received['String2'];
echo "The message received was: $var1 $var2</br>";
?>
I haven’t added the mysql connection code yet because I want to make sure this posting business is successful first.
If you’re getting the correct response from the code that you posted, it means your code is working. What is probably happening is that you’re not using
POSTwhen testing with your browser.Check to make sure
$_POST[]actually contains data first. If not, presumably you’d want to output a meaningful error. It looks like you’re just building a sandbox of sorts to play and get familiar with ASIHTTPRequest, however if your goals get more complex (and your code becomes public facing) you’ll want to spend some time reading up on how to sanitize and validatePOST/GETvariables before using them.