简体   繁体   中英

I'm trying to get value in javascript to return it in PHP in JSON format

I created a date selection function with display of the choice at the bottom (Second box in green). I would now like to be able to retrieve the user's choice in PHP and then send it in JSON format. Thank you in advance for any suggestion or help.

enter image description here

Here's my code:

    function setToSelected(me){
const x = document.querySelector("span.active");
if (x !== null) {
x.classList.remove("active");
}
me.className='active';
console.log(me.id);
var dateselected=me.id.split('-')
var day=dateselected[0].split('_')[0]
var daynum=dateselected[0].split('_')[1]
var month=dateselected[0].split('_')[2]
switch(day){
    case 'lun':
        day='Lundi'
    break;
    etc...
default:
console.log("erreur conversion day")
}

switch(month){
    case 'jan':
        month='Janvier'
    break;
    case 'fev':
        month='Fevrier'
    break;
    
default:
console.log("erreur conversion month")
}
document.getElementById("dateselected").innerHTML = "Selected restart date : "+day+" "+daynum+" "+month+" à "+dateselected[1]+"h"
}

});

So we have 2 technologies at work here, Javascript working in your front end and php working server side. To retrieve data server side in php you`ll need to do a post request to a php page from your front end because php is only executed serverside and not frontend. Steps as follows

  1. get your date info in javascript
  2. prepare data to send
  3. send data to php page via xhr request

Example

// Step 1
 var selecteddate = day+" "+daynum+" "+month+" "+dateselected[1]+"h";
// Now we have our javascriptobject called selecteddate;

// set target php page to post to
  var url = "datereceiver.php";

// Step 2 create a post object 
  var dataToSend = {"fontenddate": selecteddate };   

// Step 3 set request paramaters
  var xhr = new XMLHttpRequest();
  xhr.open("POST", url);
  xhr.setRequestHeader("Accept", "application/json");
  xhr.setRequestHeader("Content-Type", "application/json");
 // send request
  xhr.send(selecteddate);

 // set callback function to capture response from your php page(server)
  xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
 // check response code
    console.log(xhr.status);
 // get your response from your php page
    console.log(xhr.responseText);
   }};

On the php side your (datereceiver.php) page can look something like

<?php 
if($_SERVER["REQUEST_METHOD"] == "POST") { 
    $yourselecteddate = $_POST['frontenddate'];
    $response = "date received";
   } 
else{
     $response = "bad request";
}
 // set response headers 
header('Content-type: application/text'); 
 echo $response;
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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