I am trying to use infinite scrolling to load the next 5 peices of content onto my screen without reloading the entire page. I have tried about a million things. I have the scroll bar tracking working great, but I have no idea how to set up an ajax request to load additional content when the scroll bar script is activated. Please help I have been stuck on this for two days.
here is my java script:
<script type="text/javascript">
function yHandler(){
var wrap = document.getElementById('wrap');
var contentHeight = wrap.offsetHeight;
var yOffset = window.pageYOffset;
var y = yOffset + window.innerHeight;
if(y >= contentHeight){
// Ajax call to get more dynamic data goes here
wrap.innerHTML += '<div class="newData"></div>';
}
var status = document.getElementById('status');
status.innerHTML = contentHeight+" | "+y;
}
window.onscroll = yHandler;
</script>
here is my php file to connect to my database:
<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_dbConn = "localhost";
$database_dbConn = "Video";
$username_dbConn = "root";
$password_dbConn = "root";
$dbConn = mysql_pconnect($hostname_dbConn, $username_dbConn, $password_dbConn) or trigger_error(mysql_error(),E_USER_ERROR);
?>
Note: As noted by other commenters, put together a better picture with the individual pieces, but this should at least get you on the right track.
The question is very broad but for the AJAX bit use jQuery!
Simplest thing I can think of without getting into too many details.
JS
var last_grabbed = 5;
function scrollListen() {
...
$.post('path/to/script.php',{ 'last_row' : last_grabbed },function(response) {
$('.my-content-div').append(response);
last_grabbed += 5;
});
}
PHP
<?php
//your connection stuff, db select, etc
$row = $_POST['last_row']; //you should sanitize this though
$rs = mysql_query("SELECT ... LIMIT $row,5") or die(mysql_error());
while($row = mysql_fetch_assoc($rs)) {
?>
<!-- Do you HTML stuff here for each item !-->
<?php
}
?>
That should get you started. http://www.w3schools.com/php/php_mysql_intro.asp for more on the PHP side.
Related
$('select[name="third_category"]').change(function() {
var first_cat = $('#main_category').val();
var second_cat = $('#top_category').val();
var third_cat = $(this).val();
$.ajax({
type:'POST',
url:'ajax/fields_ajax.php',
data:{'first_cat':first_cat, 'second_cat':second_cat, 'third_cat':third_cat},
success:function(data){
var field_box = document.getElementsByClassName('field_box');
$(field_box).append(data);
}
});
});
My goal is, when user select third option i collect all the option's values on the page. Then i'm going to use them for my mysql queries. That is my fields_ajax.php file.
<?php
session_start();
ob_start();
include 'inc/session.php';
include 'inc/config.php';
include 'inc/mysql.class.php';
ini_set('display_errors', 0);
if( isset($_POST) ){ // secure script, works only if POST was made
$first_cat = $_POST[first_cat];
$second_cat = $_POST[second_cat];
$third_cat = $_POST[third_cat];
$category_field_query = "SELECT * FROM categories WHERE id = $first_cat";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
echo "<p>".$cat_field->fields."</p>";
} ?>
I can carry all values without problem. But when i use them on query, there's no response. Mysqli connection working correctly, my query works on other php files. And when I try something else instead of trying mysql query, ajax file response it without problem.
When i tried to use var textField and String(), the result display null.What i posted below, it display Error #2007 Parameter text must be non-null. Trying to pass the echoed results from mysql through php on AS3, through a few dynamic text box.
But when i switch it to Trace(event.target.data), it shows the correct Data.
Here is my AS3 code
var Mend:URLRequest = new URLRequest("http://localhost/Autoresult.php");
Mend.method = URLRequestMethod.POST;
var variablesss:URLVariables = new URLVariables();
variablesss.nobed1 = result.text;
variablesss.LoZip=result2.text;
variabless.rangelow=result3.text;
Mend.data = variablesss;
var BLoader:URLLoader = new URLLoader();
BLoader.dataFormat = URLLoaderDataFormat.TEXT;
BLoader.addEventListener(Event.COMPLETE,Candler);
BLoader.load(Mend);
// handler for the PHP script completion and return of status
function Candler(event:Event){
var seVariables: URLVariables = new URLVariables(event.target.data);
result.text=seVariables.nobed1;
result2.text=seVariables.LoZip1;
result3.text=seVariables.rangelow1;
}
Here is my php code
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
session_start();
include 'connect.php';
$_SESSION['username'];
$username=$_SESSION['username'];
$result=mysqli_query($con,"SELECT * FROM Test WHERE username = '$username'")or die( mysqli_error($con));
$solutions = array();
$check_num_rows=mysqli_num_rows($result);
while ($row = mysqli_fetch_assoc($result))
{
$solutions[0]=$row['nobed1'];
$solutions[1]=$row['LoZip1'];
$solutions[2]=$row['rangelow1'];}
echo "nobed1=.$solutions[0]&LoZip1=.$solutions[1]&rangelow1=.$solutions[2]";
?>
Thanks for your time
without looking into it too deeply, it seems like it might be a type miss-match.
you could try
var seVariables: URLVariables = new URLVariables(event.target.data + "");
that way it is converted to text
I managed to resolve my problem, changing the php, and putting the result in a string, pass it through to AS3, then split up the answer and put them into the dynamic text box.
Here is my code.
function Candler(event:Event){
var fromPhp:String = event.target.data;
var errors:Array = fromPhp.split(",");
trace(errors.length)
result.text= (errors[0].replace(/^\s+|\s+$/mg, ""));
result2.text= (errors[1].replace(/^\s+|\s+$/mg, ""));
result3.text= (errors[2].replace(/^\s+|\s+$/mg, ""));
result4.text= (errors[3].replace(/^\s+|\s+$/mg, ""));
}
This is the js script at the bottom of my wp post.
<script type="text/javascript" src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
var id = 'downloadid';
var data_from_ajax;
$.post('download.php', {id : id}) .done(function(data) {
data_from_ajax = data;
});
function hey() {
document.write(data_from_ajax);
}
</script>
Function hey was being called from a link OnClick function. When using this, the page would successfully perform the php code on download php (update a db then download a file) although it would clear the current page I was on. What I wanted to do was perform the php and keep the current page template. So next I tried using
document.getElementById("download").innerHTML = data_from_ajax;
instead of document.write. I made a div with the id download. Now when I click it, it simply won't perform the php. when I replace the data_from_ajax with a string, it gladly puts it in the div though.
Any help would be great.
EDIT:
my html is
download
<div id='download'> </div>
http://jsfiddle.net/7smJE/
From PHP code which you've provided, I think you should replace document.write() in your code with $('#download').html(). This way you don't need to put the returned result in your download div anymore because when PHP page gets loaded it'll do this for you and you have to put your $.post in hey() function too because you need this to perform when your link gets clicked.
PHP:
<?php
$fileid = $id;
if (is_file('d84ue9d/' . $fileid . '.apk'))
{
$ip = $_SERVER['REMOTE_ADDR'];
$con=mysqli_connect("localhost","docvet95_check","%tothemax%","docvet95_downcheck");
$result = mysqli_query($con,"SELECT * FROM `download-check` where ip = '$ip'");
while ($row = mysqli_fetch_array($result))
{
$files = $row['files'];
$downloads = $row['downloads'];
}
if ($downloads > 4)
{
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%61%6C%65%72%74%28%27%59%6F%75%5C%27%76%65%20%64%6F%77%6E%6C%6F%61%64%65%64%20%66%69%76%65%20%6F%72%20%6D%6F%72%65%20%66%69%6C%65%73%2E%20%46%6F%72%20%72%69%67%68%74%20%6E%6F%77%2C%20%74%68%69%73%20%69%73%20%6F%6B%61%79%2E%20%49%6E%20%74%68%65%20%66%75%74%75%72%65%2C%20%79%6F%75%20%77%69%6C%6C%20%6E%65%65%64%20%74%6F%20%63%6F%6D%70%6C%65%74%65%20%61%20%73%75%72%76%65%79%20%69%6E%20%6F%72%64%65%72%20%74%6F%20%63%6F%6E%74%69%6E%75%65%20%64%6F%77%6E%6C%6F%61%64%69%6E%67%2E%20%54%68%61%6E%6B%20%79%6F%75%20%66%6F%72%20%75%73%69%6E%67%20%6F%75%72%20%77%65%62%73%69%74%65%27%29%3B%20%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%2F%61%70%6B%73%2F%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
}
else
{
$downloadq = $downloads + 1;
$there = $result->num_rows;
if ($there <1)
{
$addidnip = mysqli_query($con,"INSERT INTO `download-check` (ip, files, downloads) VALUES ('$ip', '$fileid', 1)");
}
else
{
$idtoarray = explode(",", $files);
if (!in_array($fileid, $idtoarray))
{
array_push($idtoarray, $fileid);
$newfile = implode(",", $idtoarray);
$adddw = mysqli_query($con,"UPDATE `download-check` SET downloads=$downloadq, files='$newfile' where ip = '$ip'");
}
}
print "<script type=\"text/javascript\">";
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
print "</script>";
}
}
else
{ echo 'Whoops, looks like we couldn\'t find that file. You could try searching for it?'; }
?>
JavaScript:
var id = 'downloadid';
var data_from_ajax;
function hey() {
$.post('download.php', {id : id});
}
But I recommend you to return the exact data from your PHP without any extra tag and then use it this way:
var id = 'downloadid';
function hey() {
$.post('download.php', {id : id}).done(function(data) {
$("#download").html(unescape(data));
});
}
From what I can see without the fiddle:
The hey function is probably fired before the done function is ready. Why don't you call hey() from within done()?
EDIT: Cron line: /usr/bin/php /usr/local/yy/yy/yy/webspace/httpdocs/test.mysite.ie/test.php > /dev/null 2>&1
I have written a script that functions as it should when i navigate to it in the browser. This is my first time trying to use a cron job so i'm not overly familiar with how they work. The script is below. As i said, the script works as it should if i navigate to the url in a web browser.
test.php
<script src="jquery.min.js"></script>
<script>
//SET UP JS VARIABLES
var allMatchedNumbers = new Array();
var matchedthingyNumbers;
var matchedthingyPlus1Numbers;
var matchedthingyPlus2Numbers;
var winningthingyNumbers = new Array();
var winningBonusNumber;
var winningthingyPlus1Numbers = new Array();
var winningPlus1BonusNumber;
var winningthingyPlus2Numbers = new Array();
var winningPlus2BonusNumber;
var thingyList;
var thingyListItems;
var thingyPlus1List;
var thingyPlus1ListItems;
var thingyPlus2List;
var thingyPlus2ListItems;
var userNumbers = new Array();
var displayCounter = 1;
var drawDate;
var thingyNumbers;
var thingyBonus;
var thingyPlus1;
var thingyPlus1Bonus;
var thingyPlus2;
var thingyPlus2Bonus;
//GET RESULTS & DATE FOR thingy, PLUS1, PLUS2 FROM THE DOM OBJECT ONLY
$(document).ready(function fetchResults(){
$.ajax({
url: "scrape_page.php",
success: function(data) {
}
});
$.ajax({
url: "latest_results.txt",
success: function(data) {
var dom = $(data);
//GET thingy DATE
drawDate = dom.find('.date-heading.fooRegular').contents().first().text();
//GET thingy NUMBERS
thingyNumbers = dom.find('.result-block').eq(0).find('.thingy-winning-numbers');
thingyBonus = dom.find('.result-block').eq(0).find('.thingy-bonus');
thingyPlus1 = dom.find('.result-block').eq(1).find('.thingy-winning-numbers');
thingyPlus1Bonus = dom.find('.result-block').eq(1).find('.thingy-bonus');
thingyPlus2 = dom.find('.result-block').eq(2).find('.thingy-winning-numbers');
thingyPlus2Bonus = dom.find('.result-block').eq(2).find('.thingy-bonus');
populateWinningNumbers();
}
});
});
//PUT WINNING NUMBERS IN ARRAY
function populateWinningNumbers() {
//MAIN thingy NUMBERS
thingyList = thingyNumbers;
thingyListItems = thingyList.find('li');
thingyPlus1List = thingyPlus1;
thingyPlus1ListItems = thingyPlus1List.find('li');
thingyPlus2List = thingyPlus2;
thingyPlus2ListItems = thingyPlus2List.find('li');
thingyListItems.each(function(index) {
winningthingyNumbers[index] = parseInt($(this).text());
});
//winningBonusNumber = parseInt($('#mainthingyBonus').find('li').text());
winningBonusNumber = parseInt($(thingyBonus).find('li').text());
winningthingyNumbers.push(winningBonusNumber);
//thingy PLUS NUMBERS
thingyPlus1ListItems.each(function(index) {
winningthingyPlus1Numbers[index] = parseInt($(this).text());
});
winningPlus1BonusNumber = parseInt($(thingyPlus1Bonus).find('li').text());
winningthingyPlus1Numbers.push(winningPlus1BonusNumber);
//PLUS 2
thingyPlus2ListItems.each(function(index) {
winningthingyPlus2Numbers[index] = parseInt($(this).text());
});
winningPlus2BonusNumber = parseInt($(thingyPlus1Bonus).find('li').text());
winningthingyPlus2Numbers.push(winningPlus2BonusNumber);
postDataToDB();
}
//POST OFFICIAL thingy NUMBERS TO DATABASE
function postDataToDB() {
$.ajax({
url: "postToDB.php",
type: "post",
data: {thingyNums:winningthingyNumbers, thingyPlus1Nums: winningthingyPlus1Numbers, thingyPlus2Nums: winningthingyPlus2Numbers, drawDate:drawDate},
// callback handler that will be called on success
success: function (data) {
}
});
}
</script>
scrape_page.php
<?php
include 'simple_html_dom.php';
$html = file_get_html('http://www.site.com');
$file = 'latest_results.txt';
file_put_contents($file, $html);
?>
postToDB.php
<?php
$winningNums = $_POST['thingyNums'];
$winningPlus1Nums = $_POST['thingyPlus1Nums'];
$winningPlus2Nums = $_POST['thingyPlus2Nums'];
$drawDate = $_POST['drawDate'];
$thingyToSave = implode(',', $winningNums);
$plus1ToSave = implode(',', $winningPlus1Nums);
$plus2ToSave = implode(',', $winningPlus2Nums);
//CONNECT TO REMOTE
$con = mysql_connect("172.xx.xx.xx","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
//SELECT thingy DB
mysql_select_db("App", $con);
//CHECK IF DATE ALREADY EXISTS IN DB
$date_check = mysql_query("SELECT drawDate FROM thingy WHERE drawDate='$drawDate'");
$do_date_check = mysql_num_rows($date_check);
if($do_date_check > 0){
//DATE ALREADY IN DB
die("Entries already exist");
} else {
mysql_query("INSERT INTO thingy (drawDate) VALUES ('$drawDate')");
mysql_query("UPDATE thingy SET thingyRes = '$thingyToSave' WHERE drawDate = '$drawDate'");
mysql_query("UPDATE thingy SET thingyPlus1Res = '$plus1ToSave' WHERE drawDate = '$drawDate'");
mysql_query("UPDATE thingy SET thingyPlus2Res = '$plus2ToSave' WHERE drawDate = '$drawDate'");
echo "Success";
}
mysql_close($con);
?>
The script you're trying to run contains Javascript - which is executed in a browser. Cron will execute the PHP script on the server, and send the output nowhere (as you're directing it to /dev/null).
There's nothing in that scenario that will interpret and execute the Javascript.
You need to essentially port the logic in your Javascript (which makes requests to the two related PHP scripts) to PHP. (You could possibly run some server side javascript interpreter/php extension, but in this case that would seem a bit crazy.)
If you're calling test.php via wget or similar, that tool php doesn't have a JavaScript engine in it. So naturally any JavaScript-dependent features of the page won't run.
There are tools that will load the page and execute the JavaScript therein. They're called "headless" browsers. For example, PhantomJS, which is a headless browser based on WebKit with a JavaScript engine in it. There are also headless versions of Firefox and such.
You'd have your web server running as normal and point the headless browser at the URL for the page, which would both trigger the PHP (just as though the page had been requested by a browser) and process the client-side JavaScript in the page.
I use a comment box in my web page and saved user input comments. Now what I want is to display them using AJAX. I set a javascript timer to get comments one by one. But I don't know how to use AJAX to retrieve data. This is the php file
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("continental_tourism");
$query = "SELECT comment_id from comment";
$result = mysql_query($query);
$counter = 0;
while ($row = mysql_fetch_assoc($result))
{
$counter++;
}
$comment_number = rand(1,$counter);
$query_comment = mysql_query("SELECT * FROM comment WHERE comment_id = '$comment_number'");
if (!$query_comment) {
die('Invalid query: ' . mysql_error());
}
while($result_comment = mysql_fetch_array($query_comment)) {
echo $result_comment['comment'];
}
?>
following is the script part in the main file.
function timeMsg()
{
var t=setTimeout("show_comment()",3000);
}
function show_comment(){
}
How should i write the AJAX code to the?
function show_comment()
If someone can explain the AJAX code line by line, I'll be great full.
You have to move your all php script to another php file say getdata.php and use your ajax function in your file where you want to show the data say it is index.php. (this is for easy to use code). Now your index.php file should look like
<html>
<body>
<div id="comments"></div>
</body>
<script src="include/jquery.js" type="text/javascript"></script>
<script type="text/javascript>
function show_comments() {
$.ajax({
url:getdata.php
success:function(data){
$("#comments").append(data);
}
});
</script>
</html>
I am using jquery.ajax function of jquery. This is some hint how you can do this. I hope it will help you to accomplish your task.
Use jQuery's .get() method using the link to your PHP script as URL. That should call your PHP script and your script should echo the output.
You should consider json_encode-ing your output from php script before echoing it.
And I think, instead of doing this -
$query = "SELECT comment_id from comment";
$result = mysql_query($query);
$counter = 0;
while ($row = mysql_fetch_assoc($result))
{
$counter++;
}
you can query SELECT COUNT(comment_id) from comment and get the count.