0

I am trying to use the data that AJAX sends in PHP but for some reason says that the array is empty I also don't get any errors from PHP or in my console. the console.log(data) shows the array with with the values of the selects. After the PHP there is HTML where the script.js is.console.logconsole.log

index.php

 <?php
    error_reporting(-1);
    $value1 = "";
    $value2 = "";
    print_r($_POST); 
    if (isset($_POST['date']) && isset($_POST['date'])) {
        if (isset($_POST['date'])) {
            echo "Yes, mail is set";
            $value1 = $_POST['date'];
            $value2 = $_POST['quantity'];
        } else {
            echo "No, mail is not set";
        }
        exit;
    }
    echo $value1; 
    echo $value2;
    $canmakereservation = "https://www.planyo.com/rest/?method=can_make_reservation&api_key=YOURKEY&resource_id=110556&start_time=2018-04-25 09:00&end_time=2018-04-25 12:00&quantity=5";
    $cleancanmakereservation = preg_replace("/ /", "%20", $canmakereservation);
    $reservationavailable = file_get_contents("$cleancanmakereservation");
    $reservationAvailable = json_decode($reservationavailable, true);
    // echo "$cleancanmakereservation";
    // var_dump($reservationAvailable);
 ?>

script.js

$(document).ready(function(){

var date = "date";
var begin = "begin";
var eind = "eind";
var aantal = "aantal";


$('#datum').change(function() {
  date = $("#datum").val();
  console.log(date);
});
$('#beginTijd').change(function(){
    begin =( $(this).val() ); 
    console.log(begin);      
});
$('#Tijdsduur').change(function(){
    eind =( $(this).val() ); 
    console.log(eind);      
});
$('#aantalSloepen').change(function() {
aantal = ($(this).val());
console.log(aantal);
  $.ajax({
      type: "POST",
      url: "index.php",
      data: {
          date: begin,
          quantity: aantal
      },
      success: function(data) {
          alert(data);
          console.log(data);
      }
  });
});
});
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
berto
  • 51
  • 10
  • 1
    Does the `exit;` in index.php stop the code? – Nigel Ren Mar 28 '18 at 09:44
  • _Small Point_ `if (isset($_POST['date']) && isset($_POST['date'])) {` you should probably be testing `$_POST['quantity']` rather than testing `date` twice – RiggsFolly Mar 28 '18 at 09:47
  • What do you mean, `shows empty`? I can clearly see the output of the `var_dump()` in your console output. – jeroen Mar 28 '18 at 09:47
  • I can see values of `date` and `quantity` from your console image – Pankaj Makwana Mar 28 '18 at 09:48
  • It also look like you are passing a TIME and not a DATE – RiggsFolly Mar 28 '18 at 09:48
  • All your test `echo`'s are getting in the way of what is getting send back to the javascript. – RiggsFolly Mar 28 '18 at 09:52
  • the var_dump() shows in my console but I want it to show in my php @jeroen – berto Mar 28 '18 at 10:00
  • 2
    i think if php doesn't return a `json`. `echo`. and `return` are equivalent. So it cannot be faulted with string ! except other variable type – An Pham Karion Co.Ltd Mar 28 '18 at 10:03
  • You misunderstand how an ajax call works: All output of your php script is stored in the `data` variable in the `success` function. So what you are seeing is really php's `print_r()`. Because it is an ajax call, the screen in your browser does not change, you will not see a blank screen with your php output like you perhaps expect. – jeroen Mar 28 '18 at 10:03
  • so you are saying that I can never use the ajax data in php to make it use with file_get_contents function @jeroen – berto Mar 28 '18 at 10:09
  • No, you can do anything you want like you would with a regular request but you'll have to check the results in the console. – jeroen Mar 28 '18 at 10:41
  • How do I check the results in my console? do you have an example? – berto Mar 28 '18 at 10:49

2 Answers2

2

First! There are duplicate conditions isset($_POST['date']) (3 times) in your code:

 if (isset($_POST['date']) && isset($_POST['date'])) {
        if (isset($_POST['date'])) {
            echo "Yes, mail is set";
            $value1 = $_POST['date'];
            $value2 = $_POST['quantity'];
        } else {
            echo "No, mail is not set";
        }
        exit;
    }

Second! You should remove exit; and try again!

Third: You should check your variable type, if your $value1 and $value2 is not a string, numeric. echo is false. try with return

EDIT:

Try this, it worked for me! the .php destination:

$value1 = "";
$value2 = "";
if (isset($_POST['date']) && isset($_POST['quantity'])) {

        echo "Yes, mail is set";
        $value1 = $_POST['date'];
        $value2 = $_POST['quantity'];
    }
    else {
        echo "No, mail is not set";
}
echo $value1;
echo $value2;

The ajax:

enter image description here

The result

enter image description here

0

Check the ContentType header in the AJAX request. It could be that it is being sent as JSON and PHP doesn't deserializer that into the $_POST array. It may need to be sent as serialized form data, like in this example.

In my experience (albeit in .NET), if data isn't being picked out of the request by the server it's usually that the ContentType header isn't set correctly for how you're passing the data so the server doesn't understand how to pull it out.

Edit: You can control this by setting contentType property in options object passed to $.ajax, the default is apparently 'application/x-www-form-urlencoded; charset=UTF-8' and when you pass an object to the data property, according to the processData property, the default behaviour is to serialize this into a query string, fitting the default contentType. Source: jQuery docs.

So my mistake, looks like that should all be matching up, though I do usually like to be explicit with specifying these properties to avoid any confusion.

benmccallum
  • 1,241
  • 12
  • 27
  • I think with his code ! It only send a Post request. doesn't it? – An Pham Karion Co.Ltd Mar 28 '18 at 09:57
  • He's definitely sending a POST request, but the [ContentType header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) that goes along with it describes to the server how the data is being sent in that request (e.g. as JSON, form-encoded, etc.). You can control this by setting `contentType` in options object passed to [`$.ajax`](http://api.jquery.com/jquery.ajax/), the default is `'application/x-www-form-urlencoded; charset=UTF-8'` which may not align with the raw object passed in the `data` property. – benmccallum Mar 28 '18 at 10:05
  • i think his variables is not string or numeric. it may be an object ! so echo false. xD – An Pham Karion Co.Ltd Mar 28 '18 at 10:07
  • I set the contentType to the default 'application/x-www-form-urlencoded; charset=UTF-8' but it does not make a difference. – berto Mar 28 '18 at 10:21