Search code examples
phpjavascriptjqueryjsonstringify

How can I retrieve json stringified objects in php?


I sent some data to the server using the code snippet below, but I do not know how to retrieve the returned array using PHP. Thanks for any suggestion.

$('.ticket-row').each(function() {
tickets.push({ id : $(this).attr('id'),
              no : $(this).find('#no').text(),
              c_name : $(this).find('#c_name').val(),
              next_of_kin: $(this).find('#next_of_kin').val(),
              address : $(this).find('#address').val(),
              seat_no : $(this).find('#seat_no').val(),
              fare : $(this).find('#fare').val() });
});

$.ajax({
    type : 'POST',
    url : '**URL_HERE**',
    data : JSON.stringify(tickets),
    dataType : 'json'
});

Solution

  • I think you want to use something like

    'posted_data=' + encodeURIComponent(JSON.stringify(tickets))
    

    Then, on the PHP side you can get it with

    $posted_data = $_POST['posted_data'];
    $data = json_decode($posted_data);
    

    Instead of using JSON.stringify, you could also use the JSON as the data and jQuery will convert it to a query string as part of the request. Then, you can use the individual components in $_POST.