Passing an array in PHP using POST from iOS

So, I looked at an infinite number of similar problems, but none of them answered what I was looking for and answered it fully, so I hope you can all help me.

I need to transfer the restaurantID array from iOS to a PHP file using POST, or somehow that will work well. I know about ASIHTTPRequest, but I'm looking for something inline, and he abandoned the developer. And finally, I do not want to pass them through the URL, because I do not know how many records there will be.

So here is what I got so far.

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:theURL]]; [request setHTTPMethod:@"POST"]; NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init]; [jsonDict setValue:restaurants forKey:@"restIDs"]; NSLog(@"JSON Dict: %@",jsonDict);//Checking my array here NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:kNilOptions error:nil]; NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"JSON String: %@",jsonString); //Checking my jsonString here... [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setValue:@"json" forHTTPHeaderField:@"Data-Type"]; [request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"]; [request setHTTPBody: jsonData]; NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSLog(@"Return DATA contains: %@", [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil]); NSArray *restMenuCount = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil]; 

So, for this purpose, I checked everything and everything looks good, but from the end of PHP it doesn’t even pick it up.

This is what my PHP file looks like:

 $restIDs = $_POST['restIDs']; echo $restIDs; //Checking to see if it even has anything......but nothing there for ($i = 0; $i < $restIDs.count; $i++) { $query = "SELECT * FROM `MenuItems` WHERE rest_id = '$restID'"; $result = mysqli_query($connect, $query); $number = mysqli_num_rows($result); $menuNumber[$i] = $number; } echo json_encode($menuNumber); 

So what am I doing wrong? Why am I not getting anything at my PHP end. And, most importantly, can someone explain to me how to send an array via POST. Since I feel that this is my real problem here, I do not understand this enough to solve the problem myself. I do not understand how you can put everything with iOS and pick it up on the PHP side.

I hope all this was clear enough, thanks in advance.

EDIT:
I tried passing the array as a string via the URL, then hacked it, fortunately, it worked ... but I'm just under the URL limit, so I would still like to find another solution. At least now I know that the rest of my code worked as expected.

+7
source share
2 answers

You seem to have a basic misunderstanding of how the $_POST variable is populated. Specifying a document type as JSON and casting a JSON string as the body of the message will not automatically populate this array. The body must be in a specific format. This usually means URL-encoded pairs, e.g. a=1&b=2&c=2&d=%2fg+y , etc. This somewhat limits the data you can send. In particular, an arbitrary JSON object is not possible in this sense if you want it to automatically appear in the $ _POST variable. There are several options here:

There is one option: instead of using $_POST use the message body directly. Use fopen("php://input") and parse this with the PHP JSON parser:

 $input = file_get_contents("php://input"); $obj = json_decode($input,true); $restIDs = $obj['restIDs']; 

If you went this route, you do not need to create an object with a field named restIDs . Instead, you can just serialize the array and use $obj as $restIDs

Option two, assuming your objects in restIDs are just strings, instead of passing data as a JSON object, format the body as intended for using PHP:

 NSMutableString *bodyStr = [NSMutableString string]; for (NSString *restID in restaurants) { [bodyStr appendFormat:@"restIDs[]=%@&",[restID stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; } NSData *body = [bodyStr dataUsingEncoding:NSUTF8StringEncoding]; [request setHTTPBody: body]; 

You should now have access to it using $_POST['restIDs'] , as you would expect.

+8
source

You made a mistake in the array. First you put it in a JSON string, and then you did not put the JSON string in post variables, but as the body of an HTML message. If you intend to use JSON to pass data to PHP through a POST message, you need to set it as a post variable. Then in PHP you read the variable and decode json to get the source variables. Here is an example of how I did it.

Sorry that I inserted Java code here first. That might make more sense.

 -(void) setPath: (NSString *) input { Path=input; } -(void) run { NSDictionary* jsonDictionary=[NSDictionary dictionaryWithObject: data1 forKey:@"data"]; NSString* jsonString = [jsonDictionary JSONRepresentation]; AFHTTPClient *httpClient=[[AFHTTPClient alloc] initWithBaseURL:url]; NSDictionary *params =[NSDictionary dictionaryWithObjectsAndKeys: apps,@"app", jsonString,@"smpdata",nil]; NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:Path parameters:params]; NSURLResponse *response = nil; NSError *error = nil; NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if (error) { NSLog(@"Error: %@",error); } else { id JSON = AFJSONDecode(data, &error); NSArray *dataarray=[JSON valueForKey:@"Data"]; status= [NSString stringWithFormat:@"%@",[JSON valueForKeyPath:@"Status"]]; NSLog(@"%@",status); returndata= dataarray; } } -(NSArray *) returndata { return returndata; } -(NSString *) status { return status; } @end 

Php

 <? $jsondata=$_POST['smpdata']; $data = json_decode($jsondata); ?> 
+1
source

All Articles