I have the following question: how to convert this basic php code to cakephp:
Controller
public function politics_index($active_pill = null)
{
$this->layout = 'politics';
$user = $this->Auth->user();
$doctor = $user['Doctor'];
$doctorId = $user['Doctor']['id'];
if ($this->request->is('post')) {
$link = mysqli_connect("localhost", "bd", "user", "clave");
// Check connection
if($link === false){
//echo("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt update query execution
$sql = "UPDATE doctors SET acepto='Si' WHERE id=$doctorId";
if(mysqli_query($link, $sql)){
echo "<div hidden>respuestaAceptoDoctorQueIngreso=Si</div>";
} else {
echo "<div hidden>respuestaAceptoDoctorQueIngreso=No</div>";
}
// Close connection
mysqli_close($link);
//mysqli_close($conexion);
}
else {
$link = mysqli_connect("localhost", "bd", "user", "clave");
mysql_select_db("interqui_web",$conexion);
$sql = "SELECT * FROM doctors where id=$doctorId";
if($result = mysqli_query($link, $sql)){
$row = mysqli_fetch_array($result);
$acepto=$row['acepto'] ;
if($acepto==="Si"){
echo "<div hidden>respuestaAceptoDoctorQueIngreso=Si</div>";
} else {
echo "<div hidden>respuestaAceptoDoctorQueIngreso=No</div>";
}
}
mysqli_close($link);
}
}
Model
class Doctor extends AppModel {
public $belongsTo = array('Doctitle');
public $hasAndBelongsToMany = array(
'Education' =>
array(
'className' => 'Specialty',
'joinTable' => 'doctor_education',
'foreignKey' => 'doctor_id',
'associationForeignKey' => 'specialty_id',
'unique' => true,
),
);
public $validate = array(
'name' => array(
'rule' => 'notBlank'
),
'image' => array(
'rule' => array(
'isValidMimeType',
array('image/jpeg', 'image/png', 'image/gif'),
false
),
'allowEmpty' => true,
'message' => 'File is not an image',
),
);
/* using the upload plugin */
public $actsAs = array(
'Upload.Upload' => array(
'image' => array(
'path' => '{ROOT}webroot{DS}img{DS}uploads{DS}',
'thumbnailSizes' => array(
'thumb' => '150w'
),
// uncoment next if "imagick not found"
'thumbnailMethod' => 'php',
),
)
);
}
?>
Ajax
$(document).ready(function () {
$("input[type=checkbox]").on( "click", function(){
if( $('.input-check-borrado').is(':checked') ) {
var parametros = {
"doctorName" : $(".doctorTitle").text(),
"loActivo" : "Si"
};
console.log($(".doctorTitle").text());
$.ajax({
data: parametros,
url: '/politics/config',
type: 'post',
/*dataType: "json",*/
beforeSend: function () {
$("#resultado").html("Procesando, espere por favor...");
},
success: function (response) {
if(response.indexOf("respuestaAceptoDoctorQueIngreso=Si")> -1){
$('input.input-check-borrado').attr("disabled", true);
}
else {
$("input.group1").removeAttr("disabled");
}
}
});
}
});});
If you detailed yourself in the ajax, I have a documented line, it's because I don't know how to return a simple yes or no by json encode, ps when receiving it in the ajax the response was empty, I don't know if you know what I'm missing ps I had the data type of the js in 'json' and in the controller string json_encode("yes"); at first i thought i had to return an array so i returned the $user variable which i know is an array
In order to use a model from another controller you can use
$this->loadModel('Model')
and work as you normally do.You also don't need to call mysql methods directly, CakePHP does it for you when calling its methods, plus it already sanitizes them to prevent SQL injection.
Here you can see more about the magic function
findBy
, and here about updating a fieldIt is also important to check if the request is of type JSON and in this way return a JavaScript object to be able to manipulate it
In your controller the code would look like this
To call the controller method directly, we do it as a request would normally be done, with the controller URL. It is important to pass
dataType: "json"
it so that it returns a JSON and not the code of the page.Your ajax request would look like this, your response should come in
response.data.items