Hi I'm newbie in JSON and Ajax and my question is probably quite stupid but when learning, also the stupid questions are fundamental.
I need to pass two parameters via Ajax (giorno and periodo),
for example 'giorno' = 2017-05-10 and 'periodo' = 2:
$.ajax({
type:'POST',
data: JSON.stringify({
giorno: $('#dataselezionata').val(),
periodo: $('input:radio[name=periodo]:checked').val()
}),
contentType: "application/json; charset=utf-8",
dataType : 'json',
url:'http://www.rinnovipatenti.com/index2.php?a=prenotazione'
});
The JSON object passed perfectly and the result in Firebug Console is:
{"giorno":"2017-05-10","periodo":"2"}
If I try to manually copy and paste the object on the php page like this:
<?
$json = '{"giorno":"2017-05-10","periodo":"2"}'; //pasted manually
$json = json_decode($json, TRUE);
$giorno = $json['giorno'];
$periodo = $json['periodo'];
echo"$giorno"; //2017-05-10
echo"$periodo"; //2
?>
the two echoes show me the values. OK!
My problem start and stop here. I'm not able to bring the JSON object to be decoded.
I'm quite sure is a stupid solution but I don't know how to do that.
I need to create a function that wrap the Ajax call and then call the function in json_decode??
PS I also tried to simply get the values with "$_POST['giorno']" etc.. instead of using JSON but without success.
Can someone help me please? Thank you for your patience.
UPDATE 10/05/2017
Hi I've followed your suggestions so I tried one time more to simplify the code like this:
$('input:radio[name=periodo]').change(function() {
var giorno = document.getElementById("dataselezionata").value; // from datepicker
var periodo = $('input:radio[name=periodo]:checked').val(); // from radio button
var post_data = ("giorno="+giorno+"&periodo="+periodo);
$.ajax({
type:'GET',
data: post_data,
url:"http://www.rinnovipatenti.com/prenota/prenotazione.php",
});
if (this.value == '1') {
$('#orario').show();
$('#orari-mattina').show();
$('#orari-pomeriggio').hide();
}
else if (this.value == '2') {
$('#orario').show();
$('#orari-pomeriggio').show();
$('#orari-mattina').hide();
}
using GET method instead of the POST one and in the PHP page prenotazione.php the code now is:
<?
$giorno = $_GET['giorno'];
$periodo = $_GET['periodo'];
echo"$giorno";
echo"$periodo";
?>
In Firebug console the parameters are ok
giorno 2017-05-10
periodo 2
the formatted link is:
http://www.rinnovipatenti.com/prenota/prenotazione.php?giorno=2017-05-10&periodo=2
the html console preview works correctly but the page don't. I'm in the corner! Is very strange. I have only one doubt: can I send data by GET/POST method to the same page where the data are collected? In other word can the page foo.php send data to foo.php like a cycle without refresh? And the ajax call could be wrapped inside the .change function or must be outside?