1

I am sending array to php server with the following code but at php side they are not getting any value.I am sending array as json string.

- (void)postArray {
//Create the URL request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://test.com./t.php"]];
    NSMutableArray *array = [[NSMutableArray alloc] init];
    [array addObject:@"one"];
    [array addObject:@"Two"];
    [array addObject:@"three"];
    [array addObject:@"four"];
    [request setHTTPMethod:@"POST"];
   // NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:array,@"comment", nil];
    SBJSON *parser =[[SBJSON alloc] init];
   // NSString *jsonString = [parser stringWithObject:dict];
    NSString *jsonString = [parser stringWithObject:array];
    NSLog(@"Str %@",jsonString);
    [request setValue:@"application/x-www-form-urlencoded"
   forHTTPHeaderField:@"Content-Type"];
    [request setValue:jsonString forHTTPHeaderField:@"comment"];
   [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]  completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

        NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
        NSInteger statusCode = [HTTPResponse statusCode];


        if (statusCode==200) {


            //Request goes in success
            NSError* error;
            NSMutableDictionary* json = [NSJSONSerialization
                                         JSONObjectWithData:data //1
                                         options:kNilOptions
                                         error:&error];
            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];


            NSLog(@"Json for post array ----------%@",str);

        }else{

            ///request is get failed

            NSLog(@"Error Description %@",[error description]);
        }
    }];

    [request release];


}

And Output at php is

<pre><br>This is response getting from the Iphone<br>First<br><br>end First<br>Second receive json response and decode the json response<br><br>nullThird Breaking from commaArray ( [0] => )

Here is php code

<?php

echo "<pre>";
echo "<br>";
//echo "Testing array";
$totalitem=$_POST['total'];
echo "This is response getting from the Iphone";
echo "<br>";
echo "First";
echo $jsonarray1=$_POST['comment'];
echo "<br>";
print_r($jsonarray1);
echo "<br>";
echo "end First";
echo "<br>";



echo "Second receive json response and decode the json response";
echo "<br>";
echo $comment=$_POST['comment'];
echo "<br>";
$jsonarray=json_decode($comment);
echo json_encode($jsonarray);


echo "Third Breaking from comma";
echo "<br>";
$allval=explode(',',$jsonarray1);
print_r($allval);

?>

Please Help

DaveRandom
  • 87,921
  • 11
  • 154
  • 174
iProgrammer
  • 3,099
  • 3
  • 33
  • 59

2 Answers2

0

Try following Code may be helpful for you. Try to create a NSMutableDictionary and Then POST.

        NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
        [dictionnary setObject:@"First" forKey:@"First"];


        NSError *error = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
                                                           options:kNilOptions
                                                             error:&error];   

        NSString *urlString =@"Your URL";

        NSURL *url = [NSURL URLWithString:urlString];
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setHTTPMethod:@"POST"];

        [request setHTTPBody:jsonData];
        NSURLResponse *response = NULL;
        NSError *requestError = NULL;
        NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
        NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ;
         NSLog(@"%@", responseString);
Siba Prasad Hota
  • 4,779
  • 1
  • 20
  • 40
0

This is a neat and easy way to do it. In your xcode implementation file create a method like this:

NB: Remember to customize it to your needs. The important bit is passing the request array named "requestArray_". Change the url bit http://localhost/test/index.php with your desired url

-(NSArray *) setRequestWithRequestArray:(NSArray *)requestArray_{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestArray_
                                                       options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    NSString *post = [NSString stringWithFormat:@"requestArray=%@", jsonString];

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];

    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://localhost/test/index.php"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    NSURLResponse *response;
    NSError *errors = nil;

    NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:POSTReply options:0 error:&errors];

    NSLog(@"request %@", request);
    NSLog(@"jsonArray%@",jsonArray);

    return jsonArray;
}

And in your php create a test method like this:

$Array = $_POST["requestArray"];
function testMethod($Array){
        $get_result = array();
        $get_result = json_decode($Array);

        foreach($get_result as $key1 => $value){
            $result = array(
                    $key1 => $value, 
                    $key1 => $value, 
                    $key1 => $value, 
                    $key1 => $value
            );
        }

        sendResponse(200, json_encode($result));
            return true;
    }
Daniel
  • 598
  • 1
  • 6
  • 23