How to capture Javascript value with PHP

Asked

Viewed 264 times

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 PHP comparison.

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 one alert shortly after the attr of the desired value, however when loading the page and giving a echo, in $estado_cliente, nothing is displayed.

  • You can display an alert because it’s javascript and therefore running on your machine.

1 answer

0

Like 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 php via HTTP requests.

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

Ajax allows http requests to be sent without reloading the screen, an ajax function receives the response from 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 so that ajax captures it. Something 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;

Browser other questions tagged

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