How can I display user search results onto the same page inside a table?

问题: I'm trying to get some user search result data to print into a table on the same page the search was made from. I've searched for solutions here, but all of the examples ar...

问题:

I'm trying to get some user search result data to print into a table on the same page the search was made from. I've searched for solutions here, but all of the examples are using MySql. I'm currently just searching from a single .log file in the project. I've used an AJAX call to start the search from a button click. I can see that the search input does return a match from the .log file.
I'm fairly new to PHP (2 weeks!) and would love any suggestions on how to achieve this.

error-lookup.php

<?php
require_once $RootPath . "p/check-session.inc";
$RootPath = "";
$User = "";
$RetCode = 200;
$sProcess = "error-lookup.php";
?>

<!doctype html>
<html lang="en">
<head>
 <title>MyTools</title> 
<?php include_once ($RootPath."p/html-head.inc"); ?> 
</head>
<script>
function verifyAccount() {
    var pageData = {};
        errorData = $('#userInput').val();
    pageData['errorData'] = errorData;
    var param = JSON.stringify(pageData);
    $.ajax({
        global: false,
        "url": "p/search-log.php",
        data: pageData,
        cache: false,
        "type": "POST",
        dataType: "json",
        "complete": function (selectionData) {
            console.log(selectionData);
            try {
                var resultData = $.parseJSON(selectionData.responseText); 
                var output = "";
            for (var i = 0; i < resultData.length; i++) {
                var output = "<td>" + resultData[i].Id + "</td><br>" + "<td>" + resultData[i].Date + "</td><br>" + "<td>" + resultData[i].User + "</td><br>" + "<td>" + resultData[i].Message + "</td><br>" + "<td>" + resultData[i].StackTrace + "</td>";
                $("dataTable").append(output);
            }
            document.write(output);          
                $("dataTable").html(resultData);
            } catch (err) {
                showError(1,err);
            }
        }
    });
}
</script>
<body>
    <div class="page-header">
        <div class="container">
            <div class="row-fluid">
            <medium>Platform error code lookup</medium>
            </div>
        </div>
    </div>

    <form class="container">
        <input type="radio" name="tags[]" value="East-Coast" class="east-radio"/> 
            <label >East Coast Servers</label><br/>    
        <input type="radio" name="tags[]" value="West-Coast" class="west-radio"/>
            <label >West Coast Servers</label>
    </form><br>

           <div class="input-group mb-3">
                <form class="container" action="search-log.php" method="post">
                <input class="form-control" id="userInput" type="text" name="input_tag" placeholder="Enter error code or user name">
                <div class="input-group-append">
                <input class="btn btn-outline-secondary" value="Submit" name="submit_button" type="button" onclick="verifyAccount()"></input>
                </div>
                </form>

        <table class="table" id="dataTable">
        <tbody>
            <tr> 
                <th>Date</th>
                <th>Error Id</th>
                <th>User</th>
                <th>Message</th>
                <th>StackTrace</th>
            </tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
        </tbody>
    </table>

        <div class="container">
            <div id="test"></div>
        </div>
</body>
</html>

search-log

<?php 
$errorData = $_REQUEST["errorData"]; 
$errors = [];
$lines = file("../MyWeb.log", FILE_IGNORE_NEW_LINES);
foreach($lines as $line) {
    $tmp = [];
    $tmp["Date"] = substr($line, 0, 19);
    $pos = strpos($line, '{');
    $jsonObject = json_decode(substr($line, $pos),true);
    $tmp["Id"] = $jsonObject["Id"];
    $tmp["User"] = $jsonObject["User"];
    $tmp["Message"] = $jsonObject["Message"];
    $tmp["ServerName"] = $jsonObject["ServerName"];
    $tmp["StackTrace"] = $jsonObject["StackTrace"];
    array_push($errors, $tmp);
}
$results=[];
foreach($errors as $error){
    if (strpos($error["Date"], $errorData) > -1) {
        array_push($results, $error);
        continue;
    }
    if (strpos($error["Id"], $errorData) > -1) {
        array_push($results, $error);
        continue;
    }
    if (strpos($error["User"], $errorData) > -1) {
        array_push($results, $error);
        continue;
    }
    if (strpos($error["Message"], $errorData) > -1) {
        array_push($results, $error);
        continue;
    }
    if (strpos($error["ServerName"], $errorData) > -1) {
        array_push($results ,$error);
        continue;
    }
    if (strpos($error["StackTrace"], $errorData) > -1) {
        array_push($results, $error);
        continue;
    }
}
print_r($results);

回答1:

The flow is as follows:

-> $.ajax send a post with parameters;

-> You receive at your PHP script like any other post, does not need to json decode;

-> You select rows or anything you want to do, make a array or object structure, then return it with json_encode and Content-Type: application/json;

-> At success function, response will become a JS object as long as dataType is defined to Json;

Ok. First, to convert to JSON, you need to make an array or object, then, return it with json_encode. It will convert it into a JSON valid string that jQuery will parse correctly. Let's say you have a structure like: array ('name' => 'my_name'); When you JSON encode it, it will become a JSON string like { "name": "my_name" }

At our complete or success function, you will have responseText.name where the value will be "my_name". Now with it, you can do anything, like create a domNode with a div and insert it.

E.g.: you could create a table with id, then:

$('#id-of-my-table').append('<tr><td>' + rensponseText.name + '</td></tr>');

Of course this is a raw example, just to illustrate a really simple usage.


回答2:

Check if you are getting json in valid format before parsing it.

 $.ajax({
        global: false,
        "url": "p/search-log.php",
        data: pageData,
        cache: false,
        "type": "POST",
        "complete": function (selectionData) {
            // check if you are getting valid JSON before parsing it
            console.log(selectionData)
            try {
                var resultData = $.parseJSON(selectionData.responseText);           
                    $("#test").html(resultData);
            } catch (err) {
                showError(1,err);
            }
        }
    });

send data in json format

// send json from your php script

echo json_encode($results);

NOTE: you can use right click -> inspect -> network tab to check what your server is returning and whether the ajax call is being made.

Hope it helps!

  • 发表于 2018-07-08 10:07
  • 阅读 ( 274 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除