NSURLConnections and POST Problems

Discussion in 'iOS Programming' started by tyshcr, Aug 2, 2009.

  1. tyshcr macrumors newbie

    Joined:
    Aug 2, 2009
    #1
    I swear I had this working but now it doesn't. Seems totally straight
    forward but I have no idea why it is broken and I am about to scream.
    I made a simple web form:

    Code:
    <form method="POST" action="form2.php"> 
    <input type="text" name="name"> 
    <input type="submit"> 
    </form> 
    When you submit the form, it goes to form2.php and displays the
    "name" on the screen. Simple. It works in the browser.

    I am running this code in Xcode and it keeps NSLogging the code from
    the first page, but it should be submitting the form and showing me
    the output from the second page. I know I had this working before so
    I must be missing something so basic. Please help before I totally
    freakout.

    Code:
    NSString *post = @"name=Bob"; 
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO]; 
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; 
    
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; 
    [request setURL:[NSURL URLWithString:@"http://www.url.com/myform.php"]]; // changed the url 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPBody:postData]; 
    
    NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 
    NSLog(@"Succeeded! Received %d bytes of data",[urlData length]); 
    NSString *outputdata = [[NSString alloc] initWithData:urlData 
    encoding:NSASCIIStringEncoding]; 
    NSLog(outputdata);
     
  2. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    Do you not have to somewhere tell it that the data is related to the key "name"?
    Edit: OK, I see you've got name=Bob.
     
  3. tyshcr thread starter macrumors newbie

    Joined:
    Aug 2, 2009
    #3
    Yeah I have that in there. I really feel like I'm losing my mind, I've set the form up on a different server now and it's still doing the same thing.
     
  4. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #4
    A bit of Googling (which I assume you did before posting right?) indicates that you should probably change

    Code:
    NSString *post = @"name=Bob"; 
    
    to

    Code:
    NSString *post = @"&name=Bob"; 
    
     

Share This Page