Pass javascript data to a php array

Asked

Viewed 3,501 times

0

I have a little problem I’d like some ideas to solve:

I have an order screen, where I select the product in a combo, enter the quantity and when I click a button, I want to enter the combo value data and the value of the quantity in some javascript array, display in a table just below and insert this data into a php array so that when you save the request, you can scan this array in php and save the data to the database.

There’s a way to make it simple?

Supplementing the question:

I currently use jQuery libraries and my system is done in Codeigniter. The PHP Array I would keep in the view itself and pass as parameter to the Controller when saving everything in the database.

Currently I use an Ajax to fetch the price of the bank’s product without giving the refresh, so the part of looking for data from the bank 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 take this javascript data, add it in a PHP array (because I don’t know how many products will be selected) and then, when clicking the save button, I send this array together to the controller.

Hugging!

  • 1

    Post the combo part and the order screen, which makes it easier to help you pass the array you already have to PHP. It is not complicated, but it is convenient to leave already as far as it was published with the question.

  • Ariel, complete your question with more code and clarity about what you want (as Bacco asked). Also clarify if the PHP file is the same as the file where tm HTML and if you use some Javascript library like Mootools or jQuery.

  • Additionally, see if this is the answer you’re looking for. If it is, you can even delete the question, if it isn’t, give more details. http://answall.com/questions/8106/array-em-javascript-que-se-comunique-em-php

  • Guys, I updated my question, I think it’s clearer now...

2 answers

3

As you have not made it clear which part exactly you were struggling with, I will leave a full example and explain it.

First we create 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 function preventDefault to prevent the form from 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 on the button submitAll we convert the global array sendData for JSON, we clean it and the table and finally 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 just use the function json_decode and work with the array as you wish. Since it is only an example I will return the print_r of the array for Javascript that put it on the page.

<?php
if(isset($_POST['data'])) {
    $data = json_decode($_POST['data']);
    print_r($data);
}

-1

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

In the post by ajax shall indicate the dataType: 'json'.

On the PHP side you should respond to something like:

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

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

success: function (json) {
            alert(json.result);
}
  • If you want to send a Javascript array to PHP via JSON, just do $arrJs = json_decode($_POST['arr']);

Browser other questions tagged

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