Searching for data and viewing multiple fields using AJAX PHP

advertisements

I have been new to AJAX and i am unable to display the fetched data to 2 different elements of datepicker startdate and enddate but i was able to fetch only 1 value from ajax response. My HTML is given below

<div class="control-group" id="startingdatee">
    <label class="control-label" for="form-field-1">
        Start Date
    </label>
    <div class="controls" style="width:265px;" id="startingdate">
       <input class="span10 date-picker" id="startdate" value="" type="text" data-date-format="dd-mm-yyyy" name="startdate">
    </div>
</div>
<div class="control-group">
    <label class="control-label" for="form-field-1">
        End Date
    </label>
    <div class="controls" style="width:265px;">
        <input class="span10 date-picker" id="enddate" type="text" data-date-format="dd-mm-yyyy" name="enddate">
    </div>
</div>

Java Script is given below which is used to get the response from the dateshow.php file and could update only 1 value that is startdate only. I used document.getElementById("startdate").value = response..

function showDate(str)
{
 if (str=="")
 {
  return;
 }
 if (window.XMLHttpRequest)
 {
   // code for IE7+, Firefox, Chrome, Opera, Safari
   xmlhttp=new XMLHttpRequest();
 }
 else
 {
   // code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
   xmlhttp.onreadystatechange=function()
 {
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
   {
    document.getElementById("startdate").value = xmlhttp.responseText;
   }
 };
  xmlhttp.open("GET","dateshow.php?q="+str,true);
  xmlhttp.send();
 };

and php file is dateshow.php used to get minimum date and maximum date.

<?php include('includes/db.php');
  $q = $_REQUEST["q"];
  //echo $q;
  //$q = 41;
  $query =  "SELECT MIN(datetime) AS MIN,MAX(datetime) AS MAX
         FROM transactions
         WHERE farm_id = $q";
  $run = mysqli_query($con, $query);
  while($row = mysqli_fetch_array($run))
  {
    $mindate = $row['MIN'];
    $maxdate = $row['MAX'];
  }
  $mindatefor = strtotime($mindate);
  $startdate = date('d-m-Y',$mindatefor);
  $maxdatefor = strtotime($maxdate);
  $enddate = date('d-m-Y',$maxdatefor);
  echo $startdate;//."#".$enddate;
  ?>


Try creating an array in the php script and json encoding it.

$returnData = ['start'=> $startDate, 'end'=> $endDate];
echo json_encode($returnData);

Then, when you retrieve the data using AJAX, do JSON.parse(xmlhttp.responseText)

This will return a javascript object that should look like this

{
    start: some start data,
    end: some end data
}