How to capture JavaScript value with PHP [duplicate]

0

The input below is loaded along with the page script:

$("[name='estado-cliente']").attr('value', obj['uf_cliente']);

However, this value will be used for a comparison in PHP.

I've tried the following, but to no avail:

JavaScript:

var valor = $("[name='estado-cliente']").val();

PHP:

$estado_cliente = "<script> document.write(valor)</script>";

Note: I can display a alert soon after the attr of the desired value, but when loading the page and giving a echo , in $estado_cliente , nothing is displayed.

    
asked by anonymous 04.03.2017 / 23:49

1 answer

0

As the friend Leo Caracciolo said, Javascript in this case runs in the user's browser, this means that it is only possible to send information to the php through HTTP requests.

It would work like this: The php send the pro-browser information > The user enters the data - > Javascript sends the information back to php via Ajax- > Javascript receives the treated data

Ajax allows HTTP requests to be sent without reloading the screen, an ajax function receives the response from the php as if we were accessing the page, that is, it receives everything that would be displayed on the screen if we accessed through the browser normally.

Create a php page that does the treatment you need and echo the result for ajax to capture. More or less like this:

HTML:

<input name="estado-cliente">
<button>
  enviar
</button>

JS:

$(document).ready(function(){
  //Voce precisa de um evento que envie a requisição
$('button').click(function(){
    $.post("SUAPAGINA.PHP?estado-cliente=" + $('name="estado-cliente"').val(), function(dados){
    //faça o que quiser com os dados
    })
})
})

PHP:

<?php

    $dados = $_POST["estado-cliente"];

  // trate os dados como desejado e de um echo no resultado, pode usar JSON tbm, mas assim é mais simples.


  echo $resultado;
    
06.03.2017 / 13:38