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

报告相同问题?

悬赏问题

  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。