php - Post and use the response SWIFT
Get the solution ↓↓↓I want to post data to a php file, and use the JSON response to generate a table. I've just started trying to learn swift, so I have no idea where I've gone wrong so any help would be greatly appreciated.
The swift file:
func get(){
let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost/test.php")!)
request.HTTPMethod = "POST"
let postString = "country=\(buttonPressedVal)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
do {
let url = NSURL(string: "http://localhost/test.php")
let data = NSData(contentsOfURL: url!)
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
print("Result -> \(result)")
} catch {
print("Error -> \(error)")
}
}
task.resume()
}
I want to use the result variable to generate a table view.
the php file:
<?php
$pdo = new PDO("mysql:host=localhost;dbname=imoova","root","mysql");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['country'])){
$country = $_POST['country'];
}else{
//$country = 'Australia';
echo "Failed to get post\n";
}
try
{
$sql = "SELECT * FROM imoova._relocation_deals A, imoova._airport_codes_lookup B WHERE A.location_from = B.code AND B.country = :country AND A.active = 1";
$result = array();
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":country", $country);
$stmt->execute();
while($result = $stmt->fetch()){
echo json_encode($result);
}
}
catch (PDOException $e)
{
echo $e->getMessage();
}
?>
The error I get is: Error -> Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end." UserInfo={NSDebugDescription=Garbage at end.}
Answer
Solution:
These lines in your php code:
while($result = $stmt->fetch()){
echo json_encode($result);
}
You are generating multiple JSON in a single response. That is not a valid JSON. Try replacing the lines with something like this:
while($row = $stmt->fetch()){
$result[] = $row;
}
echo json_encode($result);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: sqlstate[23000]: integrity constraint violation: 1452 cannot add or update a child row: a foreign key constraint fails
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.