Return calculation for textarea

2

I have a PHP page with 2 <textarea> forms, I need to do some calculations on the first <textarea> with PHP as soon as the user clicks on the submit button and returns the result for 2 <textarea> that is on the same page, can someone please give me an idea to make this happen?

It is important to note that I need to manipulate the text that is inserted in the PHP side, otherwise I can not solve the calculations correctly and return them correctly.

I tried to get the value for $ _POST ['area_1'] but it did not work, it gives error, how can I send the content of PHP to the PHP page to manipulate it?     

asked by anonymous 30.01.2015 / 19:11

2 answers

2

In AJAX

   <script>

    $(document).on('click','#enviar',function(){
        $.ajax({
            type: "POST",
            data: { valor : $('#area_1').html() },
            url: "calcular.php",
            success: function(resposta){
                $("#area_2").html(resposta);
            }
        });
    });

    </script>

    <textarea id="area_1"></textarea>
    <input type="button" value="ENVIAR" id="enviar"/>
    <textarea id="area_2"></textarea>

Only make the file calcular.php which will return the value for the second textarea

    
30.01.2015 / 19:23
2

The functionality you want seems to be possible to do only on the client side (using JavaScript). I put together two variants. You can also take a look at in this answer to see other ways to send data to the server.

Via server:

To send to PHP you can do it in different ways. To make accurate descriptions of a <form> within which you have <textare> named . For example:

<form>
<textarea name="area_1"></textarea>
<input type="submit" value="enviar" />
</form>

In PHP you can capture this value using $_POST['area_1'] . Then you can pass this value to a variable, make the calculations you need, and then return it to the client side with echo .

$texto_1 = $_POST['area_1'];
$comprimento = 'O comprimento da string foi: '.strlen($texto_1);
echo '
    <form>
    <textarea name="area_1"></textarea>
    <textarea name="area_2">'.$comprimento.'</textarea>
    <input type="submit" value="enviar" />
    </form>
';

On the client side

You can do calculations on the JavaScript / Client side if you do not need to go through the server. In this case you may not even need <form> .

In this case to have a textarea and a button reference you can do:

var area_1 = document.querySelector('[name="area_1"]');
var area_2 = document.querySelector('[name="area_2"]');
var botao = document.querySelector('button');

botao.onclick = function () {
    area_2.value = area_1.value * 3;
}

jsFiddle: link

    
30.01.2015 / 19:17