Capture, in PHP page, the value of an input that was changed at runtime

Asked

Viewed 64 times

0

The JS below captures the URL value and assigns to the value of input.

var valor_num = /num_nfe=([^&]+)/.exec(window.location.href)[1];

//console.debug("Num. NFe: "+$("[name='num-nfe']").val());
//console.debug("Form: "+ JSON.stringify($('#meu_form').serializeObject()));

$.post("actions/autosalvar.php", function (data) {
            $("[name='cliente']").attr('value', data.cliente);
            $("[name='id-cliente']").attr('value', data.id_cliente);
            $("[name='tipo-pessoa']").attr('value', data.tipo_pessoa);
            $("[name='num-nfe']").attr('value', valor_num);
}, "json");

setInterval(function () {     
                var dados = $('#meu_form').serializeObject();
                $.post("actions/autosalvar.php", 
                {'meus_dados': dados}).done(function( data ){});
}, 2000);

However, initially when trying to capture this value on the page autosalvar.php the same is not defined, being available only in a second execution.

1st execution of the page autosalvar.php

Array
(
    [cliente] => João
    [id-cliente] => 2
    [tipo-pessoa] => PF
)

2nd run [after 2 seconds interval] of the page autosalvar.php

Array
(
    [cliente] => João
    [id-cliente] => 2
    [tipo-pessoa] => PF
    [num-nfe] => 59
)
  • You are running the script for the first time before fully loading the page?

  • Yes, the script is on header.php. @Wagnersoares

  • The first post is to retrieve the data and fill in the form, correct? And every 2s the data is updated according to what is in the form. I got it right?

  • Certíssimo @Andersoncarloswoss

  • First, to get more semantically correct, use the verb HTTP GET to recover data in the first instance. POST only when saving the form. Second, the two requests are sent to the file actions/autosalvar.php, including the first, which is just to recover the data, without sending anything. How are you making this distinction?

  • @Can we continue this discussion via chat? http://chat.stackexchange.com/rooms/54076/datasynchronics-php-com-javascript

Show 1 more comment

1 answer

0

The solution was as follows:

Pass as argument the value of input, at first request $.post:

var val_num = $("[name='num-nfe']").val();
$.post("actions/autosalvar.php", {'val_num': val_num}).done(function (data) {
...
}, "json");

Already in PHP receive the data like this:

if(isset($_POST['val_num'])){ // 1ª instância do $.post
   $valor = $_POST['val_num'];
}else{
   $valor = &$_POST['meus_dados']['num-nfe']; // Outras instâncias
}

Browser other questions tagged

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