Ajax函数,用于显示特定div中提交的结果

时间:2017-10-05 02:07:59

标签: php mysql ajax

所以我正在努力在我的数据库中存储日历的约会,我需要在完成模态之前检查数据库中的人名。

我需要显示结果的字段,按钮和div的代码:

<div class="alinhar-esquerda"> 
   <input class="form-control" name="cpf_paciente" id="cpf_paciente" placeholder="" type="text" value="">
</div>
<div class="alinhar-direita">
   <button type="submit" class="btn btn-primary" id="searchButton">Pesquisar</button>
</div>
<div class="controls controls-row" id="resultado" style="margin-top:5px;">
</div>
<?php
include("database2.php");
   if(isset($_POST["cpf_paciente"])){
      $cpf_paciente = $_POST["cpf_paciente"];
      $pesquisa = $connection->query("SELECT `id`, `cpf_paciente`, `nome_paciente`, `sobrenome_paciente` FROM  `pacientes` WHERE cpf_paciente='$cpf_paciente'");
      while($row = $pesquisa->fetch(PDO::FETCH_ASSOC)) {
         echo $row['nome_paciente'] . " " . $row['sobrenome_paciente'];
      }
   }
?>  
</div>
</div>

我需要一个Ajax代码来接收来自#submitButton输入的数据,然后通过div #resultado中的php代码而无需重新加载页面,因为所有这些都在一个模态中,我将在之后发送结果得到这个人的名字。

尝试过这样的事情,但没有成功:

$('#searchButton').submit(function() { // catch the data from submit event
$.ajax({ // create an AJAX call...
  data: $(this).serialize(), // get the data
  type: $(this).attr('POST'), // POST
  url: $(this).attr(''), // no file to call
  success: function(response) { // on success..
      $('#resultado').html(response); // update the DIV
  }
});
});

3 个答案:

答案 0 :(得分:0)

您错过了类型和网址 - &gt;

$.ajax({
    type: "POST",
    url: "<?php echo base_url(); ?>contents/hello",
    data: "id=" + a_href,
    success: function(data, textStatus) {
        $(".result").html(data);    
    },
    error: function() {
        alert('Not OKay');
    }
});​

来源 - &gt; https://stackoverflow.com/a/10575968/3543355

答案 1 :(得分:0)

应该是:

$('#searchButton').click(function() { // catch the data from submit event
    $.ajax({ // create an AJAX call...
      data: { cpf_paciente: $("#cpf_paciente").val() },
      type: "POST",
      url: '',
      success: function(response) { // on success..
          $('#resultado').html(response); // update the DIV
      }
    });
});

除非$(this).serialize()this,否则您无法使用<form>。它只是一个按钮不起作用(如何知道序列化的输入?)。

type:应该只是'POST,因为该按钮没有POST属性。

网址应为'',以转到与当前网页相同的网址,$(this).attr('')毫无意义。

submit事件仅适用于表单。对于按钮,您使用.click()

答案 2 :(得分:0)

不明白你想要什么

<?php
 while($row = $pesquisa->fetch(PDO::FETCH_ASSOC)) 
 {echo $row['nome_paciente'] . " " . $row['sobrenome_paciente'];
?>

如果结果是

第1行:qwe ert

第2行:asd dfg

JS

$('#resultado').html(response);

这将显示&#34; qwe ert asd dfg&#34;

并且不会只是一个文本,如果你想重新生成代码u并在php上设置或者你的html代码变成了js函数,那么你可以使用return str来爆炸并调用函数来重新生成元素

对我来说这两件事都很简单