PaulLian
PaulLian

Reputation: 307

Send json data to php returning null

I'm trying to send an array of data (dictionaries in side) through json format to a php file on the server side, so that later on the data will be stored into a MySQL database. However, it looks like that the data object received by php is always null.

Here are the Objective-C lines:

NSURL *url = [NSURL URLWithString:@"http://myaddress/upload.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:self.sentData];

NSError *error = nil;
NSURLResponse *response = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

if (error) NSLog(@"%s: NSURLConnection error: %@", __FUNCTION__, error);        
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"responseString: %@",responseString);

Here are the php lines:

<?php

$json_data=file_get_contents('php://input');
$post_data = json_decode($json_data);

if (is_array($post_data))
$response = array("status" => "ok", "code" => 0, "original request" => $post_data);
else
$response = array("status" => "error", "code" => -1, "original_request" => $post_data);

$processed = json_encode($response);
echo $processed;

?>

The debugging message on Xcode is as below:

2015-07-19 17:34:35.900 PhpPostTest[1531:557248] responseString: {"status":"error","code":-1,"original_request":null}

Looks like the connection is ok, but the response string indicates that the data received by php side is null. Can anybody suggest what's potential issue here?

Upvotes: 1

Views: 1205

Answers (2)

Edgar
Edgar

Reputation: 238

By default json_decode would not return the decoded string as an array. If you want it tu return an array you must specify it by setting the second parameter of the function to true.

json_decode($json_data, true);

Otherwise in this case json_decode could return a stdClass object. And of course the is_array check will evaluate to false.

Also make sure the data passed to the json_decode function is encoded as UTF-8. And it represents a valid json string, otherwise you'll get null as a result.

Upvotes: 1

Hedam
Hedam

Reputation: 2249

json_decode() will return NULL whenever the JSON you are trying to decode is malformed.

You can run echo $json_data; to verify that your JSON is actually JSON.

Upvotes: 2

Related Questions