How to configure Ajax to submit date with 2 variables

Asked

Viewed 199 times

0

I’m developing an app for users to vote on 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>

1 answer

0

Try to do so:

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 json_encode directly.

Browser other questions tagged

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