【问题标题】:Insert data through ajax into mysql database通过ajax将数据插入mysql数据库
【发布时间】:2014-01-13 04:42:44
【问题描述】:

时事通讯:

<form id="form-search" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
    <span><span class="style2">Enter you email here</span>:</span>
    <input name="email" type="email" id="email" required/>

 <input type="submit" value="subscribe" class="submit" onclick="return fun()" />
                        </form>
                        <?php
mysql_connect("localhost","","");
mysql_select_db("");
error_reporting(E_ALL && ~E_NOTICE);

$email=$_POST['email'];
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
 if(!$sql)
die(mysql_error());

mysql_close();

?>

但我想通过 Ajax 将我的电子邮件插入数据库。我不希望我的页面被重定向,因为每次刷新页面时,都会将空值插入到数据库中..

我只想通过 Ajax 将我的电子邮件插入数据库,然后是邮箱 即

<input name="email" type="email" id="email" required/>  
<input type="submit" value="subscribe" class="submit" onclick="return fun()" />

应该消失,应该有“你已成功订阅”这行..

任何简短的代码都会非常有用..提前谢谢你:)

【问题讨论】:

  • 你有没有尝试过。在你的代码中添加 ajax
  • 使用PDOmysqli函数,因为mysql_*已被弃用
  • sarmishtha : 你确定你需要 ajax 吗?我可以看到不需要 ajax。
  • @MazIqbal 是的,但我在 ajax 中不是很方便,所以无法通过它
  • @Mrcoder 但我的意思是 php 中的任何其他方法都会使我的页面重定向 na .. 我不想要

标签: php ajax


【解决方案1】:

试试这个:

  $(document).on('click','#save',function(e) {
  var data = $("#form-search").serialize();
  $.ajax({
         data: data,
         type: "post",
         url: "insertmail.php",
         success: function(data){
              alert("Data Save: " + data);
         }
});
 });

insertmail.php:

<?php 
if(isset($_REQUEST))
{
        mysql_connect("localhost","root","");
mysql_select_db("eciticket_db");
error_reporting(E_ALL && ~E_NOTICE);

$email=$_POST['email'];
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
}
?>

不要使用mysql_,它已被弃用。

another method:

实际上,如果您的问题是将空值插入数据库,那么试试这个,这里不需要 ajax。

<?php
if($_POST['email']!="")
{
    mysql_connect("localhost","root","");
    mysql_select_db("eciticket_db");
    error_reporting(E_ALL && ~E_NOTICE);
    $email=$_POST['email'];
    $sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
    $result=mysql_query($sql);
    if($result){
    //echo "You have been successfully subscribed.";
              setcookie("msg","You have been successfully subscribed.",time()+5,"/");
              header("location:yourphppage.php");
    }
     if(!$sql)
    die(mysql_error());
    mysql_close();
}
?>
    <?php if(isset($_COOKIE['msg'])){?>
       <span><?php echo $_COOKIE['msg'];setcookie("msg","",time()-5,"/");?></span> 
    <?php }?>
<form id="form-search" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
    <span><span class="style2">Enter you email here</span>:</span>
    <input name="email" type="email" id="email" required/>
    <input type="submit" value="subscribe" class="submit"/>
</form>

【讨论】:

  • 如果没有操作页面,我不能这样做吗??我的意思是我不想要任何页面重定向
  • 这种事情在没有页面重载的情况下发生。它只是将数据发布到另一个页面,然后插入该数据,然后提醒消息。
  • 问题是,订阅没有发生,提交按钮不起作用
  • 从提交按钮中删除onclick="return fun()"
  • 在页面顶部写print_r($_POST);,看看结果如何?
【解决方案2】:

ajax 将是一个 javascript sn-p,它将信息传递到一个小的 php 文件,它可以执行您想要的操作。所以在你的页面中,你需要一点 javascript,而不是所有的 php,最好是 jquery:

function fun()
{
    $.get('\addEmail.php', {email : $(this).val()}, function(data) {
        //here you would write the "you ve been successfully subscribed" div
    });
}

您的输入也必须是:

<input type="button" value="subscribe" class="submit" onclick="fun();" />

最后文件 addEmail.php 应该是这样的:

mysql_connect("localhost","root","");
mysql_select_db("eciticket_db");

error_reporting(E_ALL && ~E_NOTICE);

$email=mysql_real_escape_string($_GET['email']);
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
 if(!$sql)
die(mysql_error());

mysql_close();

sergey 也是对的,你应该使用 mysqli。这还不是全部,但足以让您入门。

【讨论】:

  • 我应该把我的正常 div 放在“您已成功订阅”
  • 不确定您的意思,但您可以通过多种方式做到这一点。也许只是将整个 ting 包含在一个 div 中并更改 html。同样,如果您还不了解 jQuery,您可能需要了解更多 jQuery。
  • 听我只是想通过 ajax 将电子邮件 ID 插入到我的数据库中,我不希望我的页面被重定向..
  • 是的,如果您将输入更改为type="button",就像我提到的那样,页面将不会提交。事实上,此时您甚至不需要&lt;form id="form-search" method="post" action="&lt;?php echo $_SERVER['PHP_SELF'];?&gt;"&gt; 行。
  • 那个订阅按钮不起作用……如果我给你带来了很大的困扰,我非常抱歉
【解决方案3】:

为什么要使用普通的 jquery ajax 功能。为什么不使用 jquery ajax 表单插件,它通过 ajax 将表单数据发布到表单操作链接。

在这里查看:

http://malsup.com/jquery/form/#getting-started

它非常易于使用,支持多种数据格式,包括json、html xml等。查看示例,您会发现它非常易于使用。

谢谢

【讨论】:

  • 但我不想要任何警报框 na
  • 是否使用警告框由您决定。如果成功部分,您可以通过显示 div 或将用户重定向到另一个页面直接在页面上显示消息。他们只是展示了一个带有警告框的示例。
【解决方案4】:

ajax:

$(document).on('click','#mv_secure_page',function(e) {
    var data = $("#m_form1").serialize();
    $.ajax({
        data: data,
        type: "post",
        url: "adapter.php",
        success: function(data){
        alert("Data: " + data);
        }
    });
});

php代码:

<?php
/**
 * Created by PhpStorm.
 * User: Engg Amjad
 * Date: 11/9/16
 * Time: 1:28 PM
 */


if(isset($_REQUEST)){
    include_once('inc/system.php');

    $full_name=$_POST['full_name'];
    $business_name=$_POST['business_name'];
    $email=$_POST['email'];
    $phone=$_POST['phone'];
    $message=$_POST['message'];

    $sql="INSERT INTO mars (f_n,b_n,em,p_n,msg) values('$full_name','$business_name','$email','$phone','$message') ";

    $sql_result=mysqli_query($con,$sql);
    if($sql_result){
       echo "inserted successfully";
    }else{
        echo "Query failed".mysqli_error($con);
    }
}
?>

【讨论】:

    【解决方案5】:

    可用的答案导致我在数据库中输入了空值。我通过将 serialize() 函数替换为以下代码来纠正此错误。

    $(document).ready(function(){
    
    // When click the button.
    $("#button").click(function() {
    
        // Assigning Variables to Form Fields
        var email = $("#email").val();
    
        // Send the form data using the ajax method
        $.ajax({
            data: "email=" + email,
            type: "post",
            url: "your_file.php",
            success: function(data){
                alert("Data Save: " + data);
            }
        });
    
    });
    
    });
    

    【讨论】:

      【解决方案6】:

      我将告诉你如何使用 PHP 在 ajax 中插入数据

      AJAX 代码

      <script type="text/javascript">
      function insertData() {
      var student_name=$("#student_name").val();
      var student_roll_no=$("#student_roll_no").val();
      var student_class=$("#student_class").val();
      
      
      // AJAX code to send data to php file.
          $.ajax({
              type: "POST",
              url: "insert-data.php",
              data: {student_name:student_name,student_roll_no:student_roll_no,student_class:s
               tudent_class},
              dataType: "JSON",
              success: function(data) {
               $("#message").html(data);
              $("p").addClass("alert alert-success");
              },
              error: function(err) {
              alert(err);
              }
          });
      
       }
      
      </script>
      

      PHP 代码:

      <?php
      
      include('db.php');
      $student_name=$_POST['student_name'];
      $student_roll_no=$_POST['student_roll_no'];
      $student_class=$_POST['student_class'];
      
      $stmt = $DBcon->prepare("INSERT INTO 
      student(student_name,student_roll_no,student_class) 
      VALUES(:student_name, :student_roll_no,:student_class)");
      
       $stmt->bindparam(':student_name', $student_name);
       $stmt->bindparam(':student_roll_no', $student_roll_no);
       $stmt->bindparam(':student_class', $student_class);
       if($stmt->execute())
       {
        $res="Data Inserted Successfully:";
        echo json_encode($res);
        }
        else {
        $error="Not Inserted,Some Probelm occur.";
        echo json_encode($error);
        }
      
      
      
        ?>
      

      您可以根据需要对其进行自定义。也可以查看AJAX Insert Data PHP的完整步骤

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-21
        • 1970-01-01
        • 1970-01-01
        • 2020-02-21
        相关资源
        最近更新 更多