简体   繁体   中英

getting null while trying to send and receive a form value using json and jquery

Here's the HTML part that may be wrong perhaps on the form statement (not sure):

<div id='data'></div>
  <form action="">
   <input type="text" name="nomeInput" value="" />
</form>

Here's the javascript part:

$(document).ready(function(){

$.post("testeBasico_1.php", {nomeInput : $('#nomeInput').val()}, function(resposta) {
  for (var x = 0, tamanhoDados = resposta.dados.length; x < tamanhoDados; x++){
     $('#data').append(resposta.dados[x]+'<br>');
  }
  //issue line
  $('#data').append('<br />'+resposta.venhoDoInput);
  }, "json");
});

Here's the php part:

$response = (object) array(
    'success' => TRUE,
    'dados'       => array("1", "2", "3"),
    'venhoDoInput' => $_POST['nomeInput']
);
echo json_encode($response);

When I try this, I get null on 'venhoDoInput' regardless the input field being filled or not.

What am I missing here? (it should be something very very basic), I'm just hoping that, by knowing that, I can better understand those evil code lines.

Thanks a lot in advance,

MEM

Note: If I dump($_POST['nomeInput'] on the server side script, I get nothing displayed... that's probably because I'm using js to display that data into the browser. And I'm not quite sure how to debug server side here... :s

You are using an id selector, but the element you are trying to select does not have the id set. Add the attribute id="nomeInput" to the input.

Edit: Your code will submit the form on page load. In order to have it submit upon actual form submission, you need to wrap it a submit listener for the form.

HTML:

<div id='data'></div>
<form action="" id="myForm">
    <input type="text" name="nomeInput" value="" />
</form>

jQuery:

$(document).ready(function(){

    $('#myForm').submit(function() {
        $.post("testeBasico_1.php", {nomeInput : $('#nomeInput').val()}, function(resposta) {
            for (var x = 0, tamanhoDados = resposta.dados.length; x < tamanhoDados; x++) {
                $('#data').append(resposta.dados[x]+'<br>');
            }
            //issue line
            $('#data').append('<br />'+resposta.venhoDoInput);
        }, "json");
        return false;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM