После функции замены datepicker, отправьте значение на ту же страницу php с помощью вызова javascript / ajax без обновления - PullRequest
0 голосов
/ 10 января 2019

Я пытаюсь заполнить часть страницы PHP в div, где результаты извлекаются из базы данных MySQL после функции смены календаря DatePicker. Каждый раз, когда я выбираю дату из календаря, я вижу доступные часы. Моя концепция: 1. Я выбираю дату 2. div с таблицей часов появляется при наличии 3. выберите радио-кнопку показного часа, а затем отправьте мой выбор в БД.

Проблема в пункте 2.

Это код javascript внутри страницы, перед тем, как закрыть голову

$(document).ready(function() {

    if(sessionStorage.getItem("homecal") === null || sessionStorage.getItem("prenotacal") === null) {
        $('#datasel').html('Seleziona la data della visita dal calendario.');
        $('#prenota-ora').hide();
    }

    if(sessionStorage.getItem("homecal") !== null) {
        $('#datasel').html('Hai selezionato il giorno ' + sessionStorage.getItem("homecal"));
        $('#giornosel').val(sessionStorage.getItem("homedate")); //scrive la data nell'input hidden
        $('#prenota-ora').show();
    }

    if(sessionStorage.getItem("prenotacal") !== null) {
        $('#datasel').html('Hai selezionato il giorno ' + sessionStorage.getItem("prenotacal"));
        $('#prenota-ora').show();
    }


    var homedate    = sessionStorage.getItem("homedate");

    var days        = new Date(homedate);
    var NumDays     = ['0', '1', '2', '3', '4', '5', '6'];
    var dayNum  = NumDays[days.getDay()];

    if(homedate !== null && dayNum == '1' || dayNum == '3' || dayNum == '5') { //lunedi e mercoledi e venerdi
        $('#orari-mattina').hide();
        $('#orari-pomeriggio').fadeIn('1000');
        $('#avanti').hide();
        }
    if(homedate !== null && dayNum == '2' || dayNum == '4') { //martedi e giovedi
        $('#orari-mattina').fadeIn('1000');
        $('#orari-pomeriggio').fadeIn('2000');
        $('#avanti').hide();
        }

    var anno        = new Date().getFullYear();

    $('#datepicker').datepicker({ 
        format: "yyyy-mm-dd",
        language: "it",
        keyboardNavigation: false,
        forceParse: false,
        daysOfWeekDisabled: "0,1,4,6",
        todayHighlight: true,
        startDate: "-0m",
        immediateUpdates: true,
        toggleActive:true,
        datesDisabled: ['2019-01-01', '2019-01-02', '2019-01-03', '2019-01-04', '2019-01-05', '2019-01-06', '2019-01-07', '2019-01-09', '2019-01-11', '2019-01-12', '2019-01-13', 'anno-01-01', 'anno-01-02', 'anno-01-03', 'anno-01-04', 'anno-01-05','anno-01-06','anno-01-07', 'anno-01-09', 'anno-01-11', 'anno-01-12', 'anno-01-13', 'anno-04-02', 'anno-04-25', 'anno-04-30', 'anno-05-01', 'anno-06-02', 'anno-06-08', 'anno-06-11', 'anno-08-01', 'anno-08-02', 'anno-08-03', 'anno-08-04', 'anno-08-05', 'anno-08-06', 'anno-08-07', 'anno-08-08', 'anno-08-09', 'anno-08-10', 'anno-08-11', 'anno-08-12',  'anno-08-13', 'anno-08-14', 'anno-08-15', 'anno-08-16', 'anno-08-17', 'anno-08-18', 'anno-08-19', 'anno-08-20', 'anno-08-21', 'anno-08-22', 'anno-08-23', 'anno-08-24', 'anno-08-25', 'anno-08-26', 'anno-08-27', 'anno-08-28', 'anno-08-29', 'anno-08-30', 'anno-08-31', 'anno-11-01', 'anno-12-07', 'anno-12-08', 'anno-12-09', 'anno-12-24', 'anno-12-25', 'anno-12-26', 'anno-12-27', 'anno-12-29', 'anno-12-30', 'anno-12-31', ]

     }).on('changeDate', function() {

    $('#prenota-ora').show();
    $('#orari-mattina').hide();
    $('#orari-pomeriggio').hide();
    $('#avanti'). hide();
    $('input[name="orario"]').prop('checked', false); //resetta orario
    $('#orario').val(""); //resetta orario

    sessionStorage.removeItem("homecal");
    sessionStorage.removeItem("homedate");
    sessionStorage.removeItem("orarioselezionato");
    $('#orariosel').html(""); //resetta orario


    sessionStorage.setItem("prenotadate", $('#datepicker').datepicker('getFormattedDate'));   // CREA SESSIONE DEL GIORNO HOME FORMATO DATE

    var values = sessionStorage.getItem("prenotadate");

    if (window.XMLHttpRequest){
        xmlhttp=new XMLHttpRequest();
    }

    else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     }

     var PageToSendTo = "prenotazione/prenota.php?";
     var MyVariable = sessionStorage.getItem("prenotadate");
     var VariablePlaceholder = "giornosel=";
     var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;

     xmlhttp.open("GET", UrlToSend, true);
     xmlhttp.send();

          var days      = new Date($('#datepicker').datepicker('getFormattedDate'));
          var NumDays   = ['0', '1', '2', '3', '4', '5', '6'];
          var dayNum    = NumDays[days.getDay()];

          if(dayNum == '1' || dayNum == '3' || dayNum == '5') { //lunedi e mercoledi e venerdi
          $('#orari-pomeriggio').fadeIn('1000');
          }
          if(dayNum == '2' || dayNum == '4') { //martedi e giovedi
          $('#orari-mattina').fadeIn('1000');
          $('#orari-pomeriggio').fadeIn('2000');
          }

    // Test with ajax method with different approaches
    //$.ajax({ // SEND VALUE TO PHP
    //  type:"GET",
    //  url: "prenotazione/prenota.php",
    //    url: "index.php?a=prenotazione-online&go=prenota",
    //  data:{giornosel:values},
    //    data: 'data='+JSON.stringify({giornosel:values}),
    //  dataType:"text",
    //  async: false,
    //  headers: {
          //     'Accept': '*/*',
          //     'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
          //     'Content-Type': 'text/html; charset=iso-8859-1' //Client 
    //          'Content-Type': 'text/html; charset=UTF-8' //Client 
    //  },
    //  success: function(data){
    //  console.log(data);
    //      var days        = new Date($('#datepicker').datepicker('getFormattedDate'));
    //        var NumDays   = ['0', '1', '2', '3', '4', '5', '6'];
    //        var dayNum    = NumDays[days.getDay()];

    //       if(dayNum == '1' || dayNum == '3' || dayNum == '5') { //lunedi e mercoledi e venerdi
    //    $('#orari-pomeriggio').fadeIn('1000');
    //    }
    //    if(dayNum == '2' || dayNum == '4') { //martedi e giovedi
    //    $('#orari-mattina').fadeIn('1000');
    //    $('#orari-pomeriggio').fadeIn('2000');
    //    }
    //  return true;
    //  },
    //  complete: function() {},
    //  error: function(xhr, textStatus, errorThrown) {
    //  console.log('ajax loading error...');
    //  return false;
    //  }
    //}); //END AJAX


    var monthNames = ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre",  "Novembre", "Dicembre"];

    var d               = new Date(sessionStorage.getItem('prenotadate'));
    var day                 = d.getDate();
    var monthIndex      = d.getMonth();
    var year                = d.getFullYear();
    var prenotacal  = day + ' ' + monthNames[monthIndex] + ' ' + year;

    $('#datasel').html('Hai selezionato il giorno ' + prenotacal);

    sessionStorage.setItem("prenotacal", prenotacal);   // CREA SESSIONE DEL GIORNO HOME FORMATO CALENDARIO 

    }); //END ONCHANGE

    $('input:radio[name=orario]').change(function() {

    var orario = $('input:radio[name=orario]:checked').attr('id');
    $('#orario').val(orario);

    var ore     = orario.substr(0,2);
    var min     = orario.substr(2,4);

    var orarioselezionato   = ore + ':' + min;

    sessionStorage.setItem("orarioselezionato", orarioselezionato); // crea sessione formato ora
    sessionStorage.setItem("orario", orario); // crea sessione formato tabella

    if(sessionStorage.getItem("orarioselezionato") === null) {}
    else {
    $('#orariosel').html(', alle ore ' + sessionStorage.getItem("orarioselezionato"));
    }

    if(sessionStorage.getItem("orarioselezionato") !== null && (sessionStorage.getItem("prenotadate") !== null || sessionStorage.getItem("homedate") !== null)) {
    $('#avanti').show();
    } else {}

    }); // END CHANGE FUNCTION
    }); // END READY FUNCTION

Я много раз пытался использовать разные решения для отправки данных на страницу php в виде ajax-метода GET / POST также с типом данных JSON, но иногда он работает правильно только на панели firebug, а не на веб-странице.

Часть PHP, которая управляет часами:

<?php
     switch ($_SERVER['REQUEST_METHOD']) {
     case 'POST':
     post_handler();
     break;

     case 'GET':
     get_handler();
     break;

     default:
     other_handler();
     break;
     }

     function post_handler() {
 //    $raw_data = file_get_contents("php://input");
 //    $req_body = json_decode($raw_data, TRUE);
 //    $giornosel = call_user_func($req_body['function'], $req_body['giornosel']);
       $giornosel  = $_POST['giornosel'];
       echo"(POST method) "; //only for testing
       echo"$giornosel"; //only for testing
      }

     function get_handler() {
     $giornosel  = $_GET['giornosel'];
     echo"(GET method) "; //only for testing
     echo"$giornosel"; //only for testing
     }

    function other_handler() {
    $giornosel  = $_REQUEST['giornosel'];
    echo"REQUEST"; //only for testing
    echo"$giornosel"; //only for testing
    }

// This first query populate the div of the enabled hour cells   
    $query = DB_Query("SELECT * FROM $table21n WHERE enabled = '1' AND fascia ='1'  ORDER BY orario ASC");

    while ($result = DB_Get_Results($query))
    {

    $div_id = $result[orario];

// this second query check the hours in DB that are available or not with a simple count. If available, the radio button is displayed, otherwise not.
    $count = mysql_query("SELECT COUNT(id) FROM $table20n WHERE orario = '$div_id' AND giorno = '$giornosel' ");
    $res_count = mysql_fetch_row($count);
    $totale = $res_count[0];

    if($totale >= $valore) {
    $disabled = invisible; // some css class
    $bgcolor = BGoccupato;
    }
    else {
         $disabled = '';
         $bgcolor = 'BGlibero';
         }

    $conto = ($valore-$totale);

    echo"<div id='$div_id' class='centopercento $bgcolor' >";

    $ore = substr($div_id, 0,2);
    $min =substr($div_id, 2,4);

    echo"$ore:$min</br>";

    echo"<input class='$disabled radiorario' type='radio' value='$div_id' name='orario' id='$div_id'>";
    echo"</div>";
    }

?>

У меня были проблемы с заголовками, поэтому я попытался также изменить заголовки (принять, тип содержимого, тип данных), но результат тот же. Это значение отправляется правильно как в методе GET, так и в методе POST, как я вижу на панели Firebug, пара параметров верна, ответ в полезной нагрузке правильный, но не запускается на веб-странице.

В заключение считаю, что дата, выбранная календарем, отправлена ​​правильно. Но я не уверен, что будет дальше. на странице PHP читать значение? Как правильно передать прочитанное значение и использовать его для обновления страницы? Могу ли я отправить запрос через javascript или ajax на ту же страницу?

Это веб-страница, на которой я работаю test

Любое предложение тепло ценим! Спасибо!

ОБНОВЛЕНИЕ 11/01/2019

Это полный код страницы prenota.php, обновленной в соответствии с предложением ниже

<?php
session_start();
?>
<!DOCTYPE HTML>
<html lang="it">
<head>
<meta charset="UTF-8">
<title>prenota</title>
<meta name="viewport" content="width = device-width, initial-scale = 1.00, minimum-scale = 0.25, maximum-scale = 2.20">
<style type="text/css">
<!--
OMITTED
-->
</style>
<script type="text/javascript">

$(document).ready(function() {

if(sessionStorage.getItem("homecal") === null || sessionStorage.getItem("prenotacal") === null) {
    $('#datasel').html('Seleziona la data della visita dal calendario.');
    $('#prenota-ora').hide();
}

if(sessionStorage.getItem("homecal") !== null) {
    $('#datasel').html('Hai selezionato il giorno ' + sessionStorage.getItem("homecal"));
    $('#giornosel').val(sessionStorage.getItem("homedate")); //scrive la data nell'input hidden
    $('#prenota-ora').show();
}

if(sessionStorage.getItem("prenotacal") !== null) {
    $('#datasel').html('Hai selezionato il giorno ' + sessionStorage.getItem("prenotacal"));
    $('#prenota-ora').show();
}

var homedate    = sessionStorage.getItem("homedate");

var days        = new Date(homedate);
var NumDays     = ['0', '1', '2', '3', '4', '5', '6'];
var dayNum  = NumDays[days.getDay()];

if(homedate !== null && dayNum == '1' || dayNum == '3' || dayNum == '5') { //lunedi e mercoledi e venerdi
    $('#orari-mattina').hide();
    $('#orari-pomeriggio').fadeIn('1000');
    $('#avanti').hide();
    }
if(homedate !== null && dayNum == '2' || dayNum == '4') { //martedi e giovedi
    $('#orari-mattina').fadeIn('1000');
    $('#orari-pomeriggio').fadeIn('2000');
    $('#avanti').hide();
    }

var anno        = new Date().getFullYear();

$('#datepicker').datepicker({ 
    format: "yyyy-mm-dd",
    language: "it",
    keyboardNavigation: false,
    forceParse: false,
    daysOfWeekDisabled: "0,1,4,6",
    todayHighlight: true,
    startDate: "-0m",
    immediateUpdates: true,
    toggleActive:true,
    datesDisabled: ['2019-01-01', '2019-01-02', '2019-01-03', '2019-01-04', '2019-01-05', '2019-01-06', '2019-01-07', '2019-01-09', '2019-01-11', '2019-01-12', '2019-01-13', 'anno-01-01', 'anno-01-02', 'anno-01-03', 'anno-01-04', 'anno-01-05','anno-01-06','anno-01-07', 'anno-01-09', 'anno-01-11', 'anno-01-12', 'anno-01-13', 'anno-04-02', 'anno-04-25', 'anno-04-30', 'anno-05-01', 'anno-06-02', 'anno-06-08', 'anno-06-11', 'anno-08-01', 'anno-08-02', 'anno-08-03', 'anno-08-04', 'anno-08-05', 'anno-08-06', 'anno-08-07', 'anno-08-08', 'anno-08-09', 'anno-08-10', 'anno-08-11', 'anno-08-12',  'anno-08-13', 'anno-08-14', 'anno-08-15', 'anno-08-16', 'anno-08-17', 'anno-08-18', 'anno-08-19', 'anno-08-20', 'anno-08-21', 'anno-08-22', 'anno-08-23', 'anno-08-24', 'anno-08-25', 'anno-08-26', 'anno-08-27', 'anno-08-28', 'anno-08-29', 'anno-08-30', 'anno-08-31', 'anno-11-01', 'anno-12-07', 'anno-12-08', 'anno-12-09', 'anno-12-24', 'anno-12-25', 'anno-12-26', 'anno-12-27', 'anno-12-29', 'anno-12-30', 'anno-12-31', ]

 }).on('changeDate', function() {

$('#prenota-ora').show();
$('#orari-mattina').hide();
$('#orari-pomeriggio').hide();
$('#avanti'). hide();
$('input[name="orario"]').prop('checked', false); //resetta orario
$('#orario').val(""); //resetta orario

sessionStorage.removeItem("homecal");
sessionStorage.removeItem("homedate");
sessionStorage.removeItem("orarioselezionato");
$('#orariosel').html(""); //resetta orario

sessionStorage.setItem("prenotadate", $('#datepicker').datepicker('getFormattedDate'));   // CREA SESSIONE DEL GIORNO HOME FORMATO DATE

var values = sessionStorage.getItem("prenotadate");

          var days      = new Date($('#datepicker').datepicker('getFormattedDate'));
      var NumDays   = ['0', '1', '2', '3', '4', '5', '6'];
      var dayNum    = NumDays[days.getDay()];

      if(dayNum == '1' || dayNum == '3' || dayNum == '5') { //lunedi e mercoledi e venerdi
      $('#orari-pomeriggio').fadeIn('1000');
      }
      if(dayNum == '2' || dayNum == '4') { //martedi e giovedi
//    $('#orari-mattina').fadeIn('1000');
      $('#orari-pomeriggio').fadeIn('2000');
      }

$.ajax({
    type: "GET",
    url: "prenotazione/prenota.php",
    data: { giornosel:values },
    dataType:"json",
    success: function(data){
        console.log(data);
        if(data.elememts.length){
            $.each(data.elements, function(i, el){
                var myEl = $("<" + el.tag + ">", el.attr);
                if(el.content != undefined){
                    myEl.html(el.content);
                }
                if(el.appendTo != undefined){
                myEl.appendTo(el.appendTo);
                } else {
                myEl.appendTo($('#orari'));
                }
            });
        }
    },
    error: function(xhr, textStatus, errorThrown) {
        console.log("Ajax Error: " + textStatus, errorThrown);
    }
});


var monthNames = ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre",  "Novembre", "Dicembre"];

var d               = new Date(sessionStorage.getItem('prenotadate'));
var day                 = d.getDate();
var monthIndex      = d.getMonth();
var year                = d.getFullYear();
var prenotacal  = day + ' ' + monthNames[monthIndex] + ' ' + year;

$('#datasel').html('Hai selezionato il giorno ' + prenotacal);

sessionStorage.setItem("prenotacal", prenotacal);   // CREA SESSIONE DEL GIORNO HOME FORMATO CALENDARIO 

}); //END ONCHANGE

$('input:radio[name=orario]').change(function() {

var orario = $('input:radio[name=orario]:checked').attr('id');
$('#orario').val(orario);

var ore     = orario.substr(0,2);
var min     = orario.substr(2,4);

var orarioselezionato   = ore + ':' + min;

sessionStorage.setItem("orarioselezionato", orarioselezionato); // crea sessione formato ora
sessionStorage.setItem("orario", orario); // crea sessione formato tabella

if(sessionStorage.getItem("orarioselezionato") === null) {}
else {
$('#orariosel').html(', alle ore ' + sessionStorage.getItem("orarioselezionato"));
}

if(sessionStorage.getItem("orarioselezionato") !== null && (sessionStorage.getItem("prenotadate") !== null || sessionStorage.getItem("homedate") !== null)) {
$('#avanti').show();
} else {}

}); // END CHANGE FUNCTION
}); // END READY FUNCTION
</script>
</head>
<body>
<form action="index.php?a=prenotazione-online&go=compila-dati" method=post>
<div id="PageDiv">
    <div id="prenota"><div id="prenota-selezione" class="text-center"><p class="f-fp f-lp"><span class="occhiello"><strong><span class="COL-blu">     <span id='datasel'></span><span id='orariosel'></span>  </span></strong></span></p>
        </div>
        <div id="prenota-giorno" class="col-xs-12 col-md-4"><div id="prenota-giorno-title" class="uppercase"><h2 class="f-fp f-lp"><span class="COL-blu">1° - seleziona il giorno</span></h2>
            </div>
            <div id="datepicker"></div>
        </div>
        <div id="prenota-ora" class="col-xs-12 col-md-8 prenota-ora"><div id="prenota-ora-title" class="uppercase"><h2 class="f-fp f-lp"><span class="COL-blu">2° - seleziona l'orario <?php
switch ($_SERVER['REQUEST_METHOD']) {
    case 'POST':
        post_handler();
        break;
    case 'GET':
        get_handler();
        break;
    default:
        other_handler();
        break;
}

$handler = array();
function post_handler() {
    $giornosel  = $_POST['giornosel'];
    $handler['method'] = "post";
    $handler['query'] = $giornosel;
}
function get_handler() {
    $giornosel  = $_GET['giornosel'];
    $handler['method'] = "get";
    $handler['query'] = $giornosel;
}
function other_handler() {
    $giornosel  = $_REQUEST['giornosel'];
    $handler['method'] = "request";
    $handler['query'] = $giornosel;
}
$data = array('handler' => $handler);

?> </span></h2>
            </div>
            <div id="orari"><div id="orari-mattina"><div id="titolo-mattina" class="uppercase col-xs-12 col-md-12"><h3 class="style2 f-fp f-lp">mattino</h3>
                    </div>
                    <div id="content-mattina"><p class="f-fp"><?php
$query = DB_Query("SELECT * FROM $table21n WHERE enabled = '1' AND fascia ='1'  ORDER BY orario ASC");
while ($result = DB_Get_Results($query))
{
$div_id = $result[orario];

$data['elements'] = array();

?></p>
                        <div id="ora-<?php echo"$div_id";?>" class="cella-orario col-xs-4 col-md-1 text-center"><p class="f-fp f-lp"><span id="oramattina"><?php
$count = mysql_query("SELECT COUNT(id) FROM $table20n WHERE orario = '$div_id' AND giorno = '$giornosel' ");
$res_count = mysql_fetch_row($count);
$totale = $res_count[0];


//    echo"$div_id</br>"; // only for test
//    echo"$totale</br>"; // only for test
//    echo"$valore"; // only for test

if($totale >= $valore) {
    $disabled = invisible;
    $bgcolor = BGoccupato;
}
else {
    $disabled = '';
    $bgcolor = BGlibero;
}
    $ore = substr($div_id, 0,2);
    $min = substr($div_id, 2,4);

array_push($data['elements'], array(
        "tag" => 'div',
        "attr" => array(
            "id" => $div_id,
            "class" => "centopercento $bgcolor"
        ),
        "content" => "$ore:$min"
    ));
array_push($data['elements'], array(
        "tag" => 'input',
        "attr" => array(
            "type" => 'radio',
            "id" => $div_id,
            "class" => "$disabled radiorario",
        "value" => $div_id,
        "name" => 'orario'
        ),
       "appendTo" => '#' . $div_id
    ));
?></span></p>
                        </div>
                        <p class="f-lp"><?php
json_encode($data);

}
?></p>
                    </div>
                </div>
                <div id="orari-pomeriggio"><div id="titolo-pomeriggio" class="uppercase col-xs-12 col-md-12"><h3 class="style2 f-fp f-lp">pomeriggio</h3>
                    </div>
                    <div id="content-pomeriggio"><p class="f-fp"><?php
$query = DB_Query("SELECT * FROM $table21n WHERE enabled = '1' AND fascia ='2'  ORDER BY orario ASC");
while ($result = DB_Get_Results($query))
{
$div_id = $result[orario];

$data['elements'] = array();

?></p>
                        <div id="ora-<?php echo"$div_id";?>" class="cella-orario col-xs-4 col-md-2 text-center"><p class="f-fp f-lp"><span id="orapomeriggio"><?php
$count = mysql_query("SELECT COUNT(id) FROM $table20n WHERE orario = '$div_id' AND giorno = '$giornosel' ");
$res_count = mysql_fetch_row($count);
$totale = $res_count[0];


//    echo"$div_id</br>"; // only for test
//    echo"$totale</br>"; // only for test
//    echo"$valore"; // only for test

if($totale >= $valore) {
    $disabled = invisible;
    $bgcolor = BGoccupato;
}
else {
    $disabled = '';
    $bgcolor = BGlibero;
}
    $ore = substr($div_id, 0,2);
    $min = substr($div_id, 2,4);

array_push($data['elements'], array(
        "tag" => 'div',
        "attr" => array(
            "id" => $div_id,
            "class" => "centopercento $bgcolor"
        ),
        "content" => "$ore:$min"
    ));
array_push($data['elements'], array(
        "tag" => 'input',
        "attr" => array(
            "type" => 'radio',
            "id" => $div_id,
            "class" => "$disabled radiorario",
        "value" => $div_id,
        "name" => 'orario'
        ),
       "appendTo" => '#' . $div_id
    ));
?></span></p>
                        </div>
                        <p class="f-lp"><?php
json_encode($data);

}
?></p>
                    </div>
                </div>
            </div>
        </div>
        <div id="avanti" class="text-center"><p class="f-fp f-lp">Se vuoi confermare clicca su <input id="avanti-button" type=submit name="invia" value="Prosegui" class="btn btn-yellow"></p>
        </div>
    </div>
</div>
</form>
</body>
</html>

Эхо json_encode($data); теперь хорошо структурировано, но плохо форматирует HTML-код этой части страницы.

Сомнение заключается в следующем: структура массива заменяет структуру html (divs и т. Д.) Или должна быть добавлена ​​как скрытая структура только для отправки значений JSON?

Ещё одно из моих сомнений в том, может ли эта страница вызывать себя через ajax call.

Другое обновление

После вызова ajax мое значение даты (т.е. 2019-01-18) отправляется с:

$.ajax({
    type: "GET",
    url: "prenotazione/dataencode.php",
    data: { giornosel:values },
    dataType:"json",
    contentType:"application/json",
    success: function(data){            
        console.log(data);
        if(data.elements.length){
            $.each(data.elements, function(i, el){
                var myEl = $("<" + el.tag + ">", el.attr);
                if(el.content != undefined){
                    myEl.html(el.content);
                }
                if(el.appendTo != undefined){
                    myEl.appendTo(el.appendTo);
                } else {
                    myEl.appendTo($('#prenota-ora'));
                }
            });
        }
    },
    error: function(xhr, textStatus, errorThrown) {
        console.log("Ajax Error: " + textStatus, errorThrown);
    }
});

в dataencode.php файл:

<?php
header("Content-Type: application/json");

$giornosel  = $_REQUEST['giornosel'];

$input = array("giorno" => $giornosel);

echo json_encode($input);

$encoded_array = json_encode($input);
file_put_contents("values.json", $encoded_array);

?>

, которые преобразуют значение в объект JSON, хорошо отформатированный и отображаемый как

{"giorno":"2019-01-18"}

на панели консоли firebug и запишите значение в файл values.json.

Затем файл datadecode.php:

<?php
$url = "prenotazione/values.json";
$input = file_get_contents($url);
if(!isset($input))
    {
    echo"error";
    }
else {
    $result = json_decode($input, true);

    $giornosel = $result[giorno];

   echo"$giornosel";
    }
?>

декодирует значение в строку php.

Этот файл включен с include('prenotazione/datadecode.php'); на главной странице prenota.php.

Теперь я хотел бы «обновить» или «загрузить» или «обновить» только div #prenota-ora, где php-запрос заполняет страницу

$count = mysql_query("SELECT COUNT(id) FROM $table20n WHERE orario = '$div_id' AND giorno = '$giornosel' ");
$res_count = mysql_fetch_row($count);
$totale = $res_count[0];


if($totale >= $valore) {
$disabled = invisible;
$bgcolor = BGoccupato;
}
else {
$disabled = '';
$bgcolor = 'BGlibero';
}

Я пытался загрузить div с помощью $("#prenota-ora").load(); после успешной функции () в вызове ajax, но безуспешно. Как я могу это сделать?

1 Ответ

0 голосов
/ 11 января 2019

Как уже упоминалось в комментариях, ваш PHP-код немного устарел и может использовать более старую функцию. Я бы исследовал использование функции MySQLi по сравнению с MySQL. Также не ясно, где определяются некоторые переменные PHP, например $table21n и $table20n. Я также хотел бы рассмотреть его настройку как:

<?php
switch ($_SERVER['REQUEST_METHOD']) {
    case 'POST':
    post_handler();
    break;
    case 'GET':
    get_handler();
    break;
    default:
    other_handler();
    break;
}
$handler = array();
function post_handler() {
    $giornosel  = $_POST['giornosel'];
    $handler['method'] = "post";
    $handler['query'] = $giornosel;
}
function get_handler() {
    $giornosel  = $_GET['giornosel'];
    $handler['method'] = "get";
    $handler['query'] = $giornosel;
}
function other_handler() {
    $giornosel  = $_REQUEST['giornosel'];
    $handler['method'] = "request";
    $handler['query'] = $giornosel;
}
$data = array('handler' => $handler);
$data['elements'] = array();
// This first query populate the div of the enabled hour cells   
$query = DB_Query("SELECT * FROM $table21n WHERE enabled = '1' AND fascia ='1'  ORDER BY orario ASC");
while ($result = DB_Get_Results($query)){
    $div_id = $result[orario];
    // this second query check the hours in DB that are available or not with a simple count. If available, the radio button is displayed, otherwise not.
    $count = mysql_query("SELECT COUNT(id) FROM $table20n WHERE orario = '$div_id' AND giorno = '$giornosel' ");
    $res_count = mysql_fetch_row($count);
    $totale = $res_count[0];
    if($totale >= $valore) {
        $disabled = "invisible"; // some css class
        $bgcolor = "BGoccupato";
    }
    else {
        $disabled = '';
        $bgcolor = 'BGlibero';
    }
    $conto = ($valore - $totale);
    $ore = substr($div_id, 0,2);
    $min =substr($div_id, 2,4);
    array_push($data['elements'], array(
        'tag' => "div",
        'attr' => arrray(
            'id' => $div_id,
            'class' => "centopercento $bgcolor"
        ),
        'content' => "$ore:$min</br>"
    ));
    array_push($data['elements'], array(
        'tag' => "input",
        'attr' => array(
            'type' => "radio",
            'id' => $div_id . "-input",
            'class' => "$disabled radiorario",
            'value' => $div_id,
            'name' => "orario"
        ),
        'appendTo' => "#" . $div_id
    ));
}
header('Content-Type: application/json');
echo json_encode($data);
?>

Идея этого кода заключается в том, что вы можете сделать к нему запрос AJAX и получить обратно данные JSON, с которыми легче работать в JavaScript. Ожидаемый результат будет примерно таким:

{
  "handler":{
    "method":"get",
    "query":"2019-01-18"
  },
  "elements":[{
    "tag":"div",
    "attr":{
      "id":"1122",
      "class":"centopercento BGoccupato"
    },
    "content":"11:22<\/br>"
  },{
    "tag":"input",
    "attr":{
      "type":"radio",
      "id":"1122-input",
      "class":"invisible radiorario",
      "value":"1122",
      "name":"orario"
    },
    "appendTo":"#1122"
  }]
}

Затем вы можете построить элементы в jQuery следующим образом:

$.ajax({
  type: "GET",
  url: "prenotazione/prenota.php",
  data: { giornosel: values },
  dataType:"json",
  success: function(data){
    console.log(data);
    if(data.elememts.length){
      $.each(data.elements, function(i, el){
        var myEl = $("<" + el.tag + ">", el.attr);
        if(el.content != undefined){
          myEl.html(el.content);
        }
        if(el.appendTo != undefined){
          myEl.appendTo(el.appendTo);
        } else {
          myEl.appendTo($('#orariosel'));
        }
      });
    }
  },
  error: function(xhr, textStatus, errorThrown) {
    console.log("Ajax Error: " + textStatus, errorThrown);
  }
});

Таким образом, AJAX будет знать, что в случае успеха данные JSON могут быть заполнены в переменной data. Это будет рассматриваться как тип объекта и может быть легко повторено для создания необходимых тегов.

Надеюсь, это поможет прояснить несколько вещей.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...