David P
David P

Reputation: 228

Post JSON to PHP Server

I want to send some data to a PHP file and all I get as response is {"status":"error","code":-1,"original_request":null}

My Objective C code:

NSMutableDictionary *questionDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:questionTitleString, @"question_title", questionBodyString, @"question_body", nil];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://myURL/post.php"]];
[request setHTTPMethod:@"POST"];


NSData *jsonData = [NSJSONSerialization dataWithJSONObject:questionDictionary options:kNilOptions error:nil];

[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];

NSURLConnection *postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

And now my PHP code:

    $postdata = file_get_contents("php://input");
$obj = json_decode($postdata);

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

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

The Problem is that the PHP receives a request from my app but does not receive the content I send to it.

Upvotes: 0

Views: 646

Answers (1)

Scott Arciszewski
Scott Arciszewski

Reputation: 34093

Why are you using json_decode() on php://input directly, when there are multiple parameters?

Try this:

// See the underlying structure of your data; attempt to decode the JSON:
var_dump($_POST);

$data = json_decode($_POST['question_title'], true);
var_dump($data);

$data = json_decode($_POST['question_body'], true);
var_dump($data);

PHP gives us the $_POST superglobal for a good reason. Also, json_decode($string, true) will return an associative array.

Upvotes: 3

Related Questions