0

How can I modify this fetch JSON function to allow HTTP POST requests to be sent. I have written a script in php that looks for variable "a"

This is what the php looks like:

<?php


$con=mysqli_connect("localhost","username","password","dbname");

// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Equipment'

$nameValue = $_POST['a'];


$sql = "SELECT customer, FROM TABLE1 WHERE (customer = '$nameValue') and status = 'Active' ";

// Check if there are results
if ($result = mysqli_query($con, $sql))
{
    // Create temporary connection
    $resultArray = array();
    $tempArray = array();

    // Look through each row
    while($row = $result->fetch_object())
    {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

mysqli_close($con);


}

?>

The following is the Swift code I am using to retrieve the JSON data, but now I would like to respond to the JSON POST Request, what can be added to this?

fileprivate func fetchJSON(){
    let urlString = "https://www.example.com/example/example.php"
    guard let url = URL(string: urlString) else { return }
    URLSession.shared.dataTask(with: url) { (data, _, error) in
        DispatchQueue.main.async {
            if let error = error {
                print("Failed to fetch data from url", error)
                return
            }
            guard let data = data else { return }
            do {
                let decoder = JSONDecoder()
                // Swift 4.1

                self.structure = try decoder.decode([ScheduleStructure].self, from: data)

                self.tableView.reloadData()

            } catch let jsonError {
                print("Failed to decode json", jsonError)
            }

        }
        }.resume()
}
  • possible duplication: https://stackoverflow.com/a/31938246/5464805 – Olympiloutre Jun 06 '19 at 06:25
  • 1
    Possible duplicate of [How to make HTTP Post request with JSON body in Swift](https://stackoverflow.com/questions/31937686/how-to-make-http-post-request-with-json-body-in-swift) – Mike Doe Jun 06 '19 at 06:32

0 Answers0