0

I am trying to post a string to the server. I have these codes below that I know works but only after I added at least one EMPTY entry into the database (it will show up in the database still, as basically, like this: ""). I have no idea why the NSURLRequest has such strange behavior. Anyone can tell me why?

NSMutableString *postString = [NSMutableString stringWithString:@"http://website.com/post.php"];
[postString appendString:[NSString stringWithFormat:@"?loc=%@",locationBox.text]];

NSMutableURLRequest* request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:postString] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:3];    
[request setHTTPMethod:@"POST"];

postConnection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
minjiera
  • 336
  • 3
  • 16
  • Are you getting response at server. Means Are you getting string at server using this method?? – iCreative Jul 18 '12 at 21:43
  • What, exactly, are you trying to do? You've never set the body of the POST request, so you're just basically posting nothing. – Jason Coco Jul 18 '12 at 21:50
  • @iCreative, I have set up the delegate methods, and have them print some words. The first or the second try is always "Failed with error" & "Unable to fetch respond". But later after I somehow manage to add some empty entry, then it will say, "Successfully received N byte of data". – minjiera Jul 19 '12 at 06:32
  • @JasonCoco Thanks for your reply. I let user type the text in to "locationBox" (a textfield), then append it to the "postString". It does work, just not always...:( I learnt this method from a youtube video [link] (youtube.com/watch?v=IQcLngIDf9k&feature=relmfu) but I didn't see simliar codes elsewhere. If there are other more reliable methods (as you said, I never set the request body) can you explain how to do it on the server php file, becoz that's the part that never gets explain. – minjiera Jul 19 '12 at 06:42

1 Answers1

1

I've had to implement a code to do something like you're trying to do and I've approched succesfully the situation in the following way. Here's the code (modified to use your url) and it works always. Basically the difference with you code is the explicit set of ContentType and HTTPHeader.

NSMutableString *postString = [NSMutableString stringWithString:@"http://website.com/post.php"];
[postString appendString:[NSString stringWithFormat:@"?loc=%@",locationBox.text]];
NSURL *url = [[[NSURL alloc] initWithString:postString] autorelease];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];

Hope you can solve your problem.