0
votes

I have tried sending POST data to a php file with asynch and synch NSURLConnection and ASIHTTPRequest but both refuse to actually echo anything in $_POST. My s.php file looks like so:

<?php
echo 'Hi There';
echo $_POST['fname'];
foreach ($_POST as $i => $value) {
     echo($i);
}
?>

My ASIHTTRequest is:

NSURL *url = [[NSURL alloc] initWithString:@"http://server.com/s.php"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"Ben" forKey:@"fname"];
[request setDelegate:self];
[request setDidFinishSelector:@selector(requestFinished:)];
[request startAsynchronous];

Which only prints the Hi There line when it comes back to requestFinished.

Edit: By using ASIFormDataRequest, I am pretty sure request is set to POST already, at least there doesn't seem to be a way to set it manually. When I tried NSURLConnection I used:

NSURL *url = [NSURL URLWithString:@"http://server.com/s.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[[NSString stringWithFormat:@"fname=carl"] dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *response;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *stringResponse = [[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding]; 
NSLog(@"%@",stringResponse);

And still only getting the Hi There line, and also getting normal replies when I use an html form.

2
add this line in your code; [request setHTTPMethod:@"POST"]; - Mobile Developer iOS Android
Its working fine user768531.no problem in the above code.Might be not the code issue. - Priyanka
@impossiblepriya Might it be something on the server side? - apchait
is "ischool.berkeley.edu/~ariel/server/s2.php" where your php file is?? - Priyanka
@impossiblepriya Yes, the php file that I posted up top is at that address. - apchait

2 Answers

0
votes

I think you have to set some http headers also before posting data, then only php can recognize that the page requested using post method

try with this line

[request setHTTPMethod: @"POST"];

-1
votes

Try it.

    NSURL *url = [[NSURL alloc] initWithString:@"http://server.com/s.php"];
   ASIHTTPRequest *Asi_request = [ASIHTTPRequest requestWithURL:url];
    [request setPostValue:@"Ben" forKey:@"fname"];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestFinished:)];
    [request startAsynchronous];
[request setHTTPMethod: @"POST"];

//if this will not work then you should generate queue in appledelegate file see:link

may this help you.