简体   繁体   中英

How to pass json object values to php dinamically?

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?

$.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
        });
    /*....*/
}); 

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
?>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM