I have an iPhone app which gets a response from a php file. This response generates an html file where the body contains a json object. How do I retrieve this JSON object ?
$query = "SELECT username FROM userData WHERE username = '$username'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
sendResponse(200, json_encode('SUCCESS Notification'));
} else {
$query = "INSERT INTO userData (username,password,email,signup_date) VALUES ('$username','$password','$email','$date')";
$result=mysql_query($query,$connection) or die (mysql_error()." Kann Tabelle der Datenbank nicht lesen!");
}
function sendResponse ($status = 200, $body ='', $content_type = 'application/json'){
$status_header = 'HTTP/1.1 ' . $status . ' ' . 'OK';
header($status_header);
header('Content-type:' . $content_type);
echo $body;
}
This is what happens in my iphone app:
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&error];
NSDictionary *jsonDictionaryResponse =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"json response = %@", jsonDictionaryResponse);
As far as I can see, you don’t add HTML-Tags around your JSON enocded string. So you could just parse the whole response body. I recommend you using jQuery (if your don’t do already) or the JSON library.
But please note, that you should chage your MIME-Type to
application/jsonwhen sending JSON data and that it doesn’t make sense tojson_encodea string.