如何从数据库向本地计算机发出实时通知

时间:2019-05-13 07:39:54

标签: javascript php jquery ajax database

我正在制作一个网页,您可以在该网页上签名以订阅列表,以获取有关一些新闻的通知。一切正常,但是我想改变一些东西。当我输入电子邮件并提交时,我将重定向到新页面(email.php),如果已将电子邮件添加到存储所有电子邮件的数据库中,则会收到通知我的警报。我想在不刷新页面的情况下执行相同的警报(在包含电子邮件的同一网站上进行警报)

我一直在AJAX上进行此操作,但是我不太擅长JavaScript(我对JS有点陌生)。我想我可能做错了什么,但看不到。

下面是一些代码

// HTML

<form method="POST" action="email.php" name="email-db" id="email-db">
                    <input type="email" class="email" name="email" placeholder="Enter your email">
                    <button  type="submit" class="submit" >&#10148;</button>
                </form>

// PHP

<?php
    $email = filter_input(INPUT_POST, 'email');
    if (!empty($email)){
        $host = "localhost";
        $dbusername ="root";
        $dbpassword ="";
        $dbname = "email";
        $alert1 = "<script type='text/javascript'>alert(\"Email has been written to subscribe list!\");</script>";
        $alertredirect = "<script type='text/javascript'>
           window.location = 'index.html'
      </script>";
        $alert2 = "<script type='text/javascript'>alert(\"Your email is already on our subscribe list!\");</script>";

        $conn = new mysqli ($host,$dbusername, $dbpassword , $dbname);
        if (mysqli_connect_error()){
            die('Connection problem('.mysqli_connect_errno().')'.mysqli_connect_error()); 
        }
        else{
            $sql = "INSERT INTO `email` (`email_id`, `email`) VALUES (NULL, '$email');";
            if ($conn->query($sql)){
                echo "$alert1";
                echo "$alertredirect";
            }
            else{
                echo "$alert2";
                echo "$alertredirect";
            }
            $conn->close();   
    }}
?>

如您所见(在email.php上),我确实进行了重定向-但正如我所说-所有这些警报都需要在index.html上发生-无需刷新或重定向。

感谢支持

3 个答案:

答案 0 :(得分:2)

  1. 将您的“提交”按钮更改为type=button,这样它就不会提交表单并回发(还有其他方法)

  2. 从您的php处理程序中删除javascript / html并返回数据,例如简单的true / false

  3. 添加一个调用$.ajax

  4. 的js单击事件处理程序

例如:

$("button.submit").click(function() {
    $.ajax({
        type: "POST", 
        url: your_url, 
        data: { email: $(".email").val() }, 
        success: function(result) {
            alert(result ? "Email saved" : "Already exists");
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error(errorThrown);
        }
    });
});

答案 1 :(得分:0)

<form method="POST" action="email.php" name="email-db" id="email-db"> <input type="email" class="email" name="email" placeholder="Enter your email"> <button type="submit" class="submit" >&#10148;</button> </form>

let form = document.querySelector("form");
form.addEventListener("submit", (event)=>{

   // This will help you to diable the defaut property of the form, And stops refresing on the submit 

   if(event && event.preventDefault){
      event.preventDefault();
   }

   let formData = new FormData(form)

   //This code will iterate data from the input elements from your form
   let postData = {};

   for(let [key, val] of formData.entries()){
    if(val) postData[key] = val;
   }


   postData(event.target.action, postData)
  .then(data => console.log(JSON.stringify(data))) 
  .catch(error => console.error(error));
})

function postData(url = '', data = {}) {
  // Default options are marked with *
    return fetch(url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, cors, *same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
            'Content-Type': 'application/json',
            // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrer: 'no-referrer', // no-referrer, *client
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    })
    .then(response => response.json()); // parses JSON response into native Javascript objects 
}

此后,会将数据发布到服务器供您使用,然后将数据发送回给您的呼叫。

答案 2 :(得分:0)

这对您来说应该很完美:

前端(JAVASCRIPT)
在前端,您可以使用AJAX这样发送请求:

$(document).ready(function(){
      $('#email-db').on('submit', function(){
           let email = $('.email').val();
           $.ajax({
              url: "email.php"
              type: 'post',
              data: { 'email': email },
              success: function(response){
                 alert(response);
              }
           });
       });
}

服务器端(PHP)
在服务器端,您可以使用PHP返回警报消息

<?php
    if (isset($_POST['email']) && !empty($_POST['email'])) {
        $host = 'localhost';
        $dbusername = 'root';
        $dbpassword = '';
        $dbname = 'email';
        $alert1 = 'Email has been written to subscribe list';
        $alert2 = 'Your email is already on our subscribe list';
        $conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
        if (mysqli_connect_error()) {
            die('Connection problem('.mysqli_connect_errno().')'.mysqli_connect_error());
        } else {
            $sql = "INSERT INTO `email` (`email_id`, `email`) VALUES (NULL, '$email');";
            return $conn->query($sql) ? $alert1 : $alert2;
        }
    }
?>