1

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?

Ric
  • 11
  • 8
  • This might help you: http://stackoverflow.com/a/42652935/1654226 – squgeim May 09 '17 at 11:18
  • 2
    In your ajax call, you don't need to stringify, jquery will handle that, just pass the object. In your PHP, use `$_POST['giorno']` to retrieve the data. jquery will simply post that data as any form would. You basically don't need to care about json encode/decode on either side. – M. Eriksson May 09 '17 at 11:18
  • This: `dataType : 'json'` in your ajax call tells the jquery to expect the response to be json, which is not what it returns. – M. Eriksson May 09 '17 at 11:21
  • if you stringify the data before you send it, the PHP receives one single string parameter in the $_POST variables, which looks like a string representation of your data. If you did that, you'd have to decode it again. But that's pointless because you can just remove the stringify in the first place and jQuery/PHP will sort it all out for you neatly. – ADyson May 09 '17 at 11:24
  • @Adyson I know you are right but I tried also with JSON stringify because with post (or get) method didn't work. It coul be more simple to pass data via Post and then get it in php with $_post['something']. I don't know is strange because in the firebug console seem to works good and in html page not – Ric May 09 '17 at 16:35
  • I tried also with get method to pass variables in the link like http://www.rinnovipatenti.com/index2.php?a=prenotazione&giorno=2017-05-10&periodo=2 but still works only in the firebug panel – Ric May 09 '17 at 16:47

3 Answers3

2
$.post( "http://www.rinnovipatenti.com/index2.php?a=prenotazione", {
    giorno: $('#dataselezionata').val(),
    periodo: $('input:radio[name=periodo]:checked').val()
    } );

you do not need to stringify your JSON

on PHP side you just use

$giorno = $_POST['giorno'];
$periodo    = $_POST['periodo'];

to get the values

you can use the following function. you have it already. it worked fine for me.

$('input:radio[name=periodo]').change(function() {

    var giorno = '2017-05-15';
    var periodo = '2';

    $.post( 'http://www.rinnovipatenti.com/index2.php?a=prenotazione', {
        giorno: giorno,
        periodo: periodo
        });
    /*....*/
}); 
user3804188
  • 130
  • 6
  • This doesn't help the OP with the PHP-side, though. It's only a partial answer. – M. Eriksson May 09 '17 at 11:27
  • I tried your $.post solution without stringify the JSON and using POST classic method. Works correctly only in the Firebug panel but not in html. I've just tried many days ago both on get and post methods but without success. And I don't know why. – Ric May 09 '17 at 12:36
  • The problem might be that there are quotes (that character: ") . So when you press a button with something like onclick="blafa" you have to escape the quotation marks. otherwise the html syntax is invalid. – user3804188 May 09 '17 at 12:50
  • The post call is sent after $('input:radio[name=periodo]').change(function() {.. ajax call etc... – Ric May 09 '17 at 13:06
  • what did firebug say? – user3804188 May 09 '17 at 15:35
  • @user3804188 With post method like this: $.post( 'http://www.rinnovipatenti.com/index2.php?a=prenotazione', { giorno: $('#dataselezionata').val(), periodo: $('input:radio[name=periodo]:checked').val() }); the Parameters are: giorno 2017-05-10 - periodo 2 and in the html firebug preview works perfect but not in the html page. I also checked all the doublequote (") but there aren't. If you want you can try by clicking http://www.rinnovipatenti.com/index2.php?a=prenotazione and selecting 2017-05-10 as data and period 2 (green box). Some hour box could be red (16:00, 17:15, 17:30) – Ric May 09 '17 at 16:20
  • @user3804188 The only two data are a numeric data formatted like this 0000-00-00 and a numeric value (1 or 2). No others value or variables are contained in the call. – Ric May 09 '17 at 18:03
  • the $.post works fine as it is written on your page. – user3804188 May 10 '17 at 19:20
1

Method 2

You don't have to stringify the JSON object

$.ajax({
    type:'POST',
    data: {
    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' 
    });

So you php code will be like this

<?


$giorno = $_POST['giorno'];
$periodo    = $_POST['periodo'];

echo"$giorno"; //2017-05-10
echo"$periodo"; //2
?>

Method 2

If you want to stringify the JSON object then put it in a key

$.ajax({
    type:'POST',
    data: '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' 
    });

So you php code will be like this

<?
$json       = $_POST['data'];

$json       = json_decode($json, TRUE);

$giorno = $json['giorno'];
$periodo    = $json['periodo'];

echo"$giorno"; //2017-05-10
echo"$periodo"; //2
?>
Aman Rawat
  • 2,625
  • 1
  • 25
  • 40
  • Since the OP has set `dataType : 'json',`, the response should be json encoded data. – M. Eriksson May 09 '17 at 11:23
  • 2
    I'd argue that method 2 is just pointless processing - set the data, stringify it, de-stringify it, use the data. The output of the stringify/de-stringify process is identical to the input, therefore it has no purpose. – ADyson May 09 '17 at 11:25
  • @ADyson Yes but it's just for better understanding, where he is getting wrong – Aman Rawat May 09 '17 at 11:27
  • You should also remove the `contentType` from the ajax request since it's not needed. – M. Eriksson May 09 '17 at 11:52
0

When you send application/json payload to php to access that payload use:

$json = json_decode(file_get_contents('php://input'), TRUE);

As mentioned in other comments and answers if you stay with $.ajax default form encoding and don't json stringify the data then use $_POST

charlietfl
  • 170,828
  • 13
  • 121
  • 150