0
I am developing a particular project and I started to develop a calendar to put in this project, however, when sending the date selected by the user or automatically when he enters the page, To be treated, I cannot rescue the data sent by Ajax to PHP by the POST method nor GET. When I try to capture this data I sent to PHP as follows print_r($_POST)
an empty array is shown on the screen, that is, it does not even contain an element inside it. I am running the calendar by PHP apache itself, ie php -S localhost:3333, I do not know if it could interfere, however, all information is valid
I am sending the Ajax data directly to index.php which is where it contains the calendar, because when I go to put inside my project, I will have to send to the very view that is running, for me to rescue in the controller, because I am doing the project in MVC structure.
I’m going to put my code now and it’s all contained inside the same folder, because the calendar I created is just a prototype to see if it would work, is not contained in the design that is with the MVC structure, is just a prototype to check if it would work, however, I have a problem with the Ajax method.
index php.
<?php
// Solicitando todos os dados enviado pelo método POST
print_r($_POST);
?>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Calendar</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div class="conteudo">
<div class="areaCalendario">
<div class="mesSelect">
<h4></h4><img src="dropDown.svg">
</div>
<div class="calendario">
<header>
<h2 class="ano"></h2>
<a class="ButtonPrevious"><</a>
<a class="ButtonNext">></a>
</header>
<table class="mes">
<tbody>
<tr>
<td class="mesSelecionado">Jan</td>
<td class="mesSelecionado">Fev</td>
<td class="mesSelecionado">Mar</td>
<td class="mesSelecionado">Abr</td>
</tr>
<tr>
<td class="mesSelecionado">Mai</td>
<td class="mesSelecionado">Jun</td>
<td class="mesSelecionado">Jul</td>
<td class="mesSelecionado" >Ago</td>
</tr>
<tr>
<td class="mesSelecionado" >Set</td>
<td class="mesSelecionado" >Out</td>
<td class="mesSelecionado" >Nov</td>
<td class="mesSelecionado" >Dez</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
script js.
document.addEventListener('DOMContentLoaded', function() {
/*
*
* Função global para fazer requisições ajax e enviar as informações para o
* servidor
*/
function getAjax(date) {
$.ajax({
type: 'post',
url: 'index.php',
data: {'date':date},
dataType: 'html',
success: d => {
console.log(d)
},
error: erro => {
console.log(erro)
}
})
}
/*
* getDaysCalender(mes, ano)
* Seleciona o mês e o ano atual, converte esses valores para string e apresenta
* esses valores ao usuário.
*/
function getDaysCalender(mes, ano) {
monthSelect = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun','Jul',
'Ago', 'Set', 'Out', 'Nov', 'Dez'];
document.querySelector('.mesSelect h4').innerHTML = monthSelect[mes];
document.querySelector('.ano').innerHTML = ano;
// percorrer as tds para selecionar o mes atual
const table = document.querySelectorAll(".mes td");
for(let i=0; i < table.length; i++){
if(table[i].innerText === monthSelect[mes]) {
table[i].classList.add("tdActive");
}
}
return `${mes+1}-${ano}`;
}
/*
* Selecionando o mês atual e o ano atual para ser enviada para o php por
* requisições ajax
*/
let dt = new Date();
let month = dt.getMonth();
let year = dt.getFullYear();
// Capturando a informação do calendário
let date = getDaysCalender(month, year);
// envia por requisição ajax para ser tratado no php.
getAjax(date)
/*
* Selecionando o próximo ano ou o ano anterior
*/
const btnPrev = document.querySelector(".ButtonPrevious");
const btnNext = document.querySelector(".ButtonNext");
btnPrev.onclick = () => {
year--;
document.querySelector('.ano').innerHTML = year;
}
btnNext.onclick = () => {
year++;
document.querySelector('.ano').innerHTML = year;
}
/*
* selectDate(mes)
* Seleciona a data que o usuário requisitou
*/
function selectDate(mes) {
// Para converter o mes para numero
monthSelect = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun','Jul',
'Ago', 'Set', 'Out', 'Nov', 'Dez'];
// Para trazer o ano que foi selecionado
let yearSelect = document.querySelector('.ano').innerHTML;
// Seleciona o mes que foi selecionado junto com o ano para deixar a class active
const table = document.querySelectorAll(".mes td");
for(let i=0; i < table.length; i++){
if(table[i].innerText === mes) {
document.querySelector('.mesSelect h4').innerHTML = mes;
table[i].classList.add("tdActive");
}
}
// Transformando o mês em numero
let mesNum = null;
for(let i=0; i<=monthSelect.length; i++) {
if(monthSelect[i] == mes) {
mesNum = i+1;
}
}
// Enviar essa informação para o php para fazer a filtragem do mês e ano
return `${mesNum}-${yearSelect}`;
}
/*
* Seleciona o mês e o ano no calendário e envia esses dados para serem tratados
* na função selectDate
*/
$('.mesSelecionado').click((e) => {
$('.mesSelecionado').removeClass('tdActive');
// Caputrando o mes escolhido e enviando para a function
let monthSelect = e.target.innerHTML;
// Recebendo os dados da function
let date = selectDate(monthSelect);
//Envia o ados para o getAjax para enviar via ajax para o php
getAjax(date)
// Fechando calendario após selecionar o mes e o ano
$('.calendario').slideToggle();
})
/*
* Abrindo o calendário quando for solicitado pelo usuário
*/
$('.mesSelect').click((e) => {
$('.calendario').slideToggle();
})
/*
* Executando métodos quando a página for carregada
*/
$(document).ready(() => {
// Deixando o calendario com display none
$('.calendario').hide();
})
}, false);
Concluding remarks
Ajax works perfectly, because it shows in the browser console all the index.php, which is the sending command if the request is successful, ie the Success command of ajax.
When sending the data via Ajax to PHP and executing the following command within the index.php ````print_r($_POST)````, it displays an empty array, but Success shows the entire index.php in the console with that array filled, follow the image to view how it looks when requesting and sending the data --> https://i.imgur.com/Mbt3gse.png
In Elements which are html codes executed, shows an empty array, follows the image as shown in Elements --> https://i.imgur.com/32VADbQ.png
Now on the network that is where shows all executions done in the application, on localhost shows the empty array, follows the image as shown --> https://i.imgur.com/vzl6PcP.png only that on the network itself has the index php. which shows that the array is populated as requested by the method print_r($_POST)
, follows the image of how the network of index.php is shown --> https://i.imgur.com/Fpht8oa.png within the network it is shown that the request was successfully made because it presents xmlrequest.js.
Final considerations
So, I don’t know if my line of reasoning is valid and correct, but what it looks like is that the localhost can’t "update" to receive index.php with the data, I mean, in other words it’s like localhost isn’t looking at index.php and realizing that it’s changed, so it can’t provide this requested data to the user in the browser, which is what I’m looking for right now, in order to be able to process this date and in the future to play for the modal, in order to be able to manipulate the data and rescue the data contained in the database. With this, if my line of reasoning is correct, I do not know how to solve. KKKKKKKKKKKKKKKKKKKK :D
Let me understand, when you enter the page shows empty, and when you call ajax shows the Array? that’s it?
– Rogerio Santos
No, when you enter the page shows empty and Ajax is called automatically, as soon as the page loads, because javascript takes the current month, for example 6/2020 and already sends to index.php, then when the user is going to do a filtering for the previous month for example, it opens the calendar and selects the previous month, then the ajax sends again by the same variable #_POST(date) the request of the user, in case 05/2020, understood ?
– ClaudianoPL
Missing details: But this is strange dataType: 'html'... usually 'json' or 'xml', I think you are using 'json'....
– Duda Gervásio
I’ve tried by the json method, it didn’t work, it’s strange because I’ve always done so and it always worked not using the html dataType and yes json, but neither JSON is working, what details are missing ???
– ClaudianoPL