douyinzha5820 2019-04-27 01:21
浏览 393
已采纳

如何使用AJAX调用PHP函数?

I'm running my server on localhost using XAMPP, and I want to call a Javascript function which sends some data from the browser to a php script

The JS function is called when the a button on my html page is pressed:

function send_verification_code(){
    var xhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
    xhttp.open('GET','database.php?email='+email_address)
    xhttp.send()
}

So I want to add, to the $_GET array, a key-value pair of email=>email_address, where email_address is a string, in the function above.

Immediately after the function above executes, I want to call another function, a PHP function which adds that data to a SQL database on my server by calling add_email_to_be_verified (the function belongs to the php script im sending the data to):

database.php:

<?php
     $dbhost = "localhost";
     $dbuser = "root";
     $dbpass = "";
     $db = "example";
     $conn;

     function add_email_to_be_verified(){
        connect();
         $sql = 'insert into emailstobeverified values(';
         $sql .= $_GET['email'];
         $sql .= ',';
         $sql .= generate_verification_code();
         $sql .= ',';
         $sql .= date("Y-m-d H:i:s");
         $sql .= ');';
         query($sql);
         disconnect();

     }
     function generate_verification_code(){ //generates a random 6-digit verification code
        $code = mt_rand(0,999999);
        $padded_code = sprintf('%06d', $code);
        return $padded_code;
     }
     function connect(){
        $conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s
". $conn -> error);
     }
     function query(sql){
        $conn->query($sql);
     }
     function disconnect(){
        $conn -> close();
     }
?>

How can I call the php function using AJAX?

  • 写回答

1条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 hdfs在idea上传文件运行错误
      • ¥15 关于selenium网页闪退
      • ¥15 怎么用PYTHON解类似于x = y+zx + cy = x+zy + v的方程
      • ¥300 FLASH AS2.0制作一个类似手机上下滑动一样的效果
      • ¥15 为什么使用openFoam 中的icoFoam计算圆柱扰流时出现浮点数例外(核心已转储)
      • ¥15 51单片机外部中断控制数码管
      • ¥15 创建网页里面的图片显示不出来
      • ¥15 语音控制的编写?(语言-c#)
      • ¥15 matlab输入书上的代码运行错误
      • ¥15 matlab怎么做三维曲面