pass variables from AJAX to PHP

Asked

Viewed 8,914 times

2

I’m trying to pass values through two variables in AJAX to a PHP file, but it’s not working. if I put data: { idUsuario: "5", idEscolha: "1", } right. What is wrong?

$(document).ready(function(){

    $("#botao").click(function(){

        var url = "InserirEscolha.php";

$.ajax({
    var idUsuario = "5";
    var idEscolha = "1";
  type: 'post',
  url: 'UpdateVisto.php',
  data: { idUsuario: idUsuario, idEscolha: idEscolha, }
});

        $.post(url, function(result) {

        });

    });

});

<?php
$idUsuario = $_POST['idUsuario'];
$idEscolha = $_POST['idEscolha'];

include "config_sistema.php";

$query = mysql_query("INSERT INTO usuario_escolha
            (id_usuario, id_escolha)
            VALUES('{idUsuario}','{$idEscolha}')");

if ($query){
    header("Location: perfil.php?ID=$idUsuario");
}
?>
  • What code does not work $.ajax or the $.post? the first example is right, you did not show in which example fails.

  • $.ajax. When I use the variables idUsuario and idEscolha, it does not receive the values. If I enter the values directly without the right variables

  • 1

    Try to pass it off data: {'idUsuario': idUsuario, 'idEscolha': idEscolha, }

  • 1

    Now it’s worked, thanks!

1 answer

1


You need to set the sent parameters, in which case add quotes names to be identifiable in php.

data: { 'idUsuario': idUsuario, 'idEscolha': idEscolha, }

If left as below php will receive the post with parameters named 5 and 1 instead of idUsuario and idEscolha.

data: { idUsuario: idUsuario, idEscolha: idEscolha, }

Browser other questions tagged

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