How to pass PHP variable to AJAX URL - javascript

Hello guys I am new to javascript
I am trying to send php variable to AJAX url file but i was unable to do it. I don't know where the problem actually arise. your help will be highly appreciated
Here i want to send the below PHP Variable "$cheque" to the AJAX URL Page cheque_select.php
<php? $cheque = '78964Y' ?>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"cheque_select.php",
method:"POST",
dataType:"json",
success:function(data)
{
var html = '';
for(var count = 0; count < data.length; count++)
{
html += '<tr>';
html += '<td><input type="checkbox" id="'+data[count].id+'" data-cheque_no="'+data[count].cheque_no+'" data-id="'+data[count].id+'" data-name="'+data[count].name+'" data-sum="'+data[count].sum+'" data-account="'+data[count].account+'" class="check_box" /></td>';
html += '<td>'+data[count].cheque_no+'</td>';
html += '<td>'+data[count].id+'</td>';
html += '<td>'+data[count].name+'</td>';
html += '<td>'+data[count].sum+'</td>';
html += '<td>'+data[count].account+'</td></tr>';
}
$('tbody').html(html);
}
});
}
fetch_data();
This is my cheque_select.php i want to fetch data from mysql by the above variable
<?php
include('connection.php');
$query = "select * FROM entry where entry.bank= $cheque";
$statement = $connect->prepare($query);
if($statement->execute())
{
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
}
?>

Simply add a "data" value in the ajax/jquery request you are firing. This will send data in the form of a POST value to the page that is receiving your ajax request. This is the revised "fetch_data" function after adding the data you wish to send:
function fetch_data()
{
$.ajax({
url:"cheque_select.php",
method:"POST",
dataType:"json",
data:{"cheque":"<?= $cheque ?>"},
success:function(data)
{
var html = '';
for(var count = 0; count < data.length; count++)
{
html += '<tr>';
html += '<td><input type="checkbox" id="'+data[count].id+'" data-cheque_no="'+data[count].cheque_no+'" data-id="'+data[count].id+'" data-name="'+data[count].name+'" data-sum="'+data[count].sum+'" data-account="'+data[count].account+'" class="check_box" /></td>';
html += '<td>'+data[count].cheque_no+'</td>';
html += '<td>'+data[count].id+'</td>';
html += '<td>'+data[count].name+'</td>';
html += '<td>'+data[count].sum+'</td>';
html += '<td>'+data[count].account+'</td></tr>';
}
$('tbody').html(html);
}
});
}
Then on the page that is receiving the request, you would get the cheque value by saying php $_POST['cheque'] . Also one mistake I noticed is you have mistyped your opening PHP tag. You have wrote <php? . The correct way is <?php .
One more thing - you haven't prepared your statement correctly in the PHP page. This is how you should prepare it:
$pre_stmt = "SELECT * FROM entry WHERE entry.bank=?";
$stmt = $conn->prepare($pre_stmt);
$stmt->bind_param(
"i", # if cheque is a numerical value keep it "i" otherwise change it to "s" if it is a string
$cheque
);
$stmt->execute();
#do whatever success condition
Preparing statements like this prevents SQL injection

Add data in your AJAX request like -
<?php $cheque = '78964Y' ?>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"cheque_select.php",
method:"POST",
dataType:"json",
data:{'cheque': "<?php echo $cheque; ?>"},
success:function(data)
{
var html = '';
for(var count = 0; count < data.length; count++)
{
html += '<tr>';
html += '<td><input type="checkbox" id="'+data[count].id+'" data-cheque_no="'+data[count].cheque_no+'" data-id="'+data[count].id+'" data-name="'+data[count].name+'" data-sum="'+data[count].sum+'" data-account="'+data[count].account+'" class="check_box" /></td>';
html += '<td>'+data[count].cheque_no+'</td>';
html += '<td>'+data[count].id+'</td>';
html += '<td>'+data[count].name+'</td>';
html += '<td>'+data[count].sum+'</td>';
html += '<td>'+data[count].account+'</td></tr>';
}
$('tbody').html(html);
}
});
}
fetch_data();
It will send the cheque value to the server end.
And get it at the PHP end just before the query by adding -
<?php
include 'connection.php';
$cheque = $_POST['cheque'];
$query = "SELECT * FROM entry WHERE entry.bank = ?";
$statement = $connect->prepare($query);
$statement->execute([$cheque]);
$data = $statement->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($data);

Related

Ajax Datatable How to display data from a function?

I have an Ajax which get data from php file and display in Datatable,it works but when I added function to the php file then my Ajax cannot get data from the file anymore, what should I modify to my Ajax file.
Also, what if I want to change the ajax function to be called depends on the value I post.For example, I have 2 function, A & B, and I will post data called db from the select in my html, if the data is A then Ajax A will be executed.
Can I do this: $(document ).on('_GET','#db==A',function() {
Ajax.js
$(document ).on('click','#showData',function() {
$.ajax({
type: 'GET',
url: 'table_backend.php',
mimeType: 'json',
success: function(data2) {
var aaData=data2['aaData'];
$.each(aaData, function(i, data) {
var body = "<tr>";
body += "<td>" + data.id+ "</td>";
body += "<td>" + data.show_activity_id + "</td>";
body += "<td>" + data.nasa_id + "</td>";
body += "<td>" + data.game_show_id + "</td>";
body += "<td>" + data.account_id + "</td>";
body += "</tr>";
$( "#showTable" ).append(body);
});
$( "#showTable" ).DataTable();
},
error: function() {
alert('Fail!');
}
});
});
table_backend.php
(My file is too big so I didn't post code about my db)
I added class and function:
$t = new table;
if(isset($_POST['db'])){
if ($_POST['db'] == "show") { $t -> tableShow($connData); }
if ($_POST['db'] == "show_activity") { $t -> tableShowAc($connData);}
}
class table{
function tableShowAc($connData){
My Ajax works before I add function:
## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = mysqli_real_escape_string($connData['conn'],$_POST['search']['value']); // Search value
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " and (id like '%".$searchValue."%' or
show_activity_id like '%".$searchValue."%' or
game_show_id like'%".$searchValue."%' ) ";
}
## Total number of records without filtering
$sel = mysqli_query($connData['conn'],"select count(*) as allcount from analysis_data.show_activity");
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];
## Total number of record with filtering
$sel = mysqli_query($connData['conn'],"select count(*) as allcount from analysis_data.show_activity WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];
## Fetch records
$empQuery = "SELECT * from analysis_data.show_activity";
$empRecords = mysqli_query($connData['conn'], $empQuery);
$data = array();
while ($row = mysqli_fetch_assoc($empRecords)) {
$data[] = array(
"id"=>$row['id'],
"show_activity_id"=>$row['show_activity_id'],
"nasa_id"=>$row['nasa_id'],
"game_show_id"=>$row['game_show_id'],
"account_id"=>$row['account_id']
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
echo json_encode($response);
return json_encode($response);
Html
<label >Select a table:</label>
<select name="db" id="db">
<option value="">Please select a table</option>
<option value="show">show</option>
<option value="show_activity">show_activity</option>
<option value="show_incentive">show_incentive</option>
<option value="show_mulp_detail">show_mulp_detail</option>
</select>
<button id="showData" type="submit">Select</button>
</form>
<table id="showTable" class="display dataTable">
<thead>
<tr>
<td>ID</td>
<td>show_activity_id</td>
<td>nasa_id</td>
<td>game_show_id</td>
<td>account_id</td>
</tr>
</thead>
</body>
</html>
What I could understand from your question is, you want to grab data {table data} from php, and you have mentioned you want to grab 2 different data (as you have mentioned A&B)
What I would suggest is to use post in ajax and send the parameters to the file, and then handle the request according to the parameters given.
but when I added function to the php file then my Ajax cannot get data from the file anymore, I don't see any function in php but I think you meant something like this..?
<?php
function something(){
//data query and search
echo //the JSON result
}
?>
Here is something you can do with Ajax to get 2 different data.
<!-- A simple select in HTML -->
<select name="dbdata" onchange="ajaxCall(this.value)">
<option > Choose a value </option>
<option value='a' > A </option>
<option value='b' > B </option>
</select>
<!-- Script for AJAX call -->
<script>
//function ajaxCall
function ajaxCall(val){
//If you wanna use GET
$.get("table_backend.php",
{ type : "tabledata", db : val },
function(data, status){
if(status == "success"){
console.log(data);//for debugging purpose
//Now do your stuff here and fill data in HTML table
}
else console.log("Error while getting data from server..!");
}
);
//If you wanna use POST
//Just use $.post instead of $.get
}
</script>
Now the php { table_backend.php }
<?php
//Grab the parameters from request.
//$_GET or $_POST according to request made from Ajax.
if(isset($_GET['type'])){
$type = $_GET['type'];
$db = $_GET['db'];
}
else echo "no parameters..!";
if($type == "tabledata"){//Just to ensure everything works fine nothing much
if( $db == 'a' ){
//Gonna call a function to get data for db=a
//As you have mentioned you have function in php so call that function here
getDBdata_A();//function to get DB data for db=a
}
else if($db == 'b'){
getDBdata_B();//function to get DB data for db=b
}
}
//Here are function definitions
getDBdata_A(){
//Do your stuff here
//Querying and searching whatever
echo echo json_encode($response);//The result
}
getDBdata_B(){
//Do your stuff here
//Querying and searching whatever
echo echo json_encode($response);//The result
}
?>
Hope this helps in someway...
Feel free to comment down for any queries.

dynamicly added row cannot run autofill ajax script

i am new to programming. so i want to make a table that user can add new rows by clicking a button.
and in that rows, user can input one fields (ID) with some registered series of numbers and then the other fields (parts name) shows the part's name according my other table.
I managed to create a code that works on adding new rows and autofill via ajax.
but unfortunately, the autofill only works on top/first row. but when i input ID on second or third row, the parts name's field did not show up.
what am i missing? this is my add row code:
<script>
var no = 0;
function addItem() {
no++;
var html = "<tr>";
html += "<td>" + no + "</td>";
html += "<td><input type='text' name='id_sap[]' onkeyup='autofills()' id='sappart' required></td>";
html += "<td><input type='text' name='material_name[]' id='namapart' required></td>";
html += "<td><input type='number' name='outcoming_qty[]' required /></td>";
html += "<td><button type='button' onclick='deleteRow(this);'>Delete</button></td>"
html += "</tr>";
var row = document.getElementById("tbody").insertRow();
row.innerHTML = html;
}
function deleteRow(button) {
button.parentElement.parentElement.remove();
// first parentElement will be td and second will be tr.
</script>
and this is my autofill code:
<script type="text/javascript">
function autofills(){
var parts = $('input[name="id_sap[]"]').val();
var sloc = $('input[name="tarea"]').val();
$.ajax({
url: 'ajax1.php',
data: {"id_sap":parts,"storage_location":sloc},
}).success(function (data) {
var json = data,
obj = JSON.parse(json);
$('input[name="material_name[]"]').val(obj.material_name);
});
}
</script>
and this is my ajax page:
<?php
//membuat koneksi ke database
$koneksi = mysqli_connect("localhost", "shaun", "godbless19", "dboptima");
//variabel nim yang dikirimkan form.php
$nomorsap = $_GET['id_sap'];
$areas = $_GET['storage_location'];
//mengambil data
$query = mysqli_query($koneksi, "SELECT * FROM material_card where id_sap = '$nomorsap' and storage_location = '$areas'");
$spare = mysqli_fetch_array($query);
$data = array(
'material_name' => $spare['material_name']);
//tampil data
echo json_encode($data);
?>
please help me , i have been wasting too much effort and time to solve this
so far i keep looking similar issues on stack overflow, none of them seems to work.
thank you very much
best regards
Try the following:
$(document).on('keyup', "#sappart input[type='text']", function() {
var parts = $('input[name="id_sap[]"]').val();
var sloc = $('input[name="tarea"]').val();
$.ajax({
url: 'ajax1.php',
data: {
"id_sap": parts,
"storage_location": sloc
},
}).success(function(data) {
var json = data,
obj = JSON.parse(json);
$('input[name="material_name[]"]').val(obj.material_name);
});
});

How can I use an array I created with php in a js function

I wrote a tool, that creates an array from a database (when the site is loaded) in php and would now like to use js functions to change the way this array is displayed in a table (different ranges, columns etc.).
How can I pass the php array to js, so I can use it in the js functions.
already tried this in the "script" section
<?php
$js_data = json_encode($data);
echo"var data = ".$js_data.";\n";
?>
function loadCompleteTable(){
table += '<table>';
for(var row in data){
table += '<tr>';
for(var col in data[row]){
table += '<td>';
table += data[row][col];
table += '</td>';
}
table += '</tr>';
}
table += '</table>';
document.getElementById("tablePlaceholder").innerHTML = table;
}
You can pass an array from PHP to javascript like this:
var js_array = JSON.parse('<?php echo json_encode($php_array); ?>');
Or if you prefer:
echo "var js_array = JSON.parse('".json_encode($php_array)."');";
I know you could just use:
var js_array = <?php echo json_encode($php_array); ?>;
But i find it less reliable. Unfortunately, I can't find anything in the docs to prove what I am saying, but I had some troubles in the past, mostly SyntaxError, that was resolved by using JSON.parse instead of just echoing the array as javascript code.
var data = <?php echo json_encode($data); ?>;
function loadCompleteTable()
{
var table = '';
table += '<table>';
for(var row in data){
table += '<tr>';
for(var col in data[row]){
table += '<td>';
table += data[row][col];
table += '</td>';
}
table += '</tr>';
}
table += '</table>';
document.getElementById("tablePlaceholder").innerHTML = table;
}

What is wrong with my Javascript and $POST concatenation?

I am using Ajax to add 3 values to my database, and then immediately append them at the bottom of my Table using the following:
**EDIT: Added the full code, and I currently only adding 1 value to the database, leaving the others empty (Adding only Text1)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
$("#Submit").click(function (e) {
e.preventDefault();
if($("#Text1").val()==='')
{
alert("Please enter some text!");
return false;
}
var myData = 'txt1='+ $("#Text1").val(); //build a post data structure
jQuery.ajax({
type: "POST",
url: "ajax.php",
dataType:"text",
data:myData,
success:function(response){
var row_data = "";
row_data +="<tr><td><?php echo $_POST['txt1'] ; ?></td><td><?php echo $_POST['txt1'];?></td><td><?php echo $_POST['txt1'];?></td></tr>";
$("#mytable").append(row_data);
$("#responds").append(response);
$("#Text1").val(''); //empty text field on successful
$("#FormSubmit").show(); //show submit button
$('table').html(data);
},
error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show(); //show submit button
alert(thrownError);
}
});
});
});
</script>
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "test_database";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
echo "Connected successfully";
if(isset($_POST["txt1"]) && strlen($_POST["txt1"])>0)
{
$contentToSave = filter_var($_POST["txt1"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$insert_row = $mysqli->query("INSERT INTO test_table(fname) VALUES('".$contentToSave."')");
if($insert_row)
{
$mysqli->close(); //close db connection
}else{
header('ERROR');
exit();
}}
?>
<div class="form_style">
<textarea name="content_txt" id="Text1" cols="45" rows="1"></textarea><br>
<button id="Submit">Add record</button>
</div><br>
<table class="table" id="mytable" style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
//initially filling the table with db data
<?php
$sql = "SELECT fname, lname, age FROM test_table";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["fname"] . "</td><td>" . $row["lname"] . "</td><td>" . $row["age"] . "</td></tr>";
}
} else {
echo "0 results";
}
$mysqli->close();
?>
</table>
</body>
</html>
The posting does work: txt1, txt2 and txt3 are inserting into the database, but what I see at the bottom of the table is '.$_POST['txt1'].' and so on, instead of the actual POST data
if you want to use php code in javascript then try below ==>
success:function(response){
var row_data = "";
row_data +="<tr><td><?php echo $_POST['txt1'] ; ?></td><td><?php echo $_POST['txt2'];?></td><td><?php echo $_POST['txt3'];?></td></tr>";
The argument you named response in the declaration of the function for success setting of the ajax call (I assume you are using jQuery's $.ajax) contains whatever your Web server sent to you.
In your case if you send AJAX request to the code you provided, that is, if the code you provided is exactly that ajax.php you referenced in the url setting of the jQuery.ajax call, THEN THE response VAR WILL CONTAIN FULL HTML TEXT RENDERED, which is probably absolutely useless to you.
Proper usage of the AJAX would be like this:
$.ajax({
// ...
dataType: 'json', // I can remember incorrectly here. It assumes your PHP backend sends JSON-encoded string.
success: function (data) { // data will be an object already parsed from JSON string sent by server.
var row_data = "";
row_data += "<tr><td>";
row_data += data.txt1;
row_data += "</td><td>";
row_data += data.txt2;
row_data += "</td><td>";
row_data += data.txt3;
row_data += "</td></tr>";
}
});
Move the block of code starting with if(isset($_POST["txt1"]) && strlen($_POST["txt1"])>0) to the very beginning of the file and do the following on successful insert to the database:
header("Content-Type: application/json");
echo json_encode(['txt1' => $_POST['txt1'], 'txt2' => #$_POST['txt2'], 'txt3' => #$_POST['txt3']);
die();
This way when handler registered in success will be entered, the response will contain the proper JSON block. You don't need to re-render the whole page on AJAX requests.
You don't need the $("#responds").append(response); block because it'll lie to you due to rendering of the response contents according to HTML rendering rules. Just use the F12 in browser and inspect the server response directly.

Page Scrolling Effect With Ajax How Data Is Loaded Into The Page

I am loading data from a mysql table into a html table. I am using AJAX php Jquery to accomplish this. I need to make sure that the way I built this will work regardless of how much data is in the table.
Right now I am working with a table that is 5000 rows long but there will eventually be 88000 rows in this table.
I know if I load all the data on page load this could end up bogging down the server and the load time of the page.
My question is the way my logic is now will it load all the results into the $results and only query the needed amount of rows because it is paginated. Or even though it is paginated is my webpage taking every row in the whole database for load time.
if the whole table is being loaded how can I change the query to only load the data when needed. It loads on page scroll.
Also I need to write a search function. Since the data is paginated would I search the data in $results or query the table with separate search functions? Which way would provide less load times which would cause a bad experience for my user?
The AjAX
<script type="text/javascript">
jQuery(document).ready(function($) {
var busy = true;
var limit = 5;
var offset = 0;
var assetPath = "<?php echo $assetPath ?>"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#productResults").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('Loading... Please wait <img src="http://www.wuno.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
(function($) {
$(document).ready(function() {
if (busy == true) {
displayRecords(limit, offset);
busy = false;
}
});
})( jQuery );
(function($) {
$(document).ready(function() {
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#productResults").height() && !busy) {
offset = limit + offset;
displayRecords(limit, offset);
}
});
});
})( jQuery );
});
</script>
This is how I am querying the database
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 5;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$sql = "SELECT * FROM wuno_inventory WHERE 1 ORDER BY id ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
By transferring a JSON object from the server the limit, offset and html (and maybe others lime status_messsage, etc.) values could be transferred to the client at the same time.
On the client side I meant something like this:
var limit = 5;
var offset = 0;
var assetPath = "<?php echo $assetPath ?>"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
dataType: "json", // We expect to receive a json object
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(json) {
limit = json.lim; // corr to $output['lim']
offset = json.offs; // corr to $output['offs']
$("#productResults").append(json.html); // corr to $output['html']
$('#loader_image').hide();
if (json.html == "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('Loading... Please wait <img src="http://www.wuno.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
...and on the server side:
$limit = (intval($_REQUEST['limit']) != 0 ) ? $_REQUEST['limit'] : 5;
$offset = (intval($_REQUEST['offset']) != 0 ) ? $_REQUEST['offset'] : 0;
$sql = "SELECT * FROM wuno_inventory WHERE 1 ORDER BY id ASC LIMIT $limit OFFSET $offset";
// Make sure to handle invalid offset values properly,
// as they are not validated from the last request.
// Prepare the $output structure (will become a json object string)
$output = array(
'lim'=>$limit,
'offs'=>$offset+$limit,
'html'=>''
);
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
$output['html'] .= $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
$output['html'] .= '<tr class="invent">';
$output['html'] .= '<td>' . $res['wuno_product'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_alternates'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_description'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_onhand'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_condition'] . '</td>';
$output['html'] .= '</tr>';
}
}
// Now encode $output as a json object (string) and send it to the client
header('Content-type: application/json; charset=utf-8');
echo json_encode($output, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_FORCE_OBJECT);
I do this exact thing you want on my site http://www.flixnetforme.com/ where as you can see as you scroll to the bottom of the page the next set of records is loaded. I have over 150,000 records but it only loads 36 at a time when the user scrolls to the bottom of the page.
The way you want to do this is is by loading your first initial records through ajax and not hardcode them into the page.
index.php
$(document).ready(function(){
var last_id;
if (last_id === undefined) {
genres = $("#genres").val();
$.ajax({
type: "POST",
url: "includes/getmorefirst.php?",
data: "genres="+ genres,
success: function(data) {
$( ".append" ).append(data);
}
});
};
};
<html><div class="append"></div></html>
In this example when the user gets to the page and is loaded it calls getmorefirst.php and return the first records.
getmorefirst.php is a file that will load the first set amount of records you want to show when the user gets to the page. In my case I load 36 records at a time when a user scrolls to the bottom of my page.
getmorefirst.php
$sql = "SELECT * FROM table ORDER BY ID ASC LIMIT 36"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$last_id = $row['ID'];
echo '<div>'.$row['column'].'</div>';
echo '<div style="display:none" class="last_id" id="'.$last_id.'"';
}
The last_id div is important so that ajax will know the last record sent and which one to pick up after when it loads the next set of 36 records.
.append is the div where I am appending the data from ajax when the user its the bottom.
.last_id is your key to knowing how to load the next set of records. In whatever order you send the records back its important that ajax knows the last ID of the record loaded so it knows where to start loading the next time ajax calls for more records. In my case when the users scrolls to the bottom of the page.
when user scrolls to bottom of index.php
if($(window).scrollTop() === $(document).height() - $(window).height()) {
last_id = $(".last_id:last").attr("id");
$.ajax({
type: "POST",
url: "includes/getmore.php?",
data: "last_id="+ last_id,
success: function(data) {
$( ".append" ).append(data);
}
});
return false;
};
};
last_id = $(".last_id:last").attr("id"); will get the last ID sent.
data: "last_id="+ last_id, will send the last id to getmore.php so it knows the last id of the record sent.
getmore.php
$sql = "SELECT * FROM table WHERE ID > '$last_id' ORDER BY ID ASC LIMIT 36"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$last_id = $row['ID'];
echo '<div>'.$row['column'].'</div>';
echo '<div style="display:none" class="last_id" id="'.$last_id.'"';
}
As you can see getmore.php will return the next 36 records but AFTER the last_id sent.
Hope this make sense and gives you a start.
Here is a reduced example of the JSON / AJAX mechanism that I have tested:
HTML (file test.html)
<html>
<head>
<!-- THE NEXT LINE MUST BE MODIFIED -->
<script src="../jquery-1.4.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
var limit = 5;
var offset = 0;
// THE NEXT LINE MUST BE MODIFIED
var assetPath = "http://www.example.com/stackoverflow/test.php"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
url: assetPath,
dataType: "json", // We expect to receive a json object
data: "limit=" + lim + "&offset=" + off,
async: true,
cache: false,
beforeSend: function() {
$("#content").html("");
},
success: function(json) {
limit = json.lim; // corr to $output['lim']
offset = json.offs; // corr to $output['offs']
$("#content").html(json.html);
window.busy = false;
}
});
}
</script>
</head>
<body>
<div id="content"></div>
<div onclick="displayRecords(limit,offset); return false;" style="cursor:pointer">Click to Call</div>
</body>
</html>
PHP (file test.php)
<?php
$limit = (intval($_REQUEST['limit']) != 0 ) ? $_REQUEST['limit'] : 5;
$offset = (intval($_REQUEST['offset']) != 0 ) ? $_REQUEST['offset'] : 0;
// Prepare the $output structure (will become a json object string)
$output = array(
'lim'=>$limit,
'offs'=>$offset+$limit,
'html'=>''
);
$output['html'] .= '<span style="color:red;">limit='.$output['lim'].', offset='.$output['offs'].'</span>';
// Now encode $output as a json object (string) and send it to the client
header('Content-type: application/json; charset=utf-8');
echo json_encode($output, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_FORCE_OBJECT);
Result
1st time
2nd time
nth time

Categories