9

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..

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

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

cagatayodabasi
  • 762
  • 11
  • 34
IT gIrLy GiRl
  • 337
  • 4
  • 7
  • 20

6 Answers6

13

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:

<?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.

another method:

Actually if your problem is null value inserted into the database then try this and here no need of 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>
DS9
  • 2,995
  • 4
  • 52
  • 102
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:

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:

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.

Frank Conry
  • 2,694
  • 3
  • 29
  • 35
  • should i just put my normal div regarding "you ve been successfully subscribed" – IT gIrLy GiRl Dec 25 '13 at 05:45
  • not sure what you mean but you can do it a number of ways. Maybe just enclose the whole ting in a div and change the html. Again, you'll probably need to get to know some more jQuery if you don't know it already. – Frank Conry Dec 25 '13 at 05:46
  • listen i just want to insert the email id to my database through ajax, i dnt want my page to be redirected.. – IT gIrLy GiRl Dec 25 '13 at 05:49
  • yeah, the page won't submit if you change the input to `type="button"` like I referenced. In fact you dont even need the ` – Frank Conry Dec 25 '13 at 05:51
  • that subscribe button is not working ... i m extremely sorry if m bothering you very much – IT gIrLy GiRl Dec 25 '13 at 05:56
  • There is no redirection. did you put anything in the comments part of this: `$.get('\addEmail.php', {email : $(this).val()}, function(data) { //here you would write the "you ve been successfully subscribed" div });` – Frank Conry Dec 25 '13 at 05:57
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.

Check it here:

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.

Thank you

Altaf Hussain
  • 5,166
  • 4
  • 30
  • 47
  • but i dont want any alert box na – IT gIrLy GiRl Dec 25 '13 at 06:16
  • it is upto you to use an alert box or not. If success section you can display a message directly on the page by showing a div or redirect the user to another page. There they just showed an example with an alert box. – Altaf Hussain Dec 25 '13 at 07:12
0

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
/**
 * 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);
    }
}
?>
RedBaron
  • 4,717
  • 5
  • 41
  • 65
Amjad
  • 11
  • 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.

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

});

});
Eric Korolev
  • 713
  • 8
  • 13
0

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

AJAX Code

<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

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

Ehtesham Shami
  • 125
  • 2
  • 7