9

I am trying the following code that executes after user enter data in fields (title, desc, city) and then clicks save.

- (IBAction)saveDataAction:(id)sender {
    NSString *lEventTitle = [NSString stringWithFormat:@"var=%@",eventTitle.text];
    NSString *lEventDesc = [NSString stringWithFormat:@"var=%@",eventDescription.text];
    NSString *lEventCity = [NSString stringWithFormat:@"var=%@",eventCity.text];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mydomain.com/ios/form.php"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    //this is hard coded based on your suggested values, obviously you'd probably need to make this more dynamic based on your application's specific data to send

    NSString *postString = [[NSString alloc] initWithFormat:@"title=%@&description=%@&city=%@", lEventTitle, lEventDesc, lEventCity];
    NSString *clearPost = [postString
                                     stringByReplacingOccurrencesOfString:@"var=" withString:@""];
    NSLog(@"%@", clearPost);
    [request setHTTPBody:[clearPost dataUsingEncoding:NSUTF8StringEncoding]];
    [request setValue:clearPost forHTTPHeaderField:@"Content-Length"];
    [NSURLConnection connectionWithRequest:request delegate:self];
    NSLog(@"%@", request);
}

When I NSLog the clearPost string (string containing the variables to be sent to server), it shows:

title=xmas&description=Celebration&city=NY

on the PHP end, I have simple as:

<?php
 $title = $_POST['title'];
 $description = $_POST['description'];
 $city = $_POST['city'];

 echo "Title: ". $title;
 echo "Description: ". $description;
 echo "City: ". $city;
?>

Just trying to get data on PHP so that later I can manipulate it. Right now when I execute the

domain.com/ios/form.php, it shows the title, description and city empty.

Sorry but I am very new to iOS and Objective-C.

3
  • 1. And what's the question? 2. You're adding the name= part twice to each POSTed variable: once in the first three lines of your method, then when creating postString. Commented Mar 23, 2013 at 16:44
  • Sorry questions was edited Commented Mar 23, 2013 at 16:52
  • IOS 9 introduced ATS and will not allow normal HTTP requests without whitelisting them. Credit: (stackoverflow.com/a/30732693/6042879) Commented Jul 29, 2016 at 20:21

3 Answers 3

15

Objective C

// Create your request string with parameter name as defined in PHP file
NSString *myRequestString = [NSString stringWithFormat:@"title=%@&description=%@&city=%@",eventTitle.text,eventDescription.text,eventCity.text];

// Create Data from request
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://www.youardomain.com/phpfilename.php"]];
// set Request Type
[request setHTTPMethod: @"POST"];
// Set content-type
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
// Set Request Body
[request setHTTPBody: myRequestData];
// Now send a request and get Response
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
// Log Response
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
NSLog(@"%@",response);

Swift

// Create your request string with parameter name as defined in PHP file
var myRequestString: String = "title=\(eventTitle.text!)&description=\(eventDescription.text!)&city=\(eventCity.text!)"
// Create Data from request
var myRequestData: NSData = NSData.dataWithBytes(myRequestString.UTF8String(), length: myRequestString.characters.count)
var request: NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: "http://www.youardomain.com/phpfilename.php")!)
// set Request Type
request.HTTPMethod = "POST"
// Set content-type
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
// Set Request Body
request.HTTPBody = myRequestData
// Now send a request and get Response
var returnData: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
// Log Response
var response: String = String(bytes: returnData.bytes(), length: returnData.characters.count, encoding: NSUTF8StringEncoding)
NSLog("%@", response)
Sign up to request clarification or add additional context in comments.

6 Comments

if you still can't get it right, feel free to ask..Thank you.
let me check on my php server. i will be back soon
Dear friend i have uploaded test php file on my server and tested updated code. its working with my side. you can test code on "dipen.5gbfree.com/test.php\" it will return xml response with your data.
the Swift example is still Objective-C here
@tyczj sorry for it, i have added code for swift as well.
|
2

NSURLConnection has been depracrated since IOS 9.0. Please use NSURLSesstion:

-(void) httpPostWithCustomDelegate
{
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

NSURL * url = [NSURL URLWithString:@"http://hayageek.com/examples/jquery/ajax-post/ajax-post.php"];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
NSString * params =@"name=Ravi&loc=India&age=31&submit=true";
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
                                    completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                      NSLog(@"Response:%@ %@\n", response, error);
                                      if(error == nil)
                                      {
                                          NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                          NSLog(@"Data = %@",text);
                                      }

                                  }];
[dataTask resume];

}

reference

Comments

0

Please try this:

[request setValue:[NSString stringWithFormat:@"%d",[clearPost length]]  forHTTPHeaderField:@"Content-Length"];

ok i am adding my request code: it may be helpful

   NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
                                        initWithURL:[NSURL
                                                     URLWithString:@"http://www.sth.com/action/verify.php"]];

        [request setHTTPMethod:@"POST"];
        [request setValue:[NSString stringWithFormat:@"%i",[sent length]]  forHTTPHeaderField:@"Content-length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:[sent dataUsingEncoding:NSASCIIStringEncoding]];

2 Comments

I edited and tried the following: after entering data I press Save. Then i go to chrome and visit domain.com/ios/form.php. Still nothing shows. Am I doing it right?
could you please write Content-Type instead content-type

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.