JSON for PHP via AJAX

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, javaScript displays 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 javaScript responsible for doing this is as follows:

$('.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 get the data from this "preview" and send it to another view, I know I have to send it in JSON, but since that data goes to another page, I believe it can not be in ajax, I'm sure ?

Can anyone help me send this data to PHP?

Thank you very much.

    
asked by anonymous 03.08.2015 / 22:59

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.

    
20.03.2016 / 16:30
0

As I understand it, by clicking Add you want to add the item to a table and send the data to the server.

By clicking Enviar pedido , you want to have access to previously added items.

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

$('.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 example above, sua_url_adiciona_item.php receives the data by $_POST , should add them in session $_SESSION (or database if applicable) and return a JSON as a response stating whether it succeeded or not error. Anything, read about json_encode .

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

    
08.08.2015 / 20:19
0

You can create a button and send via post by storing the values in an array as in the example 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();
}); 
Home And in php, after saving the data return a response:
echo json_encode(array('success'=>1,'message'=>'Salvo com sucesso!'));
    
11.08.2015 / 21:41