How to fetch data from mysql database while scrolling - php

I have a database and it contains more than 1000 records. I have to display it in front end php page, if I display all it will take more time to load so if user scrolls the information should be fetched after scrolling. Just like Facebook and Pinterest. How to achieve this...
My DB :- mysql
Server :- wamp

step 1] Take a help of little bit jquery as....
var countScroll= 0;
$(window).scroll(function()
{
if ($(window).scrollTop() == $(document).height() - $(window).height())
{
loadData();
}
countScroll++;
});
step 2] Take the help of ajax to call the loadData() function
function loadData()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var res = xmlhttp.responseText;
document.getElementById("respDiv").innerHTML=res;
}
}
xmlhttp.open("GET","loadPageData.php?loadLimit="+countScroll,true);
xmlhttp.send();
}
step 3] your php page i.e. loadPageData.php is as...
$loadLimit= $_GET['loadLimit'];
$result = mysql_query("SELECT * FROM tableName limit $loadLimit");
if(mysql_num_rows($result)>0)
{
while($row = mysql_fetch_array($result))
{
echo $yourVariable= $row['fieldName'];
}
}

Your question is generic and difficult to answer with snippet of code.
This could be a solution in pseudo-language
Fetch a default number of element (say 50) by doing a query like this SELECT * FROM yourTable WHERE ..... ORDER BY .... LIMIT 50
Use jQuery to detect scroll event
Make an AJAX call once you detect scroll event
Make a new query where you fetch 50 elements again, but this time take into account that you have scrolled (so, add a delta or offset)
Render elements returned from AJAX

Use jQuery (or your favourite library) to detect when the user gets to the end of the page, then just trigger an AJAX request to the server for the next N results.
For example:
JavaScript part:
var n = 0;
$(document).ready(function() {
$(window).scroll(function() {
if ($('body').height() <= ($(window).height() + $(window).scrollTop())) {
$.ajax({
url: "my_page.php",
data: {'n' : n},
context: document.body
}).done(function(data) {
n += 1;
console.log(data); // <--- do stuff with received data here
});
}
});
});
PHP part:
$n = $_POST['n'];
$n = 10 * $n;
$sql = "SELECT * FROM mytable LIMIT $n, 10"; // get 10 new entries each request.

Related

Calling a javascript function with ajax

I'm using a multiselect dropdown to filter images stored in my db. The results are paginated, however the pagination fails once the results are filtered. The filter uss ajax to make a php call to the database.
What I think is happening is that the once the results are loaded in the div the paginate javascript function has already fired and wont a second time. Is there a way to call the function everytime the results are filtered?
I believe I just need to recall this each time:
<script type="text/javascript">
jQuery(function($){
$('ul#items').easyPaginate({
step:6
});
});
</script>
Ajax call:
<script>
function filterResults(sel)
{
var selectedOptions = [];
for (var i = 0; i < sel.options.length; i++) {
if (sel.options[i].selected) {
selectedOptions.push("'" + sel.options[i].value + "'");
}
}
if (selectedOptions.length == 0) {
document.getElementById("divResults").innerHTML="";
return;
}
str = selectedOptions.join(",");
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("divResults").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","filter_ajax.php?filter="+str,true);
xmlhttp.send();
}
</script>
ajax_filter.php:
<?php
include ("connect.php");
$filter = $_GET["filter"];
$filterIn = $filter;
$result = mysql_query("SELECT * FROM edt_images
WHERE category1 IN ($filterIn)
OR category2 IN ($filterIn)
OR category3 IN ($filterIn)
OR category4 IN ($filterIn)
OR category5 IN ($filterIn)
OR category6 IN ($filterIn)")
or die(mysql_error());
echo "<div id='results_container'>";
echo "<ul id='items'>";
while ($row = mysql_fetch_array($result)) {
echo "<li><img src='files/300x200/thumb2_".$row['item_name'].".".$row['file_extension']."' class='filtered_images' border='0'/></li>";
}
echo "</ul>";
echo "</div>";
?>
If you are using jQuery you can simplify the code within the filterResults function greatly by utilizing the framework it provides. I would read up a bit here as you will be amazed by the extensive functionality.
This code is the jQuery equivalent of your previous code,
function filterResults(sel) {
var selectedOptions = [];
for (var i = 0; i < sel.options.length; i++) {
if (sel.options[i].selected) {
selectedOptions.push("'" + sel.options[i].value + "'");
}
}
if (selectedOptions.length == 0) {
$("divResults").html("");
return;
}
filteStr = selectedOptions.join(",");
$.ajax({
url: "http://www.google.com",
type: "get",
dataType: "html",
data: {
filter: filteStr
},
success: function (responseHtml) {
$("divResults").html(responseHtml);
//You can put your code here
$('ul#items').easyPaginate({
step: 6
});
},
error: function (responseHtml) {
//Handle error
}
});
}
To answer the question the code within the success callback of the ajax call will be executed upon a receiving the data back from the server. This code above should work as expected.
Almost everything to know lies here and here. ;)
Well
According to the comments I'll have to study up on javascript and jquery, never really was to concerned with it before.
Anyways by recalling the javascript function
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("divResults").innerHTML=xmlhttp.responseText;
RESTATING HERE
}
I was able to get it working.
Put javascript call into your php-ajax echo, example:
<?
$msg = "hello";
?>
<script type="text/javascript">alert("<?=$msg?>"></script>

Embed Ajax requests in bind events (XHR)

I'm trying to find the answer somewhere around but i can't,
So i'm having a .bind() event and I want when's triggered to make a get query from a php file with JSON like AJAX does.
I have tried the following which doesn't work:
$(document).ready(function() {
$("#adivhere").bind("valuesChanged", function(){
// Some variables here
var max2 = 10
var min2 = 5
//The classic AJAX Request
function afunc(max2,min2){
var xmlhttp;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
//The classic AJAX onreadystatechange function
xmlhttp.onreadystatechange=function()
{ if (xmlhttp.readyState==4 && xmlhttp.status==200){
//The code triggered
var fets = jQuery.parseJSON( xmlhttp.responseText );
var t = fets.date.split(/[-]/);
var d = new Date(t[0], t[1], t[2]);
alert(d);
}}
//The XHR request with the .php file and the
// two values that sends
xmlhttp.open("GET","getdates.php?max2="+max2+"&min2="+min2,true);
xmlhttp.send();
};
});
It looks like you're using jQuery, so this should work:
$(function(){
$('#adivhere').bind('valuesChanged',function(){
var max2 = 10;
var min2 = 5;
$.getJSON('getdates.php?callback=?', {max2: max2, min2: min2}, function(json){
alert(json);
var t = json.date.split(/[-]/);
if (t && t.length) {
var d = new Date(t[0], t[1], t[2]);
alert(d);
}
});
});
});
There's already an awesome $.getJSON method in jQuery that will do all of the heavy lifting for you, including return your results as JSON.
You'll need to make your getdates.php script echo the callback and wrap your results in parentheses so it returns as actual jQuery.
There are several "errors" in your script:
"afunc" is never called, so why should it be executed?
the parenthesis are not closed properly; at the end there are two missing: )}

Auto-save textarea every so many seconds

I need help with "auto-saving" a textarea. Basically, whenever a user is typing in the textarea, I would like to save a "draft" in our database. So for example, a user is typing a blog post. Every 15 seconds I would like for the script to update the database with all text input that was typed into the textarea.
I would like for this to be accomplished thru jQuery/Ajax but I cannot seem to finding anything that is meeting my needs.
Any help on this matter is greatly appreciated!
UPDATE:
Here is my PHP code:
<?php
$q=$_GET["q"];
$answer=$_GET["a"];
//Connect to the database
require_once('mysql_connect.php') ;
$sql="UPDATE english_backup SET q".$q."='".$answer."' WHERE student_id = {$_COOKIE['student']} LIMIT 1";
$result = mysqli_query($dbc, $sql);
?>
Here is my javascript code:
<script type="text/javascript">
function showUser(str, answer)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser_english.php?q="+str+"&a="+answer,true);
xmlhttp.send();
}
</script>
function saveText() {
var text = $("#myTextArea").val();
// ajax call to save the text variable
// call this function again in 15 seconds
setTimeout(saveText, 15000);
}();
I think you want something like ajax... I'm using ajax jQuery so you will need jQuery Library for it to work. Download it. You can find tutorials on the documentation tab of the website.
//in your javascript file or part
$("textarea#myTextArea").bind("keydown", function() {
myAjaxFunction(this.value) //the same as myAjaxFunction($("textarea#myTextArea").val())
});
function myAjaxFunction(value) {
$.ajax({
url: "yoururl.php",
type: "POST",
data: "textareaname=" + value,
success: function(data) {
if (!data) {
alert("unable to save file!");
}
}
});
}
//in your php part
$text = $_POST["textareaname"];
//$user_id is the id of the person typing
$sql = "UPDATE draft set text='".$text."' where user_id='".$user_id."'"; //Try another type of query not like this. This is only an example
mysql_query($sql);
if (mysql_affected_rows()==1) {
echo true;
} else echo false;
Hey everyone I'm still having a problem please see here https://stackoverflow.com/questions/10050785/php-parse-html-using-querypath-to-plain-html-characters-like-facebook-twitter

Display Multiple Records From SQL Query Using AJAX with Timer

I'm trying to find a good example on how to retrieve records using PHP from a table and refresh it say every 2 minutes using Ajax.
Anyone can point me to that tutorial?
I don't think you'll find a tutorial that specific, but you just need to learn AJAX and then make the AJAX call every two minutes using JavaScript's setInterval method.
EDIT
Meh, I'm bored enough to write this example. This isn't tested, but I don't think it has errors.
<html>
<head>
<script type="text/JavaScript">
window.onload = function()
{
// call your AJAX function every 2 minutes (120000 milliseconds)
setInterval("getRecords()", 120000);
};
function getRecords()
{
// create the AJAX variable
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
// set up the response function
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
/*
Your code goes here. 'xmlhttp.responseText' has the output from getRecords.php
*/
document.getElementById("txaRecords").innerHTML = xmlhttp.responseText;
}
}
// make the AJAX call
xmlhttp.open("GET", "getRecords.php", true);
xmlhttp.send();
}
</script>
</head>
<body>
<textarea id="txaRecords"></textArea>
</body>
</html>
This is a bit of code that I wrote for this exact purpose. Adapt as appropriate.
AJAX code:
function timer()
{
var t=setTimeout("check()",2000);
// At an appropriate interval
}
function check(){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if (xmlhttp.responseText!=""){
var output = xmlhttp.responseText;
// Do what you need to do with this variable
}
}
}
xmlhttp.open("GET","backend.php",true);
// Set file name as appropriate.
xmlhttp.send();
timer();
}
PHP code:
<?php
// This assumes you have already done mysql_connect() somewhere.
// Replace as appropriate
$query = "SELECT * FROM table_name";
// Perform the query
$result = mysql_query($query);
// Get the results in an array
while($row = mysql_fetch_array( $result )) {
// Echo the message in an appropriate format.
echo "<br />" . $row['column_name'];
}
?>
Remember to initiate one of the JS functions as you load the page:
<body onload="timer()">

I want to send multiple piece of data using a single variable to a database (using JS, PHP and AJAX)

I am not aware of the proper terminology or jargon with programming, so forgive me if this question is unclear. To make if more clear here is the code I have written so far. I will explain the problem in more detail after the code:
I use this code to retrieve data from Facebook:
function rsvpEvent() {
FB.api('/me/events/', function(response) {
for (var i=0; i<=2; i++) {
eventname=response.data[i].name;
eventid=response.data[i].id;
eventstatus=response.data[i].rsvp_status;
eventInfo(eventname,eventid,eventstatus);
strEvent=strEvent + "You are " +
eventstatus + " " + eventname + ", EID: " + eventid + "<br/>";
}
document.getElementById('rsvpEvent').style.display = "block";
document.getElementById('rsvpEvent').innerHTML = strEvent;
});
}
Request to PHP file (containing mySQL calls):
function eventInfo(eventname,eventid,eventstatus) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("eventInfo").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","event_info.php?eventName=" + eventname + "&eid=" + eventid +
"&rsvp_status=" + eventstatus,true);
xmlhttp.send();
}
So, the issue is that I need to store individual event names, ids and statuses and the code as it stands now. I can output them to a page individually, but cannot send them to the PHP file individually. How do I do this (presuming it is possible)?
Use jQuery for your ajax call to your php script.
$.post('/somefile.php', myJSobjectOrArr, function(data) {
// return something from your script to say it succeeded or not...
console.log(data);
}
In your php script just check your $_POST variable and serialize() or json_encode() it and pop it into your database.
To get your data back just unserialize() or json_decode() it.
You can join eventnames with comma(,) ,and when reading those data to save into database you can delimit comma(,), means remove commas from that and store each event name to database..
This is what i understand according to your problem..

Categories