简体   繁体   中英

How to run ajax and post to PHP

I am trying to run an ajax script from javascript inside a PHP file :

 $(document).on('click', '.goto_date', function(){ var datechosen= $('#pickdate').val(); alert(datechosen); $.ajax({ url:"vdater.php", method:"POST", dataType:"json", data:{'datechosen':datechosen}, success:function(data){ alert('success'); } }); });
 <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> </head> <body> <div align="center"> <input type="button" name="gotodate" value="Go to date" id="gotodate" class="btn btn-danger btn-xs goto_date" /> <input type="date" name='pickdate' id='pickdate' /> </div> </body> </html>

But when I run the code nothing happens apart from the alert box referring that the ajax script is reachable in the code.. The PHP file may contain the following code:

 echo $_POST['datechosen'];

令人惊讶的是,它通过删除该行来工作:

 dataType:"json",

Try this one. It must be worked!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get Ajax Response</title>
</head>
<body>
    <div align="center">           
        <input type="button" name="gotodate" value="Go to date" id="gotodate" class="btn btn-danger btn-xs goto_date" />
        <input type="date" name='pickdate' id='pickdate'  />
   </div>

   <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

<script>

let dateBtn = document.querySelector('#gotodate');
let getDate    = document.querySelector('#pickdate');
dateBtn.addEventListener('click',(event)=>{
    event.preventDefault();
    if(getDate.value.trim() !== ""){
      console.log(getDate.value.trim());
      dateBtn.style.borderColor = "transparent"
      jQuery.ajax({
        type: "POST",
        url: "vdater.php",
        data:{
          datechosen: getDate.value.trim()
        },
        success: ((response,status, object) => {
          response = JSON.parse(response);
            if(response.status){
              alert(`Date Chosen: ${response.PickedDate}`);
            }
        })
      });
    }else{
      dateBtn.style.border = "1px solid #fb5757";
    }
  });
</script>
</body>
</html>


<?php 

if(isset($_POST['datechosen'])){
    $date = $_POST['datechosen'];
    echo json_encode(["PickedDate"=> $date,"status"=>true]);
}

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