Look what happens to me is that I am returning an html by json and it arrives empty if I stop returning it by json and I receive it normal, then if it arrives well and I don't know why or what the error is:
These are the codes:
ajax
function realizaProceso(){
var parametros = {};
$.ajax({
data: parametros,
url: '../controllers/index.php',
type: 'post',
dataType: 'json',//esta linea la quito cuando no uso el json
beforeSend: function () {
},
error: function (request, status, error) {
console.log(3);
console.log(request);
console.log(status);
console.log(error);
console.log(4);
},
success: function (response) {
alert("4");
/*var randomColor = '#'+ ('000000' + Math.floor(Math.random()*16777215).toString(16)).slice(-6);
$('#resultado').css({
'background-color' : randomColor,
});*/
console.log(response);
$(".loader").hide();
$(".carousel-congratulations").html(response.congratulations);
$(".carousel-birthdays").html(response.birthdays);
$(".carousel-events").html(response.events);
window.history.pushState("", "", '/iq/tv');
}
});
$.ajax({
data: parametros,
url: '../controllers/changeVideo.php?opcion=leer',
dataType: "json",
success: function (response) {
$(".urlVideo").attr("src", response[1]);
}
});
}
this is the controller or where the query is made
<?php
//fecha del dia de hoy
setlocale(LC_TIME, 'es_ES');
$hoy = getdate();
$day=$hoy['mday'];
$month=$hoy['mon'];
$year=$hoy['year'];
// Conectando, seleccionando la base de datos
include_once "con.php";
$sentencia = $con->prepare("SELECT * FROM congratulations WHERE id= ?;");
$sentencia->execute([1]);
$result = $sentencia->fetchAll(PDO::FETCH_OBJ);
$estado ="active";
$congratulations = "";
$contador=0;
foreach($result as $fila) {
$congratulations .= '<div class="carousel-item '.$estado.'">';
$estado="";
$col_image=($fila->image==NULL) ? "default.png" : "felicitaciones/homenajeado".$fila->id."/".$fila->image ;
$col_title=$fila->title;
$col_detail=$fila->detail;
$congratulations .= '<div class="not-item">';
$congratulations .= '<div class="item-t ">'.$col_title.'</div>';
$congratulations .= '<div class="row">';
$congratulations .= '<div class="card sin-border">';
$congratulations .= '<div class="card-body">';
$congratulations .= '<div class="col" style="border-color: transparent;"><img class="img-l" src="../images/'.$col_image.'" /></div>';
$congratulations .= '</div></div>';
$congratulations .= '<div class="col" style="border-color: transparent;">';
$congratulations .= '<div class="card sin-border">';
$congratulations .= '<div class="card-body">';
$congratulations .= '<p class="card-text text-left"> Ciudad: '.$col_detail.'</p>';
$congratulations .= '</div></div></div></div></div></div>';
$contador++;
}
$congratulations .= ($contador>0) ? "" : "<div class='carousel-item active'><div class='cum-item'><div class='name fleft'>No hay cumpleaños el dia de hoy</div></div></div>";
$sentencia = $con->prepare("SELECT * FROM birthdays WHERE day= ? AND month= ?;");
$sentencia->execute([$day, $month]);
$result = $sentencia->fetchAll(PDO::FETCH_OBJ);
$estado ="active";
$birthdays = "";
$contador=0;
foreach($result as $fila) {
$birthdays .= '<div class="carousel-item '.$estado.'">';
$estado="";
$birthdays .= '<div class="cum-item">';
$col_image=($fila->image==NULL) ? "default.png" : $fila->id."/".$fila->image ;
$col_name=$fila->name;
$col_surname=$fila->surname;
$col_job=$fila->job;
$birthdays .= '<div class="img-cum fleft sin-border"><img class="img-l" src="../images/'.$col_image.'" /></div>';
$birthdays .= '<div class="col sin-border">';
$birthdays .= '<div class="row">';
$birthdays .= '<div class="name fleft">'.$col_name.'<br/>'.$col_surname.'</div></div>';
$birthdays .= '<div class="row">';
$birthdays .= '<div class="cargo fel "> '.$col_job.'</div>';
$birthdays .= '</div></div></div></div>';
$contador++;
}
$birthdays .= ($contador>0) ? "" : "<div class='carousel-item active'><div class='cum-item'><div class='name fleft'>No hay cumpleaños el dia de hoy</div></div></div>";
$sentencia = $con->prepare("SELECT * FROM events WHERE year>= ?");
$sentencia->execute([2018]);
$result = $sentencia->fetchAll(PDO::FETCH_OBJ);
$estado ="active";
$events = "";
foreach($result as $fila) {
$events .= '<div class="carousel-item '.$estado.'">';
$estado="";
$events .= '<div class="event-item">';
$events .= '<div class="row">';
$col_name = $fila->name;
$col_description = $fila->description;
$col_city = $fila->city;
$col_place = $fila->place;
$col_day = $fila->day;
$col_month = strftime("%B", DateTime::createFromFormat('m', $fila->month)->getTimestamp());
$col_month = ucwords(strtolower($col_month));
$col_hour = strftime("%I", DateTime::createFromFormat('H', $fila->hour)->getTimestamp());
$col_minute = $fila->minute;
$col_format = DateTime::createFromFormat("H", $col_hour);
$col_format = $col_format->format("a");
$events .= '<div class="card sin-border">';
$events .= '<div class="card-body">';
$events .= '<div class="col sin-border"><h3 class="text-truncate text-center">'.$col_day.'<small> '.$col_month.'</small></h3></div>';
$events .= '</div></div>';
$events .= '<div class="col sin-border">';
$events .= '<div class="card sin-border" style="border-left-color: rgba(0, 0, 0, .10) !important;">';
$events .= '<div class="card-body">';
$events .= '<h2 class="card-title text-left">'.$col_name.'</h2>';
$events .= '<p class="card-text text-left"> Ciudad: '.$col_city.'</p>';
$events .= '<p class="card-text text-left">Lugar: '.$col_place.'</p>';
$events .= '<p class="card-text text-left">Hora: '.$col_hour.':'.$col_minute.' '.$col_format.'</p>';
$events .= '<p class="card-text text-left"><small>Interesados escribir a [email protected]</small></p>';
$events .= '</div></div></div></div></div></div>';
$contador++;
}
if to the controller I add:
echo $congratulations.$birthdays.$events;
?>
In the console I get this:
As you can see, it shows me the html code of the queries that I need.
but on the contrary I add to the controller this:
header('Content-Type: application/json');
//Guardamos los datos en un array
$datos = array(
'estado' => 'ok',
'congratulations' => $congratulations,
'birthdays' => $birthdays,
'events' => $events
);
//Devolvemos el array pasado a JSON como objeto
echo json_encode($datos, JSON_FORCE_OBJECT);
?>
Your .php file seems not to be encoded correctly that in the html you generate there are � characters.
Verify that your file is encoded in UTF-8 without BOM .
And make sure to save it with said encoding using your preferred text editor/IDE.
You have to apply an adequate coding by levels , going to the root of the problem.
In your case, you would have to act on two key issues:
header
one in your JSONIt is always a good idea to indicate the encoding when you create a JSON:
And also tell the connection object to bring the data from the database encoded according to what you need:
Regarding the connection, to avoid having to do this query every time, you can indicate that you want encoding
utf-8
when you create the connection itself.There are two ways to do it:
Passing it in an array of options. This is my preferred way, because by the way, for safety, you should turn off emulated preparations when using PDO and set error handling well. So you can create an array with all the options and pass it to the constructor of your PDO object:
ATTR_EMULATE_PREPARES
avoid emulated prepares, which could be a security risk for SQL Injection.ERRMODE_EXCEPTION
Correctly configure error handling. For example, in some scenarios, when there are errors creating the connection, PDO may write to the error log your connection credentials, including the password!MYSQL_ATTR_INIT_COMMAND
configure the connection to useutf-8
, so you no longer have to send this query every time you use your connection:$con->query("SET NAMES 'utf8'");
The encoding can also be passed directly in the DSN, as follows:
It is passed
charset=UTF8
preceded by;
after the database name. If you put it in the options array explained in (1), you would no longer have to do it as explained here in (2).