I have a tournament class file and the method of inserting a new one, after inserting makes a query of the id. Said id I want to return it to create the view of groups of players of said tournament, I work with MVC.
public function registrarTorneo($nombreTorneo,$Fecha,$Localidad,$iddisciplina){
try
{
$sqltorneo="INSERT INTO torneo(idtorneo,nombretorneo,Fecha,Localidad,Iddisciplina) VALUES (null,'".$nombreTorneo."','".$Fecha."','".$Localidad."',".$iddisciplina.");";
$sqlidtorneo='select max(idtorneo) as id from torneo order by idtorneo desc;';
$conexion = Conexion::singleton_conexion();
$conexion->beginTransaction();
$conexion->query($sqltorneo);
$conexion->commit();
$stm=$conexion->prepare($sqlidtorneo);
$stm->execute();
$array=$stm->fetchAll(PDO::FETCH_ASSOC);
return $array;
}catch(Exception $e){
die($e->getMessage());
}
}
then I have the Tournament process where I create an object of that type:
if (isset($_POST['opcion'])=='crear'){
$c=new Torneo();
$nombre=$_POST['nombre'];
$fecha=$_POST['fecha'];
$localidad=$_POST['localidad'];
$dis=$_POST['dis'];
$grupos=$_POST['grupos'];
$jpg=$_POST['jxg'];
$id=$c->registrarTorneo($nombre,$fecha,$localidad,$dis);
echo json_encode($id);
}
And when I try to get the id I do:data[0].id
If I do: console.log(data)
I get: [{"id":"56"}]
$("#nuevotorneo").on("click",function(){
if (validaForm()==true){
$.ajax({
type: "POST",
data:{'opcion':'crear','nombre':$("#nombre").val(),'fecha':$("#fechahora").val(),'localidad':$('select[id="localidad"] option:selected').text(),
'dis':$("#disciplina").val(),'grupos':$("#numGrupos").val(),'jxg':$("#numjp").val()},
url: '/billar/views/modules/torneo/procesoTorneo.php',
beforeSend: function(){
/*
* Esta función se ejecuta durante el envió de la petición al
* servidor.
* */
},
complete:function(){
},
success: function(data){
/*
* Se ejecuta cuando termina la petición y esta ha sido
* correcta
* */
console.log(data);
// window.location.href="index.php?controller=torneo&action=fasegrupos";
},
error: function(){
/*
* Se ejecuta si la peticón ha sido erronea
* */
alert("Problemas al tratar de enviar el formulario");
}
});
// Nos permite cancelar el envio del formulario
return false;} });
So what is the proper way to access the id value?
The problem is that by not indicating it
dataType
in your Ajax request, it returns it to you with thedataType
default onehtml
and to read it as JSON you would have to do aJSON.parse
in Ajax.Since you use MVC, you should have a JSON output type in the View, to which you would send the JSON outputs, either data or errors.
A simpler solution is to indicate the
dataType
and ensure server-side always a JSON response.For that you will have to modify the error handling a bit too, avoiding resolving with a simple
die
, and sending something like:$outPut=array ("error"=>"mensaje de error");
.Without getting into the mess of the view, we'll do it by hand, because that's the way you have it, but consider simplifying it by using the view (as you well know the
V
deMVC
means View , and you should send all the outputs to it).Proposed solution
You indicate the
dataType
in Ajax:You modify the checks in
success
:Applying this should work. If something is not clear, you can say so by commenting on this answer.
Hint for PHP code
You do not need to use
fetchAll()
for this case, this method creates an array of array, so then you would have to do the reading like this:data[0].id
. For unique rows you canfetch
simply use:So the data will not be an array of array and you can do the reading in JS like this:
data.id
, without having to refer to the index0
.