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.
DataPull.php:
CASE "CityList":
echo "<select style='width:132px;height:243px;' size='17' id='CityListA' name='CityListA' onChange='SubCityList(this.value);'>";
$result = $db-> query("SELECT region_id,region_name FROM dwrel_region ORDER BY region_name");
while ($row = $db-> fetch_assoc($result)){
echo "<option value='".$row["region_id"]."'>".$row["region_name"]."</option> \n";
}
echo "</select>";
break;
JavaScript:
function CityList(){
try{var xmlhttp=new XMLHttpRequest();}catch (e){try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");}catch (e){try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}catch (e){return false;}}}
xmlhttp.onreadystatechange=function(){if (xmlhttp.readyState==4 && xmlhttp.status==200){getEl("CityList").innerHTML=xmlhttp.responseText;}}
eMsg = "DataPull.php?get=CityList";
xmlhttp.open("GET",eMsg);
xmlhttp.send();
}
It works just fine for me. Was reading around JQuery/AJAX and surprised you could do it via $(function(){}); part.. but I don't or can't begin to understand where and how to put it together "as is" with the code I have above. Hopefully someone out there is kind enough to guide me to the right direction using AJAX, pulling and output results.
Was trying to understand how to be able to use this, even reading mentioned the use of JSON? (I think) or data "as is", something.. Oh I don't know.. Anyways, hopefully someone could help me put this together and then I could understand it even better.
Thanks!
EDIT:
After weeks from this post, learned a new way to do this:
in CSS:
.LoaderIcon {width:100%;height:100%;background:url('./images/Loading.gif') no-repeat center center;}
in JQuery:
$.ajax({
beforeSend: function(){ $('#SOMEID').addClass('LoaderIcon'); },
url: "SOME PARAMETER",
success:function(data){
$('#SOMEID').removeClass('LoaderIcon');
$('#SOMEID').html(data)
}
This has been working like charm for me, hopefully it would benefit others :)
});
Try this
function CityList(){
$("#YOUR_SPINNING_DIV_ID").html('<img src="PATH_TO_SPINNINGANIM_GIF"');
$.ajax({
url: "DataPull.php?get=CityList",
success: function(data ){
$("#CityList").html(data );
$("#YOUR_SPINNING_DIV_ID").html("");
}
});
}
and then call this function on any event that you are observing like button clicks or window onload. If you are doing it on windown onload then Jquery equivalient will be
$(document).ready(function() {
$.ajax({
url: "DataPull.php?get=CityList",
success: function(data ){
$("#CityList").html(data );
}
});
)};
Something like this in your jQuery(document).ready()
$.ajax({
type:'GET',
url:'DataPull.php',
data:'get=CityList',
success:function(msg){
alert('Success!\n\n+'+msg);
},
error:function(msg){
alert('Error!\n\n'+msg);
}
});
Where msg is the echo from the given PHP file. Read more about it on the jQuery website.
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();
As a beginner in jQuery I'm trying to understand how to handle .click().
My event click function :
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('.del').click(function() {
var lien = $(this).attr("title");
$.post(lien, function(data) {
$('#result').empty();
$('#result').append(data);
})
});
</script>
The span :
<span title="<?php echo base_url().'del/cat/'.$cat->idcategories ?>"class="del alignright">supprimer</span>
This works the first time but not after that. Is this happening because I'm using attr()?
Any explanation of the expected behavior would be very much appreciated.
First of all, it looks like you're missing the last bracket-parens, to close document.ready. This could (should) be causing an error. Your code should be like this:
$(document).ready(function() {
$('.del').click(function() {
var lien = $(this).attr("title");
$.post(lien, function(data) {
$('#result').empty();
$('#result').append(data);
});
});
});
For good measure, also add a space before class in your span:
<span title="<?php echo base_url().'del/cat/'.$cat->idcategories ?>" class="del alignright">supprimer</span>
Then consider the other answers of changing click to live in the event that you're somehow replacing or unbinding .del elsewhere.
By the looks of it you sending a request to delete something... If your sending the request twice it's only going to delete once..
However Try
$('.del').live('click',function(){
var lien = $(this).attr("title");
$.post(lien, function(data) {
$('#result').empty();
$('#result').append(data);
}
});
So, for some reason my script refuses to work, although it seems to be correct.
I tried using $.ajax instead, but not working with that either. Any ideas what's gone wrong?
<script>
$(document).ready(function() {
$('#saveForm .submit').click(function() {
var _user = $('#saveForm .user');
_userId = $('#saveForm .userId');
_password = $('#saveForm .password');
$('#saveForm').append('<p>Loading...</p>');
$.post("ajax/fetchPhotos.php", {user:_user, userId:_userId, password:_password}, function(data) {
alert(data);
});
return false;
});
});
</script>
In ajax/fetchPhotos.php i have this:
<?php
set_time_limit(0);
session_start();
require_once("includes/functions.php");
require_once("includes/pclzip.lib.php");
/*
Huge block of code here (commented out for the moment)
*/
echo "wut?";
So, when clicking .submit, it should send a request to fetchPhotos.php with three params and then alert "wut?". Right now the page hangs in chrome.. nothing happens. In firefox the page just refreshes. I do get one error in the console, but i only see it for a split second as the page refreshes directly.
Thanks,
Pete
you must use the .val() method to get the value of the inputs.
try this way:
<script>
$(document).ready(function() {
$('#saveForm .submit').bind('click', function() {
var
user = $('#saveForm .user').val(),
id = $('#saveForm .userId').val(),
password = $('#saveForm .password').val();
$('#saveForm').append('<p>Loading...</p>');
$.post("ajax/fetchPhotos.php", {user:user, userId:id, password:password}, function(data) {
alert(data);
});
return false;
});
});
</script>
It seems syntax related problem and also try with absolute url or can do in this way
new Ajax.Request("ajax/fetchPhotos.php", {
method: 'post',
parameters: 'id='+id,
onComplete: function(transport) {
alert(transport.responseText);
}
});