使用ajax插入查询而不重新加载整个页面

时间:2018-01-23 07:59:08

标签: javascript php jquery mysql ajax

我想通过AJAX插入数据(没有重新加载页面)。我试过但它没有显示数据,也没有重新加载页面。

我有一个文件 first.php (其中包含表单),一个AJAX代码和一个 firstcall.php ,其中将执行查询。

我的 first.php (html表单)是:

<form  class="reservation-form mb-0" action="" method="post"  autocomplete="off">
<input name="name1" id="name1" class="form-control"  type="text" placeholder="Enter Name" required aria-required="true">
<input name="age" id="age" class="form-control" required  type="number" placeholder="Enter Age" aria-required="true">
<input type="checkbox" id="checkbox" class="checkbox1" name="namec[]" value="<?php echo $value['id']; ?>" >
<input type="submit" class="pull-right btn btn-warning" value="Submit" id="submit">
 </form>

此处应显示数据:

<div class="col-md-5">
 <div class="panel panel-primary" id="showdata">

</div>      
</div>

AJAX是:

<script type="text/javascript">
$(document).ready(function(){
 $("#submit").click(function(){
    var name1 = $("#name1").val();
    var age = $("#age").val();

    var chkArray=[];
    $('.checkbox1:checked').each( function() {               
    chkArray.push($(this).val());    
    } );
    var selected;
    selected = chkArray.join(',') ;

    if(selected.length > 1){
    $.ajax( {
    url:'firstcall.php',
    type:'POST',
    data:{name1: name1,age: age,namec: chkArray},
     }).done(function(data){
      $("#showdata").html(data);
         });

        }
            else{
    alert("Please at least one of the checkbox");   
 }
 }  
 }  

</script>

firstcall.php 是:

<div class="panel panel-primary" id="showdata">
<?php 
foreach($_POST['namec'] as $selected){
echo $selected;
$_SESSION['name1']=$_POST["name1"];
$_SESSION['age']=$_POST["age"];

echo $name1=$_SESSION['name1'];
echo $age=$_SESSION['age'];

$query=mysql_query("insert into patient_details (p_name,p_age,g_number) values ('$name1','$age','$selected')") or die(mysql_error());
}
?>  

2 个答案:

答案 0 :(得分:2)

$("#submit").click(function(event){添加命令后

event.preventDefault();

您的页面不会重新加载

答案 1 :(得分:1)

提交按钮会在点击时自动重新加载页面,因此解决方案是将按钮类型更改为button或将preventDefault添加到点击事件

&#13;
&#13;
$("#submit1,#submit2").click(function() {
  alert('form submited')
})
$("#submit3").click(function(e) {
  e.preventDefault();
  alert('form submited')
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  this will reload the page
  <input type="submit" class="pull-right btn btn-warning" value="Submit" id="submit1">
</form>

<form>
  this will not reload the page
  <input type="button" value="Submit" id="submit2">
</form>


<form>
  this will not reload the page
  <input type="submit" value="Submit" id="submit3">
</form>
&#13;
&#13;
&#13;