Reputation: 1435
Im new to IOS and I am trying to obtain data from a php file in Json format. The way that I would like to obtain this data is by sending information from the app to the php sql query. I have tried the following:
IOS:
NSString *myRequestString = [NSString stringWithFormat:@"%@%@",@"ID",newsID];
NSLog(myRequestString);
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:@"http://domain.com/file.php"]];
[request setHTTPMethod: @"REQUEST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPBody: myRequestData];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //Or async request
NSError *error=nil;
NSArray *results = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:&error];
PHP:
$query="SELECT news_description FROM newsTable WHERE newsID = ".$_REQUEST['ID'].";
$result=mysql_query($query);
while($row=mysql_fetch_assoc($result))
$output[]=$row;
print(json_encode($output));
I have researched some ideas but unfortunately it does not send the information to the php file. I have tried changing $_REQUEST to $_POST, also I created a variable in my php file to store $_POST but no luck. Any suggestions? Please help! Thank you!
Upvotes: 0
Views: 228
Reputation: 7560
Try JWURLConnection on GitHub. If you prefer to write your own code, you can look at the source code.
EDIT To give you more information: You are creating a plain HTTP request in your code. And the HTTP body your are sending is absolutely not HTTP compliant. The x-www-form-urlencoded
content type has to follow very specific rules defined by RFC.
As I looked at your code again I saw an issue. You are missing an equals sign:
[NSString stringWithFormat:@"%@=%@",@"ID",newsID]
^^^
I would recommend to read the RFC specifications or, as stated before, follow the code implemented in the mentioned class, it follows the rules strictly.
If you can't fix the issue using the class you'll probably have an issue in the PHP script, so you would have to provide more informations about the script.
EDIT II
As I looked at your code once again I could find another issue. You are not setting the request method correctly. Here you set
[request setHTTPMethod:@"REQUEST"];
which is not a valid HTTP method! If you want post, you have to set it to @"POST"
or for get @"GET"
, for head @"HEAD"
and so on, see RFC 2616.
Upvotes: 1