简体   繁体   English

在datepicker onchange函数之后,使用javascript / ajax调用将值发送到同一php页面,而无需刷新

[英]After datepicker onchange function, send value to same php page with javascript/ajax call without refresh

I'm trying to populate a portion of PHP page in a div where results are retrieved from a Mysql DB after a datepicker calendar onchange function. 我正在尝试在div中填充PHP页面的一部分,在该位置中,从datepicker日历onchange函数之后从Mysql DB检索结果。 Every time I select a date from calendar, I would see the hours available. 每当我从日历中选择一个日期时,我都会看到可用的小时数。 My concept is: 1. I choose a date 2. a div with the hours table appear with availability 3. select a radio button of the disponible hour, then send my choose to the db. 我的概念是:1.我选择一个日期2.带有小时表的div随即出现,并带有可用性3.选择一个不适用小时的单选按钮,然后将我的选择发送到数据库。

The problem is at point 2. 问题出在第二点。

This is the javascript code inside the page, just before the head close 这是页面内的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

I tried lot of times different solutions to send data to php page as ajax call GET/POST method also with JSON datatype but it run sometimes correctly only on firebug panel, not on web page. 我尝试了很多次不同的解决方案来将数据作为JSON数据类型的ajax调用GET / POST方法发送到php页面,但有时只能在Firebug面板上正确运行,而不是在网页上正确运行。

The portion of PHP that manage the hours is: 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>";
    }

?>

I had a trouble about headers so I tried also to change headers (accept, content-type, data-type) but the result is the same. 我在标题上遇到麻烦,因此我也尝试更改标题(接受,内容类型,数据类型),但结果是相同的。 The value is sent correctly both on GET and POST method as I can see on the firebug panel, the parameter pair is correct, the response in the payload is correct but doesn't run on the web page. 正如我在萤火虫面板上看到的那样,该值已在GET和POST方法上正确发送,参数对正确,有效负载中的响应正确,但未在网页上运行。

In conclusion I think that the date selected by the calendar is sent correctly. 总之,我认为日历选择的日期已正确发送。 But I'm not sure what happens next. 但是我不确定接下来会发生什么。 the PHP page read the value? PHP页面读取值? How the sent value can be read correctly and used to update the page? 如何正确读取发送的值并将其用于更新页面? Can I send a request via javascript or ajax to the same page? 我可以通过javascript或ajax将请求发送到同一页面吗?

This is the web page where I'm working test 这是我正在测试的网页

Any suggestion is warmly appreciate! 任何建议都将不胜感激! Thank you! 谢谢!

UPDATE 11/01/2019 更新11/01/2019

This is the full code of the prenota.php page updated following the below suggestion 这是按照以下建议更新的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>

The echo of the json_encode($data); json_encode($data); is now well structured but doesn't format well the html of that portion of page. 现在结构良好,但页面那部分的html格式不正确。

The doubt is: the array structure replace the html structure (divs etc..) or must be added as a hidden structure only to send JSON values? 疑问是:数组结构替换html结构(divs等。)还是必须添加为隐藏结构才能发送JSON值?

Another one of my doubts is if this page can call itself via ajax call. 我的另一个疑问是,该页面是否可以通过ajax调用自身。

Other update 其他更新

After the ajax call my date value (ie 2019-01-18) is sent with: 在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);
    }
});

to a dataencode.php file: 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);

?>

that convert the value in a JSON object, well formatted and echoed like 转换JSON对象中的值,格式正确并回显为

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

on the firebug console panel, and write the value in a values.json file. 在Firebug控制台面板上,然后将值写入values.json文件中。

Then the datadecode.php file: 然后是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";
    }
?>

decode the value to a php string. 将值解码为php字符串。

This file is included with an include('prenotazione/datadecode.php'); 该文件包含在include('prenotazione/datadecode.php'); on the main page prenota.php . 在主页prenota.php

Now I would to "update" or "load" or "refresh" only a div #prenota-ora where the php query populate the page 现在,我将仅对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';
}

I tried to load the div with $("#prenota-ora").load(); 我试图用$("#prenota-ora").load();加载div $("#prenota-ora").load(); after success function() in the ajax call but without success. 在ajax调用中成功执行function()之后,但未成功。 How can I do? 我能怎么做?

As mentioned in the comments, your PHP code is a bit dated and may be using older function. 如评论中所述,您的PHP代码有点陈旧,可能正在使用较旧的功能。 I would investigate using MySQLi function versus MySQL. 我将调查使用MySQLi函数与MySQL。 It's also not clear where some of the PHP variable are define, like $table21n and $table20n . 还不清楚一些PHP变量的定义位置,例如$table21n$table20n I would also consider configuring it like: 我也考虑将其配置为:

<?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);
?>

The idea with this code is that you can make an AJAX request to it and get back JSON data that is easier to work with in JavaScript. 这段代码的想法是,您可以向其发出AJAX请求并获取更易于在JavaScript中使用的JSON数据。 The expected result would be something like: 预期的结果将是这样的:

{
  "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"
  }]
}

You can then build the elements in jQuery like this: 然后,您可以像这样在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);
  }
});

This way the AJAX will know to expect JSON data that can be populated in the data variable upon success. 这样,AJAX将知道期望成功后可以在data变量中填充的JSON数据。 This will be treated like an Object type and can be easily iterated to build the needed tags. 这将被视为对象类型,并且可以轻松地进行迭代以构建所需的标签。

Hope this helps clarify a few things. 希望这有助于澄清一些事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM