How to configure Ajax to submit date with 2 variables

0

I'm developing an app for users to vote products. Technologies used JQuery plugin rateit, ajax and PHP. However I am having a problem with JSON, the configuration for 2 variables is giving the following error: SyntaxError: Unexpected token < in JSON at position 0 parsererror.
I present the code:

<? php
require_once 'ajax.php';

if (isset($_GET['id']) && isset($_GET['value'])) 
{
  $codigo = $_GET['id'];
  $valor = $_GET['value'];

  echo '{
  "id": '.json_encode($codigo).',
  "valor": '.json_encode($valor).'
};

}
<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Ajax star</title>
  <script src="src/jquery-3.1.0.js"></script>
  <link href="src/rateit.css" rel="stylesheet" type="text/css" />
  <script src="src/jquery.rateit.min.js" type="text/javascript"></script>
</head>

<body>

  <div id="products">

    <div style="float:right; width:350px; border:1px solid #ccc; padding:1em;">

      <strong>Server response:</strong>
      <ul id="response"></ul>

    </div>

    <ul>

      <li>
        <h4>Product X (id: 312)</h4>
        RateIt:
        <div data-productid="312" class="rateit"></div>
      </li>
      <li>
        <h4>Product Y (id: 423)</h4>
        RateIt:
        <div data-productid="423" class="rateit"></div>
      </li>
      <li>
        <h4>Product Z (id: 653)</h4>
        RateIt:
        <div data-productid="653" class="rateit"></div>
      </li>

    </ul>

  </div>

  <script>
    //we bind only to the rateit controls within the products div

    $('#products .rateit').bind('rated reset', function(e) {

      var ri = $(this);
      var valor = ri.rateit('value');
      var productID = ri.data('productid');

      //maybe we want to disable voting?
      ri.rateit('readonly', true);

      $.ajax({
        type: 'GET',
        url: "myfile.php",
        data: {
          id: productID,
          value: valor
        }, //our data
        dataType: "json",
        success: function(data) {

          var id = data.id;
          var valor = data.valor;
          alert(id);
          alert(valor)

        },
        error: function(jxhr, msg, err) {
          console.log(jxhr);
          $('#response').append('<li style="color:red">' + err + " " + msg + '</li>');
        }
      });
    });
  </script>

</body>

</html>
    
asked by anonymous 15.09.2017 / 01:42

1 answer

0

Try to do this:

if (isset($_GET['id']) && isset($_GET['value'])) {
  $dados = [];
  $dados[codigo] = $_GET['id'];
  $dados[valor] = $_GET['value'];
  echo json_encode($dados);   
}

Play the values in an array and use direct json_encode.

    
15.09.2017 / 02:41