Why doesn't this infinite scroll work in IE? - php

The code below works as intended for Chrome and Firefox. For IE, it scrolls through the same content. I searched extensively for a solution but found nothing.
Header
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(window).scroll(function()
{
if($(window).scrollTop() == $(document).height() - $(window).height())
{
$('div#loadmoreajaxloader').show();
$.ajax(
{
url: "http://www.hackedflashgames.com/loadmore.php",
success: function(html)
{
if(html)
{
$("#wrapper").append(html);
$('div#loadmoreajaxloader').hide();
}else
{
$('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
}
}
});
}
});
</script>
loadmore.php
<?php
include('db.php');
$stmt = $db->prepare("SELECT * FROM games ORDER BY RAND() LIMIT 6");
if($stmt->execute()){
while ($row = $stmt->fetch()) {
echo'
content here
';
}
}
?>

IE is renown for it's aggressive caching especially with AJAX.
Try adding some random query string to the URL for the ajax call (like a timestamp).
You could also specify this in your code : $.ajaxSetup({ cache: false });
Thus you won't have to manually add the query string, jQuery will take care of it.

Related

Load more button not working and showing all the records on the page

I have a page and I am displaying the list(MAX 200 records) on my page using ajax.
I am using the below code to call the ajax and show the response on the page.
And the second script is for a button called "Load More". I have to show the 20 records on the page then the user clicks on load more than displays the next 20 records.
Now, My issue is, I am getting all the records and load more button
$(document).ready(function(){
$.ajax({
url: 'function21.php',
method:'post',
dataType: "json",
data:{action:"employeelist21"},
success: function(data){
$('#employeelist').append(data);
}
})
});
$(document).ready(function(){
var list = $("#employeelist21 li");
var numToShow = 20;
var button = $("#next");
var numInList = list.length;
//alert(numInList);
list.hide();
if (numInList > numToShow) {
button.show();
}
list.slice(0, numToShow).show();
button.click(function(){
var showing = list.filter(":visible").length;
list.slice(showing - 1, showing + numToShow).fadeIn();
var nowShowing = list.filter(":visible").length;
if (nowShowing >= numInList) {
button.hide();
}
});
});
PHP
function employeelist21($pdo)
{
$query=" sql query here";
$stmt = $pdo->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if (!empty($results)) {
$data='';
$data='<ul><li>
<div class="box">
<div><span>Company</span></div>
<div><span>Industry</span></div>
<div><span>Name</span></div>
<div><span>Location</span></div>
</div>
</li>';
foreach($results as $key){
$data.='<li>
<div class="box">
<div><h4>'.$key['Industry'].'</h4></div>
<div><p>'.$key['industry_name'].'</p></div>
<div><p>'.$key['name'].'</p></div>
<div><p>'.$key['city'].'</p></div>
</div>
</li>';
}
$data.='</ul><div class="text-center">Load More</div>';
}
else{
$data.='No records available';
}
echo json_encode($data);
}
First, I would rather transfer back a list of data (not html) in json format and use that like an array, creating the HTML for it in javascript. BUT we don't always get what we want, so in this case I would assign an attribute to each set of 20 like this:
// at the top of your script (not in a function)
let perPage = 20, onGroup=0
// in your ajax function ...
success: function(data){
$('#employeelist').hide();
$('#employeelist').append(data);
$('#employeelist box').each( function(index) {
if (index===0) return; //header row
$(this).data('group',Math.floor(index-1/perPage))
});
$('#employeelist box').hide()
$('#employeelist box [data-group=0]').show()
$('#employeelist').show();
}
Then for the button, remove this from the PHP and make it an element under the results div
<div class="text-center">Load More</div>
Then in your script
$(document).ready(function() {
$("#next").click(function(){
$('#employeelist box [data-group='+onGroup+']').hide()
onGroup++;
$('#employeelist box [data-group='+onGroup+']').show()
if ($('#employeelist box [data-group='+(onGroup+1)+']').length ===0) {
$(this).hide();
}
});
});
Hard to test here, but let me know if it doesn't work

Wordpress jQuery initialize widgets.php area

Hey guys I'm having a huge problem initializing jQuery on the backend of WordPress (widgets.php). I'm building a widget to display some select options that can only be accessed through SOAP, so I had to ajaxify it using admin-ajax.php. Everything works perfectly on the front-end but when it comes to the backend it breaks completely.
function widget_inject() {
echo "<script>
jQuery(document).ready(function($) {
var ajaxurl = '".admin_url('admin-ajax.php')."';
var list_target_id = 'list-target'; //first select list ID
var list_select_id = 'list-select'; //second select list ID
var initial_target_html = '<option value=\"\">Please select category...</option>';
$('#'+list_target_id).html(initial_target_html);
$('#'+list_select_id).change(function(e) {
var selectvalue = $(this).val();
$('#'+list_target_id).html('<option value=\"\">Loading...</option>');
if (selectvalue == \"\") {
$('#'+list_target_id).html(initial_target_html);
} else {
$.ajax({url: ajaxurl,
data: {
action: 'parentcatajax1',
parentCat: selectvalue
},
success: function(output) {
//alert(output);
$('#'+list_target_id).html(output);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + \" \"+ thrownError);
}});
}
});
});</script>";
}
add_action('admin_enqueue_scripts','widget_inject');
^This is what I'm trying. I've tried admin-init, admin-head, admin-footer none of them seem to work.
& yeah I have...
add_action('wp_ajax_nopriv_parentcatajax1', 'parentCatCallback1');
add_action('wp_ajax_parentcatajax1', 'parentCatCallback1');
for my ajax function; it works perfectly on the front end.
I'm at a stand still for a client & can't figure out what to do.
Any suggestions? Thanks in advance!
Your printing your jQuery before wordpress has initialized jQuery. Wp_enqueue scripts is not the point where it starts printing the scripts onto the page. The below will clear your jQuery not defined error, let me know if there are more errors after this.
function widget_inject() {
echo "<script>
jQuery(document).ready(function($) {
alert('ready');//re-enter your code here
})(jQuery);
</script>";
}
add_action('admin_print_scripts','widget_inject', 100);//hook= 'admin_print_scripts'

Ajax not working in chrome. Can anyone save me?

I have this code on my page...
the jQuery
window.setInterval( function(){
$.get("php/get_posts.php", function(data) {
$('.post-container').prepend(data);
});},10);
This is the get_posts.php
<?php
include('dbconnect.php');
session_start();
$uid= $_SESSION['uid'];
$get_ids=mysql_query("SELECT * FROM posts ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($get_ids)){
$id=$row['id'];
$sm=$row['message'];
}
$get_lpid=mysql_query("SELECT * FROM users WHERE uid='$uid'");
while($row_o = mysql_fetch_array($get_lpid)){
$l_pid=$row_o['lastviewed'];
}
if($id!=$l_pid){
$insert=mysql_query("UPDATE users SET lastviewed='$id' WHERE uid='$uid' ");
if($insert){?>
<div class='media'><img src='img/profile_pictures/thumbs/thumb_13718921232_119055628287843_1500172795_n.jpg' class='img-circle post-circle pull-left'><div class='media-heading'><a href='#'>Pratik Sonar</a><div class='pull-right'><small>12.00PM</small></div></strong></div><div class='media-body'><?php echo $sm ?></div></div>
<?php } else{
}
}
else{
}?>
This technique seems to work on every browser except chrome. I have tested ie, safari, firefox and opera all are working. Can anyone enlighten me on this thing? Is there something I don't know or am I missing?
Try to wrap your code into this function:
$(document).ready(function() { ... });
Like:
$(document).ready(function() {
window.setInterval( function(){
$.get("php/get_posts.php", function(data) {
$('.post-container').prepend(data);
});},10);
});
You're probably better off using setTimeout() too.
Now the code runs when the DOM is fully loaded.
Why are you using window.setInterval?
It's simply setInterval(), without any parent.
Try
$(document).ready(function() {
setInterval(function(){
$.get("php/get_posts.php", function(data) {
$('.post-container').prepend(data);
});
},10);
});
Thank You guys for all your concerns. Well at last the bug got fixed by this chunk of code. I guess setTimeout gain gains victory over setInterval
$(document).ready(function() {
window.setTimeout(function(){
$.ajax({
type: "GET",
url: "php/get_posts.php",
}).done(function( data ) {
$('.post-container').prepend(data);
});
},10);
});

Update div dynamically with database values depending on dropdown

Please see website.
My database has a table with values 'name' (the event under step 2 on the left), 'price', 'date' etc and I'd like to display them dynamically in the dark box on the right depending on which event is chosen.
I'm currently displaying the event itself with the code below, but I'm unsure as to how to develop it to grab database values based on this choice. I'm guessing some sort of .get().
<script type="text/javascript">
$(document).ready(function() {
$('#right_inside').html('<h2>' + $('#club').val() + '</h2>');
});
$('#club').change(function(event) {
$('#right_inside').html('<h2>' + $('#club').val() + '</h2>');
});
</script>
This has had me stumped for ages, so any help would be much, much appreciated!
EDIT
Thanks for your replies. Here's what I now have, but it isn't working.
jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('#right_inside').html('<h2>' + $('#club').val() + '</h2>');
});
$('#club').change(function(event) {
$.ajax({
type: "post",
url: "eventinfo.php",
data: $(this).serialize(),
success: function(data) {
$('#right_inside').html('<h2>' + $('#club').val() + '</h2>Price'+data.price);
},
dataType: "json"
});
});
</script>
eventinfo.php:
<?php
// the name of the input text box is 'club'
$night = $_POST['club'];
$night = mysql_real_escape_string($night);
// one of the columns values included in * is 'price'
// this line was previously: $query = mysql_query("SELECT * FROM nights WHERE name = '$night'");
$query = "SELECT * FROM nights WHERE name = '$night'";
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$items[] = array($row[0]);
}
}
mysql_close();
// convert into JSON format and print
echo json_encode($items);
?>
The best course of action would be to use an xmlhttp object to load your PHP page that echos the data out. From that xmlhttp object you can assign the responseText (which will be the output contents of your PHP page) to a Javascript variable.
In other words, you probably want to use AJAX.
This is a good place to use client side templating. Use jQuery.tmpl and make a template for the right side (example below):
<script id="infoTemplate" type="text/html">
<div>
<span>${price}</span>
<span>${information}</span>
</div>
</script>
Then, make a method in PHP that takes in something like eventId and passes back a JSON object that looks something like this: {"price":"123.34","information":"some info here"}.
To load up your template, do this:
$(document).ready(function(){
// ... other stuff
$.template("infoTemplate", $("#infoTemplate").html());
});
Then, in your change event handler, do this:
$('#club').change(function(event) {
$.get('/yourNewPHPMethod', $('#club').val(), function(data){
$('#right_inside').html($.tmpl('infoTemplate', data));
});
});
Sorry, didn't have time to test any of this but it's the main idea and should help you establish a good pattern for any of this type of work in the future.
See jQuery.tmpl documentation below:
http://api.jquery.com/jquery.tmpl/
If I understand you right, you want an AJAX call to get the price. So something like
$('#club').change(function(event) {
$.ajax(
{type: "post",
url: "/path/to/price",
data: $(this).serialize(),
success: function(data)
{
$('#right_inside').html('<h2>' + $('#club').val() + '</h2>Price'+data.price);
},
dataType: "json"
});
Then since you are using PHP get the values you want and load them into an array and use json_encode.
update
For the PHP try changing
if($result && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$items[] = array($row[0]);
}
}
to
if($result && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$items[] = array("price"=>$row['price']);
}
}
update #2
Try adding the following to your PHP file, near the top:
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

Do php query with ajax

I'd like to do a sql query with ajax so I don't need to reload the page / load a new page.
So basicly I need to call a php page with ajax. And it would be great if there could be a way to reload a count of amount of rows in a table too.
Edit: to make it more clear, it should be able to do something along the lines of when you click the Like button on Facebook.
Thanks
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
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)
{
document.getElementById("your_div").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_file.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv">here are your contents</div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
You don't want to query using ajax, you want to get new data using ajax, which is a fundamental difference.
You should just, using ajax, request a php page with perhaps some parameters, which in turn executes the query and returns the data in a format you can handle (most likely: json).
If you allow queries to be executed using ajax, how are you going to prevent a malicious user from sending drop table users, instead of select * from news where id = 123?
You won't do a sql query with ajax, what you need to do is call an external php page (one where your query is) in the background using ajax. Here is a link that explains how to do it with jquery: http://api.jquery.com/jQuery.ajax/
"Facebook Like" button in Agile Toolkit (PHP UI Library):
$likes = get_like_count();
$view = $this->add('View');
$button = $view->add('Button')->setLabel('Like');
$view->add('Text')->set($likes);
if($button->isClicked()){
increate_like_count();
$view->js()->reload()->execute();
}
p.s. no additional JS or HTML code needed.
function onClick(){
$.post(
"path/to/file", //Ajax file ajax_file.php
{ value : value ,insiId : insiId }, // parameters if you want send
//function that is called when server returns a value.
function(data){
if(data){
$("#row_"+data.id).show(); //display div rows
}
},"json"
);
}
<div id="myDiv">here are your contents</div>
<button type="button" onclick="onClick()">Change Content</button>
Here the ajax code that you can call to the server side php file and get the out put and do what you want
You are wrong, who says that he is submitting the whole query who is telling that he is not filtering? U can do all this easy with the jquery load function, you load a php file like that $('#BOX').load('urfile.php?param=...');.
Have fun,
i hope that was a little helpful for you, sry bcs of my bad english.
Possible solution: Ajax calls PHP scripts which make the query and return the new number
$.ajax({
async:true,
type:GET,
url:'<PHP_FILE>',
cache:false,
data:'<GET_PARAMETERS_SENT_TO_PHP_FILE>',
dataType:'json',
success: function(data){
$('<#HTML_TARGET>').html(data);
},
error: function(jqXHR, textStatus, errorThrown){
$('<#HTML_TARGET>').html('<div class="ajax_error">'+errorThrown+'</div>');
}
});
Where
<PHP_FILE> is your php script which output must be encoded according to dataType. The available types (and the result passed as the first argument to your success callback) are: "xml", "html", "script", "json", "jsonp", "text".
<GET_PARAMETER_SENT_TO_PHP> is a comma separate list of value sent via GET (es. 'mode=ajax&mykey=myval')
<#HTML_TARGET> is the jquery selector
See jquery.ajax for more details.
For example:
<p>Votes:<span id="count_votes"></span></p>
<script type="text/javascript">
$.ajax({
async:true,
type:GET,
url:'votes.php',
cache:false,
dataType:'text',
data:'id=4'
success: function(data){
$('#count_votes').html(data);
},
error: function(jqXHR, textStatus, errorThrown){
$('#count_votes').html(errorThrown);
}
});
</script>
If your looking for something like the facebook like btn. Then your PHP code should look something like this -
<?php
$topic_no = $_POST['topic'];
$topic_likes = update_Like_count($topic_no);
echo $topic_likes;
function update_Like_count($topic)
{
//update database by incrementing the likes by one and get new value
return $count;
}
?>
and the javascript/jquery ajax should be something like so -
<script>
$('#like-btn').click( function () {
$.post(
"like.php",
{ topic : value },
function(data)
{
if(data)
{
$("#like-btn span").append(data); //or append it to wherever you'd like to show it
}
else
{
echo "error";
}
},
"json"
);
});
</script>
Here is an example which uses a favorite jQuery plugin of mine, jQuery.tmpl(), and also the jQuery .text() function.
HTML and Javascript Code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
</head>
<body>
<script id="UserTemplate" type="text/x-jquery-tmpl">
<li><b>Username: ${name}</b> Group ID: (${group_id})</li>
</script>
<button id="facebookBtn">Facebook Button</button>
<div id="UserCount"></div>
<ul id="userList"></ul>
<script>
function getData(group_id) {
$.ajax({
dataType: "json",
url: "test.php?group_id=" + group_id,
success: function( data ) {
var users = data.users;
/* Remove current set of movie template items */
$( "#userList" ).empty();
/* Render the template with the movies data and insert
the rendered HTML under the "movieList" element */
$( "#UserTemplate" ).tmpl( users )
.appendTo( "#userList" );
$( "#UserCount" ).text('Number of users: '+ data.count);
}
});
}
$( "#facebookBtn" ).click( function() {
getData("1");
});
</script>
</body>
</html>
PHP Code
<?php
//Perform a query using the data passed via ajax
$group_id = $_GET['group_id'];
$user_array = array(
array('name'=>'John','group_id'=>'1',),
array('name'=>'Bob','group_id'=>'1',),
array('name'=>'Dan','group_id'=>'1',),
);
$user_count = count($user_array);
echo json_encode(array('count'=>$user_count,'users'=>$user_array));
HTML:
//result div will display result
<div id="result"></div>
<input type="button" onclick="getcount();" value="Get Count"/>
JS:
//will make an ajax call to ustom_ajax.php
function getcount()
{
$.ajax({
type:"get",
url : "custom_ajax.php",
beforeSend: function() {
// add the spinner
$('<div></div>')
.attr('class', 'spinner')
.hide()
.appendTo("#result")
.fadeTo('slow', 0.6);
},
success : function (data) {
$("#result").html(data);
},
complete: function() {
// remove the spinner
$('.spinner').fadeOut('slow', function() {
$(this).remove();
});
}
});
}
custom_ajax.php:
//will perform server side function
//make a connection and then query
$query_txt = "SELECT count(*) FROM table ";
$result= mysql_query($query_txt) or die(mysql_error());
$total=mysql_num_rows($result) ;
$html= "Total result is $total";
echo $html; exit();

Categories