JSON for PHP via AJAX

Asked

Viewed 652 times

6

I really need some help..

I have a select with the products:

<!-- panel preview -->
    <div class="col-sm-5">
        <h4>Adicionar Produtos:</h4>
        <div class="panel panel-default">
            <div class="panel-body form-horizontal payment-form">
                <div class="form-group">
                    <label for="status" class="col-sm-3 control-label">Escolha o produto</label>
                    <div class="col-sm-9">
                        <select id="status" name="status[]" class="order-type">
                          <option value="cake">Tortas Confeitadas</option>
                          <option value="lollipop">Bolos Caseiros</option>
                          <option value="dessert">Pão</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label for="amount" class="col-sm-3 control-label">Quantidade</label>
                    <div class="col-sm-9">
                        <input type="number" class="form-control" id="amount" name="amount[]" required="required">
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-12 text-right">
                        <button type="button" class="btn btn-default preview-add-button">
                            <span class="ico-plus"></span> Add
                        </button>
                    </div>
                </div>
            </div>
        </div>            
    </div> <!-- / panel preview -->

By clicking the Add button Avascript shows a "preview" of the selected products in the table below.

<div class="col-sm-7">
        <h4>Preview:</h4>
        <div class="row">
            <div class="col-xs-6">
                <div class="table-responsive">
                    <table class="table preview-table" id="example-table">
                        <thead>
                            <tr>
                                <th>Produto</th>
                                <th>Quantidade</th>
                            </tr>
                        </thead>
                        <tbody></tbody> <!-- preview content goes here-->
                    </table>
                </div>                            
            </div>
        </div>
        <div class="row text-left">
            <div class="col-xs-4">
                <h4>Total: <strong class="preview-total"></strong></h4>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12">
                <hr style="border:1px dashed #dddddd;">
                <button class="btn-block convert-table">Enviar pedido</button>
            </div>                
        </div>
    </div>

The Java responsible for doing this, is the following:

$('.preview-add-button').click(function(){
    var form_data = {};
    form_data["status"] = $('.payment-form #status option:selected').text();
    form_data["amount"] = parseFloat($('.payment-form input[name="amount[]"]').val()).toFixed(2);
    form_data["remove-row"] = '<span class="ico-cancel"></span>';
    var row = $('<tr></tr>');
    $.each(form_data, function( type, value ) {
        $('<td class="input-'+type+'"></td>').html(value).appendTo(row);
    });
    $('.preview-table > tbody:last').append(row);
    calc_total(); 
}); 

What I need, is to take the data of this "preview" and send to another view, I know I have to send in JSON, but as this data goes to another page, I believe that can not be in ajax, I’m sure?

Can someone help me send this data to PHP?

Thank you very much.

3 answers

1

Here is the solution to your problems :D

Javascript

$(document).on('click', 'ELEMENTO QUE SERA CLICADO', function() {
var formData = new FormData($('form')[0]);

$.ajax({
    url         : 'URL DO PHP QUE VAI PROCESSAR',
    method      : 'POST',
    data        : FormData,
    success: function (response) {
        console.log(response);
    }
})
.fail(function(response) {
    console.log(response);
});

});

PHP

<?php 
echo '<pre>';
print_r($_POST);
?>

Debug with what you have achieved.

0

You can create a button and post by storing the values in an array as shown below:

$('.preview-add-button').click(function() {

var itens = [];
var form_data = {};
form_data["status"] = $('.payment-form #status option:selected').text();
form_data["amount"] = parseFloat($('.payment-form input[name="amount[]"]').val()).toFixed(2);
form_data["remove-row"] = '<span class="ico-cancel"></span>';
var row = $('<tr></tr>');

$.each(form_data, function( type, value ) {

      itens[type] = value;
    $('<td class="input-'+type+'"></td>')
      .html(value)
      .appendTo(row);
});
     var button = '<tr><td><input type="button" value="Salvar" id="salvar"></td></tr>';
     var dataTable = itens.join(","); //separa os valores por vírgula
     $('.preview-table > tbody:last')
        .append(row)
        .append(button);
 
 /* use o método [delegate] para reler todo o
    documento novamente e pegar a id:"salvar"
    recém-criada: */ 
  $(document).delegate('#salvar','click', function() {
      $.post('salvar_dados.php', {valores:dataTable}, function(e) {
          var m = jQuery.parseJSON(e);
        if (e.success) {
            alert(e.message);  
        }
   });
 calc_total();
}); 

And in php, after saving the data return a response:

echo json_encode(array('success'=>1,'message'=>'Salvo com sucesso!'));

0

From what I understand, when I click Add you want to add the item to a table and send the data to the server.

Click Enviar pedido, you want to have access to the previously added items.

Well, to send the data to the server, I suggest adding the following code to the end of the existing event:

$('.preview-add-button').click(function(){
    // ... (seu código já existente fica aqui)

    $.ajax({
        type: "POST",
        url: "sua_url_adiciona_item.php",
        data: {
            status: form_data.status,
            amount: form_data.amount
        },
        success: function (data) {
            console.log(data);
        },
        error: function (xhr, status, error) {
            console.log(status, error);
        },
        dataType: "json"
    });
});

In the above example, sua_url_adiciona_item.php receives the data by $_POST, should add them to the sitting $_SESSION (or in the database if applicable) and return a JSON as a response stating if it was successful or an error. Anything, read on json_encode.

Finally, when you click Enviar pedido just read the data that was added in the session (or in the database) and display the items as you prefer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.