0

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.

2
  • 1
    shouldn't it be is_array($obj) instead of is_array($post_data) ? And also "original_request" => $obj Commented Feb 17, 2014 at 18:18
  • 2
    also I guess the json_decode needs second true parameter in order by to decode to array Commented Feb 17, 2014 at 18:20

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.