Reputation: 21
I'm looking to call a HTTP_POST from the iPhone SDK to a php file on my server. If I call this below:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://*****/api2/index.php"]];
[request setHTTPMethod:@"POST"];
[request addValue:@"postValues" forHTTPHeaderField:@"METHOD"];
//create data that will be sent in the post
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:@2 forKey:@"value1"];
[dictionary setValue:@"This was sent from ios to server" forKey:@"value2"];
//serialize the dictionary data as json
NSData *data = [[dictionary copy] JSONValue];
[request setHTTPBody:data]; //set the data as the post body
[request addValue:[NSString stringWithFormat:@"%d",data.length] forHTTPHeaderField:@"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(!connection){
NSLog(@"Connection Failed");
}
php code on server
if ($_SERVER['HTTP_METHOD'] == 'postValues'){
$body = $_POST;
$id;// value1 from dictionary
$name; // value2 from dictionary
}
Please help with $id and $name
Upvotes: 0
Views: 725
Reputation: 63462
First, the method of this request is POST
, not postValues
. All you did is add a header with the name METHOD
and the value postValues
, so, if you want to check for that, you need to look into the interface between whatever server you're using and PHP. For Apache, that's apache_request_headers()
.
Then, if you're setting the JSON object to be the body of the request, then you need to read the body to get to it. To do that, you need to read php://input
. So, your example becomes:
$body = json_decode(file_get_contents('php://input'), true);
$id = $body['value1'];// value1 from dictionary
$name = $body['value2']; // value2 from dictionary
Upvotes: 1
Reputation: 2218
You could either send the extra values in the query (and retrieve using $_GET) Or you could place the values in your json data.
Also the correct way of retrieving your json as an object is:
$bodyAsObject = json_decode( file_get_contents('php://input') );
Upvotes: 0