0

I have a PHP function where I pass a variable to and it returns an array containing a start date and end date.

<?php
 function dateRangeTimeFrame($var1){
  ...

  $date['startDate'] = $startDate;
  $date['endDate'] = $endDate;

  return $date;
 }
?>

I am also trying to use this PHP function in an AJAX call so I can reuse the code. I have added this to the beginning of the page:

if (isset($_POST['dateFunction'])) {
  print_r(dateRangeTimeFrame($_POST['dateFunction']));
}

My jQuery code is as follows:

$.ajax({
    url: 'includes/functions.php',
    type: 'post',
    data: { "dateFunction": theDate},
    success: function(response) { 
        console.log(response['startDate']); 
        console.log(response.startDate); 
    }
});

My issue is that I do not know how to access the response that the php function is returning.

Here is the response I am getting from the PHP function:

Array
(
  [startDate] => 2015/01/17
  [endDate] => 2015/02/16
)

How would I go about getting these 2 vars from the PHP response?

3 Answers 3

4

You need to use JSON. Your Javascript natively understands and can parse it

if (isset($_POST['dateFunction'])) {
   echo json_encode(dateRangeTimeFrame($_POST['dateFunction']));
}

And your jQuery (note I added dataType)

$.ajax({
    url: 'includes/functions.php',
    dataType: 'json',
    type: 'post',
    data: { "dateFunction": theDate},
    success: function(response) { 
        console.log(response.startDate); 
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1
    <?php
     function dateRangeTimeFrame($var1){
      ...

      $date['startDate'] = $startDate;
      $date['endDate'] = $endDate;

      return json_encode($date);
     }

?>

jQuery

$.ajax({
    url: 'includes/functions.php',
    type: 'post',
    data: { "dateFunction": theDate},
    dataType: "json",
    success: function(response) { 
       console.log(response.startDate); 
    }
});

Comments

0
<?php
function dateRangeTimeFrame($var1) {
   // ...

   $date['startDate'] = $startDate;
   $date['endDate'] = $endDate;

   echo json_encode($date);
}
?> 

Ajax

$.ajax({
   url: 'includes/functions.php',
   type: 'post',
   data: { "dateFunction": theDate },
   success: function(response) { 
      for (var i = 0; i < response.length; i++) {
         alert(response[i].startDate);
      } 
   }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.