php always returns 0

4

I'm doing a calculation for php, picked up with jQuery and passed in ajax. All this within a wordpress (I think this does not influence the failure). After filling 3 fields (1 input and 2 select) you must send it by ajax and the php add the values and return the sum ... but no! I always return 0 and I do not know what to try ... Can you give me a hand?!?!

Just one more contribution, if instead of sending the object (values), I send them 3 separately if I add the ones of the select but not the input.

I leave my code below:

(fuctions.php)

  function calcular() {

    $result = $_REQUEST['data1'] + $_REQUEST['data2'] + $_REQUEST['data3'];
    echo $result;

      wp_die();
  }
  add_action('wp_ajax_calcular','calcular');
  add_action('wp_ajax_nopriv_calcular','calcular');

(script.js)

// calculation

$(document).ready(function(){

    $('#importe').on('keyup',calculo);
    $('select#nFac').on('change',calculo);
    $('select#nDeuda').on('change',calculo);

    function calculo(evento) {
      let data1 = parseInt($("#importe").val());
      let data2 = parseInt($("select#nFac").val());
      let data3 = parseInt($("select#nDeuda").val());

      let valores = {
              "data1" : data1,
              "data2" : data2,
              "data3" : data3
      };

      $.ajax({
            url:   admin_url.ajax_url,
            data: {action:'calcular', valor:valores},
            type:  'POST',
            success: function(data) {
                $('#result').html(data);
                // console.log(data);
            }
      });
    }

});
    
asked by Xavi 06.07.2018 в 18:23
source

3 answers

4

The first node that you have to access is a value, and then the data, it is also no more than caste to whole in PHP

function calcular() {

    $result = (int) $_REQUEST['valor']['data1'] + (int) $_REQUEST['valor']['data2'] + (int) $_REQUEST['valor']['data3'];
    echo $result;

      wp_die();
  }
  add_action('wp_ajax_calcular','calcular');
  add_action('wp_ajax_nopriv_calcular','calcular');
}

I also recommend that before sending the valid values if they are really defined, this will help to clean the information to PHP

function calculo(evento) {
      let data1 = parseInt($("#importe").val());
      let data2 = parseInt($("select#nFac").val());
      let data3 = parseInt($("select#nDeuda").val());

if( data1 && data2 && data3 ){
      let valores = {
              "data1" : data1,
              "data2" : data2,
              "data3" : data3
      };

      $.ajax({
            url:   admin_url.ajax_url,
            data: {action:'calcular', valor:valores},
            type:  'POST',
            success: function(data) {
                $('#result').html(data);
                // console.log(data);
            }
      });
 }

else{
  alert('No existe uno o más valores');
}
}

That should fix the problem

    
answered by 06.07.2018 / 18:30
source
1

Your code can still be optimized.

Why make the server do a job that the client should do?

The reality of client / server communication is as follows, usually:

1  servidor
n  clientes 

Where% co_of% can be 1, it can be 1,000, it can be 1,000,000.

If the n clients send the data to the server so that it calculates them, you are causing the server to do n calculations, apart from the other things that it has to do and that are its own.

Someone will be able to object that it is something banal being a simple calculation of n . It is not. Let's suppose a page with thousands of concurrent connections sending each one two values a + b and a for the server to calculate them.

Why does not the client calculate them and send them already calculated to the server for processing, ONLY in case that data is needed for something on the server 1 ?

That optimization problem I see a lot in questions raised here. Perhaps it is because we learn from poorly done tutorials or because little importance is given to this?

I would call this principle: that each one does what corresponds to him .

If we apply it in your case, the code would be:

On the client:

function calculo(evento) {
      let data1 = parseInt($("#importe").val());
      let data2 = parseInt($("select#nFac").val());
      let data3 = parseInt($("select#nDeuda").val());

if( data1 && data2 && data3 ){
      let total = data1+data2+data2;

      $.ajax({
            url:   admin_url.ajax_url,
            data: {action:'total', valor:total},
            type:  'POST',
            success: function(data) {
                $('#result').html(data);
                // console.log(data);
            }
      });
 }

else{
  alert('No existe uno o más valores');
}
}

On the server:

We can use a ternary operator to evaluate if in b the key $_REQUEST exists, to assign it to valor and if we do not assign it $result or any other value.

$result = (empty($_REQUEST['valor'])) ? NULL : $_REQUEST['valor'];

In this way, the server is free to add, because the sum has already been made by the client.

Another aspect of optimization

When we work with various data, optimization can still be incorporated into the logic of the program.

Suppose that instead of three values we need to add NULL values that can be 10, 34, 200 ...

At the level of Javascript can be optimized by grouping these values by some common element, for example by putting n to each of them and applying a sum in a loop to all elements of that class. So we avoid the class="sumar" .

And, if it had to be done on the server, we could use functions that help us optimize the code. For example, in this case, you could add all the values that are in total= a + b + c + ... n using $_REQUEST as follows:

$result= (empty($_REQUEST['valor'])) ? NULL : array_sum($_REQUEST['valor']);

We have also used a ternary operator here. If there is data in array_sum we will add all the values that are in the array. This solution is optimal if for some reason you decide to do the sum of the values on the server and not on the client.

I hope it will be useful and help to always consider as a solution the one that is most optimal.

Optimization is a fundamental element when scheduling .

1 Even in your example, the server calculates the values and does absolutely nothing with them, returns them to the client and the Ajax code shows the sum in a container of the client . (This would be like knowing that $_REQUEST['valor'] and paying the ticket to someone to go to Australia carrying 2+2=4 + 2 , calculate how much it is and that back will bring you the result ... I exaggerate a bit, but it is that's absurd: the money you spend paying for airfare means network resources and server memory that you use unnecessarily).

PD

Here is an example of your code running without any intervention from Ajax or the server.

$(function() {

  $('#importe').on('keyup', calculo);
  $('#nFac').on('change', calculo);
  $('#nDeuda').on('change', calculo);

});

function calculo() {
  let data1 = parseInt($("#importe").val());
  let data2 = parseInt($("#nFac").val());
  let data3 = parseInt($("#nDeuda").val());
  let total = data1 + data2 + data3;
  $('#result').html(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="importe" type="number" placeholder="Escriba el importe">
<select id="nFac">
  <option value="0" selected="selected">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="100">100</option>
</select>

<select id="nDeuda">
  <option value="0" selected="selected">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="1000">1000</option>
</select>
<hr />
<h2>Total:</h2>
<div id="result"></div>
    
answered by 06.07.2018 в 20:55
0

First you have the value you send, then later you have to take the value of the data.

Any doubt warns

    function calcular() {

    $result = (int) $_REQUEST['valor']['data1'] + (int) $_REQUEST['valor']['data2'] + (int) $_REQUEST['valor']['data3'];


      wp_die();
  }
  add_action('wp_ajax_calcular','calcular');
  add_action('wp_ajax_nopriv_calcular','calcular');
    
answered by 06.07.2018 в 18:33