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...
_POSTrendition, but I've provided an example of that in the latter part of my answer.NSDictionarythat I json-encode to capture all of these items I want to pass. The_POSTstructure feels like a web-browser-forms technology that doesn't lend itself this sort of computer-to-computer communication which JSON excels at (though it can be contorted to do so). Both techniques work, but I'd lean towards the consolidated JSON approach, not the mix of _POST and JSON approach. But use whichever works for you.