Passing data from javascript to an array in php

0

I have a small problem that I would like some ideas to solve:

I have a request screen, where I select the product in a combo, I inform the quantity and when I click on a button, I want to insert the data of the value of the combo and the value of the quantity in some javascript array, display in a table just below and insert this data into a php array for when to save the request, be able to scan this array in php and save the data in the database.

Is there a way to make it simple?

Complementing the question:

I currently use the jQuery libraries and my system is done in CodeIgniter. The Array in PHP I would keep in the same view and would pass as parameter to the Controller when I would save everything in the bank.

I currently use an Ajax to fetch the price of the bank product without giving the refresh, so the part of fetching bank data with ajax I can already turn around, as I show below:

<script type="text/javascript">
$(document).ready(function () {
    $("select[name='produto_id']").change(function () {
        var base_url = '<?php echo base_url();?>';
        alert('Entrou');
        var preco = $("input[name='valor']");
        //var teste = $("select[name='nome']").val();
        //alert(teste);
        $(preco).val('Carregando...');

        $.ajax({
            type: "POST",
            //url: "application/views/admin/teste.php",
            url: '<?php echo base_url(); ?>index.php?admin/list_dropdown',
            data: "prod=" + $("select[name='produto_id']").val(),
            success: function (json) {
                alert(json);
                //$(preco).val((Math.round(json * 100) / 100)).toFixed(2);
                $(preco).val(json).toFixed(2);
            }
        });
        //);
    });
});
</script>

My question, would be, how to get this data from javascript, add it to an array in PHP (because I do not know how many products will be selected) then, when I click the save button, I send this array together to the controller .

A hug!

    
asked by anonymous 05.04.2014 / 16:33

2 answers

3

As you have not made it clear which part was in trouble, I'll leave a complete example and explain it.

We first created the following HTML page.

<form id="dataForm">
    <select name="type">
        <option value="1">Tipo 1</option>
        <option value="2">Tipo 2</option>
        <option value="3">Tipo 3</option>
    </select>
    <input type="text" name="value" />
    <input type="submit" value="Adicionar" />
</form>
<input id="submitAll" type="button" value="Enviar" />
<table>
    <tr>
        <th>Tipo</th>
        <th>Valor</th>
    </tr>
</table>

In it we have the HTML form that will be used to add items, we have another button outside the form that will be used by Javascript to send the data and we have a table where we will display the data that has already been added. >

In Javascript we will use the preventDefault function to prevent the form being sent normally, then we take the data that is in it and put it in a global array and also insert it into the table.

var sendData = [];
$('form#dataForm').submit(function(e){
    e.preventDefault();
    var type = $('select[name=type] option:selected').val(),
        value = $('input[name=value]').val();
    sendData.push({
        'type': type,
        'value': value
    });
    $('table tr:last').after(
        '<tr>\
            <td>'+type+'</td>\
            <td>'+value+'</td>\
        </tr>');
});

Then in the submitAll button we convert the global array sendData to JSON, we clear it and the table and in the end we send the data.

$('input#submitAll').click(function(){
    var data = JSON.stringify(sendData);
    sendData = [];
    $('table tr:gt(0)').remove();
    $.ajax({
        type: 'post',
        url: '/insert.php',
        data: 'data=' + data,
        //dataType: 'json',
        success: function(ret) {
            document.write('<pre>' + ret +'</pre>');
        }
    });
});

Now in PHP you only have to use the json_decode function and work with the array as you wish. As just an example I'll return the print_r of the array to the Javascript that put it on the page.

<?php
if(isset($_POST['data'])) {
    $data = json_decode($_POST['data']);
    print_r($data);
}
    
05.04.2014 / 22:08
0

The best way to pass Javascript information < = > PHP is through JSON.

In post by ajax should indicate dataType: 'json' .

On the PHP side you should respond in something like:

<?php 
echo json_encode(array('result'=>'hello world'));
?>

Finally, in the response handling of your ajax request you can access the array sent by PHP:

success: function (json) {
            alert(json.result);
}
    
05.04.2014 / 20:24