dongweng9474 2016-02-15 23:04
浏览 100
已采纳

如何在wordpress中使用ajax来显示使用php和Json的数据库列

I'm new using ajax and I have a code to display from wordpress some information from database columns. I have this PHP code to connect with the database and create the JSON file:

<?php    
$username = $_REQUEST['username']; 
$password = $_REQUEST['password'];    

if (isset($username) && isset($password)) {
//CONEXION
    $host="localhost";
    $user="DB_Username";
    $pass="DB_Password";
    $dbname="DB_Name";

//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname) 
or die("unexpected error");

//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8"); 

if(!$result = mysqli_query($conexion, $sql)) die();

$clients = array();

$num_result = mysqli_num_rows($result);

    if ($num_result == 0) {
        $clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
    } else {
        while($row = mysqli_fetch_array($result)) 
        { 
            $id=$row['ID'];
            $Name=$row['Name'];

            if ($row['A_Login'] == $username && $row['A_Password'] == $password){        
                $clients[] = array('id'=> $id, 'Name'=> $Name);
                } else {
                    $clients[] = array('error'=> "true", "msg" => "Incorrect data");
                    }

        }
    }

$close = mysqli_close($conexion) 
or die("Unespected error with DB");
  }
else {
    $clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}   
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;

?>

In a wordpress page I have this code, I build a form where if the user click the submit button call doLogin()

<script type="text/javascript"> function doLogin(){
    data = {username: jQuery("#user").val(), password: jQuery("#pass").val()}
    console.log(data);
    jQuery.ajax({
    type: "POST",
    url: "Mywebsiteurl.php",
    data: data,
    beforeSend: function(){

    },
    success: function(data){
        console.log(data);
        //var arr = JSON.parse(data);
        //$('#forma').html(data);

    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("Error");
        console.log(textStatus);
        console.log(errorThrown);
    }
});
} </script>

I need to show in <div id="forma"> a kind of list usign html, for example:

Id: VALUE ID Name: VALUE NAME

and more information...

When i try to print in my website the required information using $('#forma').html(data); I obtain error or just an empty space.

How can I fix it? thanks.

  • 写回答

2条回答 默认 最新

  • douwei1944 2016-02-16 10:46
    关注

    In WordPress we need to hook the ajax hook to your check_user function here.

    add_action('wp_ajax_your_action_from_js', 'your_function');
    
    //Using ajax for non-logged users as well (PUBLIC)
    add_action('wp_ajax_nopriv_your_action_from_js', 'your_function');
    

    Check below code for how it is done regarding your context.

    In functions.php

    function check_user() {
        $username = $_REQUEST['username']; 
        $password = $_REQUEST['password'];    
    
        if (isset($username) && isset($password)) {
        //CONEXION
            $host="localhost";
            $user="DB_Username";
            $pass="DB_Password";
            $dbname="DB_Name";
    
        //Conexion
        $conexion = mysqli_connect($host, $user, $pass,$dbname) 
        or die("unexpected error");
    
        //gWe made the search
        $sql = "SELECT * FROM Column WHERE A_Login='$username'";
        mysqli_set_charset($conexion, "utf8"); 
    
        if(!$result = mysqli_query($conexion, $sql)) die();
    
        $clients = array();
    
        $num_result = mysqli_num_rows($result);
    
            if ($num_result == 0) {
                $clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
            } else {
                while($row = mysqli_fetch_array($result)) 
                { 
                    $id=$row['ID'];
                    $Name=$row['Name'];
    
                    if ($row['A_Login'] == $username && $row['A_Password'] == $password){        
                        $clients[] = array('id'=> $id, 'Name'=> $Name);
                        } else {
                            $clients[] = array('error'=> "true", "msg" => "Incorrect data");
                            }
    
                }
            }
    
        $close = mysqli_close($conexion) 
        or die("Unespected error with DB");
          }
        else {
            $clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
        }   
        //We build the JSON
        $json_string = json_encode($clients);
        echo $json_string;
    }
    
    add_action('wp_ajax_check_user', 'check_user');
    
    //Using ajax for non-logged users as well (PUBLIC)
    add_action('wp_ajax_nopriv_check_user', 'check_user');
    

    In your JS called file.

    In the script the action is related to your _your_action_from_js. So action is needed for knowing where the ajax has to hit. In our case it executes our check_user and returns the appropriate values.

    <script type="text/javascript"> 
    function doLogin(){
        data = {action: 'check_user', username: jQuery("#user").val(), password: jQuery("#pass").val()}
        console.log(data);
        jQuery.ajax({
            type: "POST",
            url: ajax_url,
            data: data,
            beforeSend: function(){
    
        },
        success: function(data){
            console.log(data);
            //var arr = JSON.parse(data);
            //$('#forma').html(data);
    
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("Error");
            console.log(textStatus);
            console.log(errorThrown);
        }
    });
    } 
    </script>
    

    Reference Simple AJAX Form: http://wptheming.com/2013/07/simple-ajax-example/

    CODEX Reference: https://codex.wordpress.org/AJAX_in_Plugins

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 multisim中关于74ls192n和DSWPK开关的问题(相关搜索:计数器)
  • ¥15 在误装Windows server2019 后如何利用Windows.old恢复?
  • ¥20 代码实现状态连接包过滤防火墙的设计与实现
  • ¥15 vscode的红色箭头爆红和has no default export报错
  • ¥15 关于#sql#的问题:#情况描述 在用vs对项目进行调试时,出现找不到网络路径,然后查看SQL配置工具,发现SQL服务显示远程调用过程失败(相关搜索:防火墙)
  • ¥15 eNSP中基于默认路由及浮动路由的公司与分部互联和校园网综合项目
  • ¥15 主要进行描述泥浆在管路不同区段泥浆的密度不相同,泥浆的密度有高有低,此时管路的摩阻分布需要怎么计算,(标签-matlab)
  • ¥40 通过编制程序计算圆管内层流充分发展对流换热,参数如图5-4,以及公式5-16所示,要求用表5-6对程序计算准确性进行验证
  • ¥20 该学习哪个编程语言? AI会取代程序员吗?
  • ¥15 ensp如何拼通IP地址