通过ajax将数据插入mysql数据库

时间:2022-09-26 08:47:25

Newsletter:

通讯:

<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();

?>

But I want to insert my E-Mail to database through Ajax. I don't want my page to get redirected, because every time the page got refreshed, null value got inserted to the database..

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

I just want my E-mail got inserted to database through Ajax, and after that the email box i.e.

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

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

should get disappeared and there should be the line "you've been successfully subscribed" ..

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

Any brief code will be very useful.. thank u in advance :)

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

6 个解决方案

#1


10  

Try this:

尝试这个:

  $(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);
         }
});
 });

and in insertmail.php:

并在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.";
}
}
?>

Don't use mysql_ it's deprecated.

不要使用mysql_它已被弃用。

another method:

另一种方法:

Actually if your problem is null value inserted into the database then try this and here no need of ajax.

实际上,如果您的问题是插入数据库的空值,那么尝试这个,这里不需要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>

#2


3  

The ajax is going to be a javascript snippet that passes information to a small php file that does what you want. So in your page, instead of all that php, you want a little javascript, preferable jquery:

ajax将是一个javascript片段,它将信息传递给一个小的php文件,它可以完成你想要的工作。所以在你的页面,而不是所有的PHP,你想要一个小的javascript,更喜欢jquery:

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

also you input would have to be:

你输入也必须是:

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

last the file addEmail.php should look something like:

最后文件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();

Also sergey is right, you should use mysqli. That's not everything, but enough to get you started.

也是sergey是对的,你应该使用mysqli。这不是一切,但足以让你开始。

#3


2  

Why use normal jquery ajax feature. Why not use jquery ajax form plugin, which post the form data by ajax to the form action link.

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

Check it here:

在这里查看:

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

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

It is very easy to use and support several data formats including json, html xml etc. Checkout the example and you will find it very easy to use.

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

Thank you

谢谢

#4


0  

The available answers led to the fact that I entered empty values into the database. I corrected this error by replacing the serialize () function with the following code.

可用的答案导致我在数据库中输入空值。我通过使用以下代码替换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);
        }
    });

});

});

#5


0  

I will tell you steps how you can insert data in ajax using PHP

我将告诉您如何使用PHP在ajax中插入数据的步骤

AJAX Code

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 Code:

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);
  }



  ?>

You can customize it according to your needs. you can also check complete steps of AJAX Insert Data PHP

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

#6


-1  

ajax:

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 code:

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);
    }
}
?>

#1


10  

Try this:

尝试这个:

  $(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);
         }
});
 });

and in insertmail.php:

并在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.";
}
}
?>

Don't use mysql_ it's deprecated.

不要使用mysql_它已被弃用。

another method:

另一种方法:

Actually if your problem is null value inserted into the database then try this and here no need of ajax.

实际上,如果您的问题是插入数据库的空值,那么尝试这个,这里不需要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>

#2


3  

The ajax is going to be a javascript snippet that passes information to a small php file that does what you want. So in your page, instead of all that php, you want a little javascript, preferable jquery:

ajax将是一个javascript片段,它将信息传递给一个小的php文件,它可以完成你想要的工作。所以在你的页面,而不是所有的PHP,你想要一个小的javascript,更喜欢jquery:

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

also you input would have to be:

你输入也必须是:

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

last the file addEmail.php should look something like:

最后文件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();

Also sergey is right, you should use mysqli. That's not everything, but enough to get you started.

也是sergey是对的,你应该使用mysqli。这不是一切,但足以让你开始。

#3


2  

Why use normal jquery ajax feature. Why not use jquery ajax form plugin, which post the form data by ajax to the form action link.

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

Check it here:

在这里查看:

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

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

It is very easy to use and support several data formats including json, html xml etc. Checkout the example and you will find it very easy to use.

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

Thank you

谢谢

#4


0  

The available answers led to the fact that I entered empty values into the database. I corrected this error by replacing the serialize () function with the following code.

可用的答案导致我在数据库中输入空值。我通过使用以下代码替换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);
        }
    });

});

});

#5


0  

I will tell you steps how you can insert data in ajax using PHP

我将告诉您如何使用PHP在ajax中插入数据的步骤

AJAX Code

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 Code:

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);
  }



  ?>

You can customize it according to your needs. you can also check complete steps of AJAX Insert Data PHP

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

#6


-1  

ajax:

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 code:

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);
    }
}
?>