I've been struggling with this for the last few days; I am trying to post an array to PHP. I can successfully send it, but it's not taken in with a post-variable (I am trying to use the variable key "json"... With this code, I receive the array in php:
Objective-C
NSError *error;
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects: @"one", @"two", @"three", nil] forKeys: [NSArray arrayWithObjects: @"a", @"b", @"c", nil]];
NSArray *jsonArray = [NSArray arrayWithObject:jsonDictionary];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonArray options:NSUTF8StringEncoding error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"somewebservicelocation/arrayTest.php?json="]];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:jsonData];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *response = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"response: %@",response);
PHP
$handle = fopen('php://input','r');
$array = fgets($handle);
echo $array;
if(isset($array))
{
echo "success";
}
else
{
echo "failure";
}
If I use this PHP, using _POST, I get no love:
$rawJsonData = $_POST['json'];
$array = json_decode(stripslashes($rawJsonData),true);
echo $array;
if(isset($array))
{
echo "success";
}
else
{
echo "failure";
}
...I've been at it for several days - all over Stack Overflow, and understand I need to include the variable and data in the body of the request, but I just can't get it to work. What am I doing wrong? How do you go about this differently? Save me from this headache...
On the PHP side, I've used something similar to your first example:
And then on the iOS side, I use:
I just tested this round trip, and it works fine.
If you are determined to use the
_POST
technique, what works for me is to set the the data to bejson=%@
, such as:And the PHP to parse it is much like you had: