简体   繁体   中英

pass table size variable from js to php

I have a page in PHP with:

$sizelimit = "6"; 
include ('table.php');

It work fine displaying the last 6 mysql entries of my table generated by php on my main page (as a brief) and 20 or last entries if user access table.php directly. Now I am implementing ajax to load this same table every time it has a new entry, but how do I do to pass that variable $sizelimit from ajax to php so on my main page this table.php will have only 6 entries, but if table.php is accessed alone it has last 20 entries? my code now is:

 $sizelimit = "6"; 
// include ('table3.php'); 
echo'    <div id="results">Loading data ...</div>';

table.php is:

<?php   
require_once '../db/dbconfig.php';
// Create connection.
if ($sizelimit <> "" and $sizelimit > 0) {
$limit = $sizelimit;
} else {
$limit = "20";
}

$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
// Get the most recent 25 entries.
$result = mysqli_query($conn, "SELECT Time, T1, T2, Height FROM temp ORDER BY Time DESC, Time DESC  LIMIT ".$limit);
?>
<table class="table striped  bordered hoverable white">
    <tr><th>Time</th><th>Water Temp</th><th>Air Temp</th><th>Tank level</th></tr>
<?php
while($row = mysqli_fetch_assoc($result)) {
    echo "<tr><td>";
    echo $row["Time"];
    echo "</td><td>";
    echo $row["T1"];
    echo "&deg;C</td><td>";
    echo $row["T2"];
    echo "&deg;C</td><td>";
    echo $row["Height"];
    echo "mm</td></tr>";
}
echo "</tr></table>";

// Close connection.
mysqli_close($conn);
?>

thanks a lot

Implementing ajax, means you will make a request with those params you want to send, than listen for the response (which will return the table - with last 6 entries) and than make something with that response - preferably render it.

This way, you can send the $size parameter on your ajax request and keep the same logic.

The best practice would be to detect the ajax request, encode the table data as JSON and than make the rendering on client size. For this you can simply make the ajax request as POST, and at server side treat GET and POST with different responses.

AJAX EXAMPLE - This is an example of the client side logic, using plain JavaScript with no other frameworks required:

var getMyTable = function(url, data) {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
        if (xmlhttp.status == 200) {
            data = JSON.parse(xmlhttp.responseText);
            console.log('Post ajax call was a success')
            // SUCCESS - get ready to render the response.
            // call function responsible for data render
            // - in your case you can render all html response directly:
            displayTable(xmlhttp.responseText);
        } else if (xmlhttp.status == 400) {
            console.log('There was an error 400 for POST')
        } else {
            console.log('something else other than 200 was returned for POST! The status is ' + xmlhttp.status)
        }
        }
    }

    xmlhttp.open("POST", url, true);
    //...
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send(data);
};

function displayTable(htmlData) {
    // get the table element and update the data to display
    document.getElementById("#table-response").innerHTML = htmlData;
}

//This is a direct call - you can place it somewhere else.
getMyTable("/table.php", "limit=8");

On server side, detect if you have received data on POST and than update your logic...

$ajaxRequest = false;
if(isset($_POST["limit"])){
    $ajaxRequest = true;
    $sizelimit = $_POST["limit"];
}

if ($ajaxRequest) {
    // ... can do additional operations if needed.
}

// continue with your connection and $sizelimit check

When calling ajax use it like this :

.ajax({
    url: 'table.php',
    type: 'POST',
    data: { limit: "5"} ,
    contentType: 'application/json; charset=utf-8',
    success: function (response) {
        //success
    },
    error: function () {
        //error
    }
}); 

And in your php file :

require_once '../db/dbconfig.php';
// Create connection.
if(isset($_POST["limit"])){
   $sizelimit = $_POST["limit"];
}
if ($sizelimit <> "" and $sizelimit > 0) {
$limit = $sizelimit;
} else {
$limit = "20";
}

If you send 20 in javascript you will get 20, if you send 6 in javascript you will get 6. Hopefully it will solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM