如何从php返回php变量值以及html响应ajax

how to return php variables values along with html response ajax from php

本文关键字:php html 响应 ajax 变量值 返回      更新时间:2023-09-26

我想返回两个变量:

1) 来自search_members.php 的mysqli查询的记录总数

2) 如果发现任何结果,则为true或false

这是我的代码:

<input type="button" value="Search" onclick="GetSearchResults(0)" 
       class="SrchBtn" />
<script>
var pageNo = 1;
var DoSearch;
var SearchString = "";
function GetSearchResults()
{
    DoSearch = false;
    if (document.getElementById("SearchString").value > 0) {
        SearchString = document.getElementById("SearchString").value;
        DoSearch = true;
        if (DoSearch === true) {
            $.ajax({
                type: 'POST',
                url: 'search_members.php',
                data: { SearchString: SearchString, pageNo: pageNo},
                success: function(response) {
                    $('#SearchReultsBox').html(response);
                }
            });
        }
    }
}
</script>

我想要得到的变量值是$SearchFound和$total_pages,如下所示这是search_members.php 的代码

 <?php
include_once('dbConnect.php');
$SearchFound=false;
$Items_PerPage=10;
if (!empty($_POST['SearchString']))
{
    $SearchString= $_POST['SearchString'] ; 
    $SearchString = trim(htmlentities($SearchString));
    $SearchString= strip_tags($SearchString);
    $SearchString= mysqli_real_escape_string($con,$SearchString);
}
$pageNo=$_POST['pageNo'];

$sql="SELECT * from members where member_name=$SearchString";
$result = $con->query($sql); 
$num_rec = mysqli_num_rows($result);
if ($num_rec>0)
{
    $SearchFound=true;
        $total_pages = ceil($num_rec / $Items_PerPage);
        $start_from = ($pageNo-1) * $Items_PerPage;     
        $sql .= " LIMIT $start_from, $Items_PerPage";   
        $result = $con->query($sql);
        $total_page_records = mysqli_num_rows($result); 
        while($row = mysqli_fetch_array($result))
        {
            //echo "<table>";.......display table with results
        }
}
else
{
    echo "<p>no resutls found</p>";
}
?>

如果您想要一个Collection或多个Scalar Value(如HTML Text或Simple String),则可能需要返回JSON。在这里像这样:

    <script>
        var pageNo          = 1;
        var SearchString    = "";
        var DoSearch;
        function GetSearchResults() {
            DoSearch    = false;
            if(document.getElementById("SearchString").value>0) {
                SearchString = document.getElementById("SearchString").value;
                DoSearch=true;
                if (DoSearch===true) {
                    $.ajax({
                        type:       'POST',
                        dataType:   'JSON',     //EXPLICITLY SET THIS TO JSON
                        url:        'search_members.php',
                        data:       { SearchString: SearchString, pageNo: pageNo},
                        success:    function(response) {
                            // YOUR AJAX REQUEST RETURNS JSON DATA WITH ONLY 2 VALUE TYPES - INTEGER & BOOLEAN
                            // NOW IF YOU WANT TO DISPLAY YOUR SEARCH RESULT 
                            // YOU MAY WANT TO BUILD THAT IN YOUR PHP FILE (PERHAPS WITH A KEY LIKE SO: html
                            // AFTERWARDS YOU MIGHT BE ABLE TO DO:
                            //$('#SearchResultsBox').html(response.html);
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            console.log('Error: '+jqXHR.responseText);
                        }
                    });
                }
            }
        }
    </script>

转到等式的PHP方面;你可能想做这样的事情:

<?php
    /**
     * search_member.php
     */
    include_once('dbConnect.php');
    $SearchFound    = false;
    $Items_PerPage  = 10;
    //DECLARE DEFAULT RESPONSE PAYLOAD 
    $response       = array(
        "message"       => "<p>no resutls found</p>",
        "numRecords"    => null,
        "searchFound"   => false,
    );
    $searchString   = isset($_POST['SearchString']) ? htmlspecialchars(trim($_POST['SearchString']))    : null;
    $pageNo         = isset($_POST['pageNo'])       ? htmlspecialchars(trim($_POST['pageNo']))          : null;
    if ($searchString) {
        $SearchString   = strip_tags($SearchString);
        $SearchString   = mysqli_real_escape_string($con,$SearchString);
    }

    $sql        = "SELECT * FROM members WHERE member_name='{$SearchString}'";
    $result     = $con->query($sql);
    $num_rec    = mysqli_num_rows($result);
    if ($num_rec>0) {
        $SearchFound        = true;
        $total_pages        = ceil($num_rec / $Items_PerPage);
        $start_from         = ($pageNo-1) * $Items_PerPage;
        $sql               .= " LIMIT {$start_from}, {$Items_PerPage}";
        $result             = $con->query($sql);
        $total_page_records = mysqli_num_rows($result);
        //SINCE YOU WANT TO ONLY RETURN 2 VALUE: DO IT HERE INSTEAD:
        $response           = array(
            "message"       => "The World is Good and Everyone is Smiling like you, now.... ;-)",
            "numRecords"    => $total_page_records,
            "searchFound"   => $SearchFound
        );
        /*
        while($row = mysqli_fetch_array($result)){
            //echo "<table>";.......display table with results
        }
        */
    }else{
        //REMEMBER YOU ARE RETURNING JSON DATA SO NO NEED TO ECHO A HTML DATA RATHER SEND IT BACK AS A PAYLOAD
        //echo "<p>no resutls found</p>";
    }
    //SEND BACK A JSON PAYLOAD BASED ON THE RESPONSE DATA
    die( json_encode($response) );
?>