Pass PHP variable in AJAX

Asked

Viewed 488 times

0

I have a script.js file that needs to capture a php variable, as I do?

Look what I got:

function atualizaFotos() {

    $.ajax({
        url: "imovel-fotos-id.php?cliente=&cod="
    }).done(function (resposta) {
        $("#fotos").html(resposta);
    });

}

I have the client variable and the code variable. How to capture a php variable and pass it in this parameter?

I’m waiting for help!

Thank you very much!

1 answer

1

You can put your variable php in a input guy hidden, and send parameters to the file via js. For example:

<input type="hidden" id="cliente" value="<?php echo $var_cliente_php; ?>">
<input type="hidden" id="codigo" value="<?php echo $var_codigo_php; ?>">
<input type="button" onclick="atualizaFotos(document.getElementById("cliente").value, document.getElementById("codigo").value)" value="Enviar">

and your jQuery function would look like this:

function atualizaFotos(pCliente, pCodigo) {
  $.ajax({
    url: "imovel-fotos-id.php?cliente="+pCliente+"&cod="+pCodigo
  }).done(function (resposta) {
    $("#fotos").html(resposta);
  });
}
  • I advise protecting variables $var_cliente_php and $var_codigo_php with htmlentities and/or json_encode (treat UTF-8 if necessary).

Browser other questions tagged

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