POST METHOD not getting data from php

what im trying to do is getting the information from my textfields and send it using POST method to my PHP file to save it into my DB but the data from the textfield is not getting saved im getting this error: when i try to capture the data

SUCCESS: {

error = 1;

message = "el dato es: ";

}


all code


//
//  creaciondecuentaViewController.swift
//  123Taxi
//
//  Created by José Raúl Toledano Rosado on 10/10/18.
//  Copyright © 2018 José Raúl Toledano Rosado. All rights reserved.
//
import Alamofire
import UIKit

class creaciondecuentaViewController: UIViewController {
    @IBOutlet var Nombre_Completo: UITextField!
    @IBOutlet var asd123: UILabel!
    
    @IBOutlet var Email: UITextField!

    @IBOutlet var Contrasena: UITextField!
    
    
    @IBOutlet var Telefono: UITextField!
    
    @IBOutlet var Telefono_Contacto: UITextField!
    
    @IBOutlet var Email_Contacto: UITextField!
    var pasajero = true
    let URL_USER_REGISTER = "can't show this"
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        pasajero = true
        // Do any additional setup after loading the view.
    }
    

    @IBAction func CrearCuenta(_ sender: UIButton) {
        pasajero = true
        if Email.text == "" || Contrasena.text == "" || Telefono.text == "" || Telefono_Contacto.text == "" || Email_Contacto.text == ""{
            displayAlert(title: "Información Faltante", message: "Debes porporcionar los datos solicitados")
        }
        else
        {
            //creating parameters for the post request
            let parameters: Parameters=[
                "Nombre_Completo":Nombre_Completo.text!,
                "Correo":Email.text!,
                "Contrasena":Contrasena.text!,
                "Telefono":Telefono.text!,
                "Email_Contacto":Email_Contacto.text!,
                "Telefono_Contacto":Telefono_Contacto.text!
                
            ]
            
            
       
            //Sending http post request
            Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON
                {
                    response in
                    //printing response
                    print(response)
                    
                    //getting the json value from the server
                    if let result = response.result.value {
                        
                        //converting it as NSDictionary
                        let jsonData = result as! NSDictionary
                        
                        //displaying the message in label
                        self.asd123.text = jsonData.value(forKey: "message") as! String?
                    }
            }
            
        }
    }
    
    func displayAlert (title:String, message:String){
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
        self.present(alertController, animated: true, completion: nil)
        
    }
        
    
    
    
    @IBAction func YaTengoCuenta(_ sender: UIButton) {
        
    }
    
    
    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    
    
    
    @IBAction func unwindToVC1(segue:UIStoryboardSegue) {
        
    }
    @IBAction func goBackToOneButtonTapped(_ sender: Any) {
        performSegue(withIdentifier: "fromregistroToMain", sender: self)
    }
    
    
    
}

i guess this is where im stuck


//Sending http post request
            Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON
                {
                    response in
                    //printing response
                    print(response)
                    
                    //getting the json value from the server
                    if let result = response.result.value {
                        
                        //converting it as NSDictionary
                        let jsonData = result as! NSDictionary
                        
                        //displaying the message in label
                        self.asd123.text = jsonData.value(forKey: "message") as! String?
                    }
            }
            
        }
    }

php code DbConnect

/**
 * Created by PhpStorm.
 * User: zerocool
 * Date: 10/11/18
 * Time: 4:23 PM
 */

class DbOperation
{
  private $conn;

  //Constructor
  function __construct()
  {
  include dirname(__FILE__) . '/constants.php';
  include dirname(__FILE__) . '/DbConnect.php';
  // opening db connection
  $db = new DbConnect();
  $this->conn = $db->connect();
  }

  //Function to create a new user
  public function createUser($Nombre_Completo, $Correo, $Contrasena, $Telefono, $Email_Contacto, $Telefono_Contacto)
  {
  if (!$this->isUserExist($Nombre_Completo, $Correo, $Telefono)) {
  $Contrasena = md5($contrasena);
  $stmt = $this->conn->prepare("INSERT INTO users (Nombre_Completo, Correo, Contrasena, Telefono, Email_Contacto, Telefono_Contacto) VALUES (?, ?, ?, ?, ?, ?)");
  $stmt->bind_param("ssssss", $Nombre_Completo, $Correo, $Contrasena, $Telefono, $Email_Contacto, $Telefono_Contacto);
  if ($stmt->execute()) {
  return USER_CREATED;
  } else {
  return USER_NOT_CREATED;
  }
  } else {
  return USER_ALREADY_EXIST;
  }
  }


  private function isUserExist($Nombre_Completo, $Correo, $Telefono)
  {
  $stmt = $this->conn->prepare("SELECT id FROM users WHERE Nombre_Completo = ? OR Correo = ? OR Telefono = ?");
  $stmt->bind_param("sss", $Nombre_Completo, $Correo, $Telefono);
  $stmt->execute();
  $stmt->store_result();
  return $stmt->num_rows > 0;
  }
}

register php


/**
 * Created by PhpStorm.
 * User: zerocool
 * Date: 10/11/18
 * Time: 4:49 PM
 */

require_once '../includes/DbOperation.php';

$response = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  if (!verifyRequiredParams(array('Nombre_Completo', 'Correo', 'Contrasena', 'Telefono', 'Email_Contacto', 'Telefono_Contacto'))) {
  //getting values
  $Nombre_Completo = $_POST['Nombre_Completo'];
  $Correo = $_POST['Correo'];
  $Contrasena= $_POST['Contrasena'];
  $Telefono = $_POST['Telefono'];
  $Email_Contacto= $_POST['Email_Contacto'];
  $Telefono_Contacto= $_POST['Telefono_Contacto'];

  //creating db operation object
  $db = new DbOperation();

  //adding user to database
  $result = $db->createUser($Nombre_Completo, $Correo, $Contrasena, $Telefono, $Email_Contacto, $Telefono_Contacto);

  //making the response accordingly
  if ($result == USER_CREATED) {
  $response['error'] = false;
  $response['message'] = '¡Usuario creado!';
  } elseif ($result == USER_ALREADY_EXIST) {
  $response['error'] = true;
  $response['message'] = 'Cuenta existente, pruebe de nuevo';
  } elseif ($result == USER_NOT_CREATED) {
  $response['error'] = true;
  $response['message'] = 'Ocurrió un error';
  }
  } else {
  $response['error'] = true;
  $response['message'] = 'el dato es: '.$Nombre_Completo;
  }
} else {
  $response['error'] = true;
  $response['message'] = 'Solicitud no valida';
}

//function to validate the required parameter in request
function verifyRequiredParams($required_fields)
{

  //Getting the request parameters
  $request_params = $_REQUEST;

  //Looping through all the parameters
  foreach ($required_fields as $field) {
  //if any requred parameter is missing
  if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {

  //returning true;
  return true;
  }
  }
  return false;
}

echo json_encode($response);

Replies

This is not a good place to find faults in your PHP code, or telling how to use third part libraries such as Alamofire,

but you are doing inconsistent things in your client code and server code.


The server side code uses `$_POST`, which means all request parameters needs to be sent in a usual `application/x-www-form-urlencoded`.

But your client code send them in JSON -- `encoding: JSONEncoding.default`.

You may need to pass an appropriate value for the parameter `encoding`.