使用Ajax插入到Mysql表单php而无需重新加载页面

时间:2016-03-30 15:49:56

标签: javascript php jquery mysql ajax

我有这个jQuery AJAX代码,进入Mysql表单php。它无需重新加载页面即可运行。问题是当用户在表单中输入内容时,然后单击提交,我想使用php和ajax(使用jquery)。但它不会在alert()中打印字符串。有人可以告诉我这是如何实现的吗?

HTML:

<form id="students" method="post">
   <div class="row">
      <input name="a[]" value="" type="text" >
      <input name="b[]" value="" type="text"  >
   </div>
   <div class="row">
      <input name="a[]" value="" type="text" >
      <input name="b[]" value="" type="text"  >
   </div>
   <input type="submit" value="submit" id="submitbutton" class="insert"/>
</form>


<script type="text/javascript">
 $('#students').submit(function(){
    event.preventDefault();
    $.ajax({
      type: 'POST',
      url: 'ajax_insert.php',
      data: $('#students').serialize(),
      dataType: 'JSON',
      success: function(data) {
          alert('form has been posted successfully');
      }
    });
 });
</script>

和ajax_insert.php:

$a1=$_POST['a'];
$b1=$_POST['b'];

//$query_values = array();
$index=0;

foreach($a1 as $s){
   $sql = "INSERT INTO test_data(a,b) VALUES('$s','".$b1[$index]."')";

   $result = mysql_query($sql);
   if($result)
   {
     echo "1";
   }
   $index++;
}

3 个答案:

答案 0 :(得分:1)

$('#students').submit(function(event){
    event.preventDefault();
    $.ajax({
    type: 'POST',
    url: 'ajax_insert.php',
    data: $('#students').serialize(),
    dataType: 'JSON',
    success: function(data) {
    alert('form has been posted successfully');
  }
 });

查看官方文档here并了解如何使用event.preventDefault();

答案 1 :(得分:0)

您可能必须在提交事件回调中event.preventDefault();

$('#students').submit(function(){
  event.preventDefault();
  $.ajax({
    type: 'POST',
    url: 'ajax_insert.php',
    data: $('#students').serialize(),
    dataType: 'JSON',
    success: function(data) {
      alert('form has been posted successfully');
    }
  });
});

答案 2 :(得分:0)

使用dataType时需要返回有效的json:&#34; json&#34;在$ .ajax调用

或者您可以使用dataType:&#34; html&#34;没有重写PHP代码

更新(代码示例,应该有效):

HTML中的

<script type="text/javascript">
  $('#students').submit(function(e){
    e.preventDefault();
    $.ajax({
      type: 'POST',
      url: 'ajax_insert.php',
      data: $('#students').serialize(),
      dataType: 'JSON',
      success: function(data) {
          if(data.result == 1) {
              alert('form has been posted successfully');
          } else {
              alert(data.error);
          }
      }
    });
 });
</script>

ajax_insert.php

$a1=$_POST['a'];
$b1=$_POST['b'];

//$query_values = array();
$index=0;
$errors = array();

foreach($a1 as $s){
   $sql = "INSERT INTO test_data(a,b) VALUES('$s','".$b1[$index]."')";

   $result = mysql_query($sql);
   if(!$result)
   {
     $errors[] = "\"$sql\"";
   }
   $index++;
}

if(!empty($errors)) {
   echo json_encode(array('result'=>0,'error'=>"Error executing following queries: \n".implode("\n", $errors)));
} else {
   echo json_encode(array('result'=>1));
}