Basic javascript function - php

I have this function working
<script type="text/javascript">
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$('div#loadmoreajaxloader').show();
$.ajax({
url: "loadmore.php?wall=<?php echo $wall; ?>&lastid=" + $(".postitem:last").attr("id"),
success: function(html) {
if (html) {
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
} else {
$('div#loadmoreajaxloader').html('<center><font color="white">No more posts to show.</font></center>');
}
}
});
}
});
</script>
But I need to have the same stuff happening (on IOS Devices), but instead of it happening when the browser reaches the loadmoreajaxeloader div, I simply need it to happen on an onclick event on a link. Thanks heaps.
Tried to add code but didn't format so here it is http://pastebin.com/p2VUqZff

You need to separate the Ajax and the scroll event.
So create a function to load the content like so:
// Create the load content function
function loadContent(){
$.ajax({
url: "loadmore.php?wall=<?php echo $wall; ?>&lastid=" + $(".postitem:last").attr("id"),
success: function(html){
if(html){
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
}else{
$('div#loadmoreajaxloader').html('<center><font color="white">No more posts to show.</font></center>');
}
}
});
}
Then bind the scroll event to the window:
// Set the onscroll event
$(window).scroll(function(){
if($(window).scrollTop()==$(document).height()-$(window).height()){
$('div#loadmoreajaxloader').show();
// IF YOU WANT TO LOAD MORE CONTENT WHEN SCROLLING THEN UNCOMMENT THE NEXT LINE
// loadContent();
}
});
Then set the onclick event of the Load More link:
// Bind the click event to the Load More link
$('#loadMore').click(function(e){
// This will prevent any default action
e.preventDefault();
// Load the content
loadContent();
});
UPDATE
I forgot to make sure the events are assigned once the page has loaded. Surround all of your javascript with this:
$(document).ready(function(){
// PUT ALL THE JAVASCRIPT HERE
});

If you're saying you want the code to execute both on scroll and when your link is clicked you can put the common code in a function that you call from all the places you need it:
function doStuff() {
$.ajax({
url: "loadmore.php?wall=<?php echo $wall; ?>&lastid=" + $(".postitem:last").attr("id"),
success: function(html) {
if (html) {
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
} else {
$('div#loadmoreajaxloader').html('<center><font color="white">No more posts to show.</font></center>');
}
}
});
}
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$('div#loadmoreajaxloader').show();
doStuff();
}
});
$("#idOfYourLinkGoesHere").click(function() {
doStuff();
return false;
});
Noting that returning false from the click handler stops the default behaviour for a click on a link (i.e., prevents it navigating away from the current page or moving back to the top of the page).
I wasn't sure if the .show() was to occur from the link so I've left it within the scroll handler. If it applies to either case move it into the doStuff() function.

Try to replace the scroll parts with something like that:
$('a#moreLoader').click(function() {
$('div#loadmoreajaxloader').show();
$.ajax({
url: "loadmore.php?wall=<?php echo $wall; ?>&lastid=" + $(".postitem:last").attr("id"),
success: function(html) {
if (html) {
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
} else {
$('div#loadmoreajaxloader').html('<center><font color="white">No more posts to show.</font></center>');
}
}
});
return false;
});
where a#moreLoader is a link with 'moreLoader' as id :
<a id="moreLoader" href="#">load more</a>

I think what you are asking is "how can I reuse this function when a link is clicked" - and if so, the answer is this:
<script type="text/javascript">
// Declare the AJAX action as a separate function
var loadMoreContent = function() {
$.ajax({
url: "loadmore.php?wall=<?php echo $wall; ?>&lastid=" + $(".postitem:last").attr("id"),
success: function(html) {
if (html) {
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
} else {
$('div#loadmoreajaxloader').html('<center><font color="white">No more posts to show.</font></center>');
}
}
});
};
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$('div#loadmoreajaxloader').show();
loadMoreContent(); // Just call the separate function here
}
});
// ...and attach the function as a click handler to the link:
$('#idOfMyLink').click(function() {
loadMoreContent(); // Just call the separate function here
return false; // Return false to prevent navigation away from the page
});
</script>

Related

trouble in call a ajax file in jquery

This below coding is working in chrome browser but not in mozilla. How to solve this problem in mozilla firefox.
$(document).ready(function() {
$("#del_enquiry").click(function() {
var enquiry = new Array();
$('input[name="del_enq"]:checked').each(function() {
enquiry.push(this.value);
});
if(confirm("Do you want to delete the Records"))
{
var delid="deleteid="+enquiry;
$.ajax({
url: "delete_enquiry.php",
type: "POST",
data: delid,
cache: false,
success: function(data) {
if(data==1) {
alert("Record Deleted Successfully");
} else {
alert("Record not Deleted");
}
}
});
}
});
});
You can use onsubmit atttribue of form tag function before submitting the form.
Inside my function write your confirm box conditions.
if(confirm("Do you want to delete?"))
{
return true;
}

auto refresh ajax div running on php page

Please see my code below. I want to auto refresh a div on a php page. I tried to refresh through javascript and html header, but it is slowly slowing down my computer.
page2.php
<?php
if($_GET['type']!='ajax'){
include 'header.php';
echo "<div id='main-content'>";
}
?>
Itm 1</br>
Itm 2
<img class="ajax-loader" src="ajax-loader.gif" alt="loading..." />
<?php
if($_GET['type']!='ajax'){
echo "</div>";
include 'footer.php';
}?>
app.js
$.cergis = $.cergis || {};
$.cergis.loadContent = function () {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
}
});
if (pageUrl != window.location) {
window.history.pushState({ path: pageUrl }, '', pageUrl);
}
}
$.cergis.backForwardButtons = function () {
$(window).on('popstate', function () {
$.ajax({
url: location.pathname + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
}
});
});
}
$("a").on('click', function (e) {
pageUrl = $(this).attr('href');
$.cergis.loadContent();
e.preventDefault();
});
$.cergis.backForwardButtons();
i have tried different variation but no luck. please help me.
thanks.
app.js changed...
function myTimer() {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
}
});
}
setInterval(function(){myTimer()}, 1000);
Try setTimeout:
function myTimer() {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
setTimeout(myTimer,1000);//so that the request ends setTimeout calls a new request.
},
error: function () {
setTimeout(myTimer,1000);//If there is an error in the request the "autoupdate" can continue.
}
});
}
myTimer();//fire
this way setTimeout() waiting to finish the request to invoke a new request.
setInterval() does not wait, which makes simuntaneos generate multiple events, which causes the slowness.
You can use setTimeout($.cergis.loadContent, 1000); to refresh once or setInterval($.cergis.loadContent, 1000); to refresh each seconds (1000 milliseconds = 1second).
See http://www.w3schools.com/js/js_timing.asp

Jquery stop function when user hovers over a div

I have a jquery ajax function:
function posts()
{
pfunc = $.ajax({
url: 'backend/posts.php',
success: function(data) {
$('#posts').html(data);
$('#posts').fadeIn(2000);
setTimeout(posts,2000);
}
});
}
posts();
And I want to stop the function when a user hovers over the div 'Posts' and resume when the user stops hovering over that div. Is there any way I could do that.
Thanks
Here you go :)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function posts()
{
pfunc = $.ajax({
url: 'backend/posts.php',
success: function(data) {
$('#posts').html(data);
$('#posts').fadeIn(2000);
timer = setTimeout(posts,2000);
}
});
}
posts();
$(document).ready(function(){
$('#posts').hover(function(){clearTimeout(timer);}, function(){setTimeout(posts,2000);});
});
</script>
<div id = 'posts'></div>
Basically I added a mouser-over and mouse-out event handlers to the #post div which will clear and reset the timeouts respectively..
you probably wnat to stop ajax function from running what you are looking for is called
var pfunc = $.ajax({
url: 'backend/posts.php',
success: function(data) {
$('#posts').html(data);
$('#posts').fadeIn(2000);
setTimeout(posts,2000);
}
});
more on hover event
$("idofyourdiv").hover(
function () {
pfunc.abort();
},
function () {
pfunc();
}
);
First, I'd structure your base code somewhat like this:
var timer = null;
var request = null;
function posts() {
request = $.ajax({
url: 'backend/posts.php',
success: function(data) {
$('#posts').html(data).fadeIn(2000);
timer = setTimeout(posts, 2000);
}
});
}
posts();
Next, to clear the timer, run clearTimeout() on the timer object. timer stores the id of your timeout function, which might not exist when you try to clear it, so safely clear it like this:
if (timer !== null) {
clearTimeout(timer);
}
Finally, you should abort the AJAX request, so just add that in as well:
if ((timer !== null) && (request !== null)) {
clearTimeout(timer);
request.abort();
}
This one will check if your div is being hovered. And if it is true, the ajax call will be cancelled.
Trying not to modify too much your code:
function posts()
{
pfunc = $.ajax({
url: 'backend/posts.php',
beforeSend: function(){
if($("#posts").is(":hover")){
return false;
}
},
success: function(data) {
$('#posts').html(data);
$('#posts').fadeIn(2000);
setTimeout(posts,2000);
}
});
}
posts();
javascript is not multi threaded so you can not stop a piece of code from running. As stated in other answers you may call abort on your ajax request but that is not stopping any code, it just aborting a request. And I'm not even sure its smart to abort the request when your just going to make the request again when the user stops hovering. I would let the request go thru and check the hover state in the response. If the hover state does not match your condition buffer the response and wait till the user stops hovering then resume your execution. Something like the following...
var hovering = false;
var onResponse = null;
$('.Posts').mouseover(function() {
hovering = true;
});
$('.Posts').mouseout(function() {
hovering = false;
onResponse && onResponse();
});
function posts() {
pfunc = $.ajax({
url: 'backend/posts.php',
success: function(data) {
onResponse = function() {
if(hovering) return;
$('#posts').html(data);
$('#posts').fadeIn(2000);
setTimeout(posts, 2000);
onResponse = null;
};
onResponse();
}
});
}
posts();

Recaptcha Login page

I would like to know how to merge these two Javascript ajax scripts. So that my login info will check my DB for user name and password match as well as recaptcha will work. I have very little javascript experience. Thank you. Two different PHP pages that need to work for each i think because these both echo the answer.
Login script.
<script language="javascript">
$(document).ready(function()
{
$("#login_form").submit(function()
{
//remove all the class add the messagebox classes and start fading
$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
//check the username exists or not from ajax
$.post("ajax_login.php",{ user_name:$('#username').val(),password:$('#password').val(),rand:Math.random() } ,function(data)
{
if(data=='yes') //if correct login detail
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Logging in.....').addClass('messageboxok').fadeTo(900,1,
function()
{
//redirect to secure page
document.location='edujob.php';
});
});
}
else
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('incorrect').addClass('messageboxerror').fadeTo(900,1);
});
}
});
return false; //not to post the form physically
});
//now call the ajax also focus move from
});
</script>
Recaptcha script
function validateCaptcha()
{
challengeField = $("input#recaptcha_challenge_field").val();
responseField = $("input#recaptcha_response_field").val();
//alert(challengeField);
//alert(responseField);
//return false;
var html = $.ajax({
type: "POST",
url: "ajax.recaptcha.php",
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
async: false
}).responseText;
if(html == "success")
{
$("#captchaStatus").html("YES");
// Uncomment the following line in your application
return false;
}
else
{
$("#captchaStatus").html("Your captcha is incorrect. Please try again");
Recaptcha.reload();
return false;
}
}
I guess this works for me thanks for looking.
<script language="javascript">
function validateCaptcha()
{
challengeField = $("input#recaptcha_challenge_field").val();
responseField = $("input#recaptcha_response_field").val();
$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
//alert(challengeField);
//alert(responseField);
//return false;
var html = $.ajax({
type: "POST",
url: "ajax.recaptcha.php",
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
async: false
}).responseText;
if(html == "success")
{
$("#captchaStatus").html("YES");
$.post("ajax_login.php",{ user_name:$('#username').val(),password:$('#password').val(),rand:Math.random() } ,function(data)
{
if(data=='yes') //if correct login detail
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Logging in.....').addClass('messageboxok').fadeTo(900,1,
function()
{
//redirect to secure page
document.location='edujob.php';
});
});
}
else
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Incorrect username or password').addClass('messageboxerror').fadeTo(900,1);
});
}
});
return false;
}
else
{
$("#captchaStatus").html("Your captcha is incorrect. Please try again");
Recaptcha.reload();
return false;
}
}
</script>

something wrong with this jquery?

i have these two jquery scripts on my html page, one of them loads more results(like pagination), and the other one replies to users messages, just like twitter!
the replies works(inserts username into textbox), when the page is on default, but when i load more results, the loaded results wnt insert the username into the textbox!! these are the two scripts,
the replies jquery:
function insertParamIntoField(anchor, param, field) {
var query = anchor.search.substring(1, anchor.search.length).split('&');
for(var i = 0, kv; i < query.length; i++) {
kv = query[i].split('=', 2);
if (kv[0] == param) {
field.val(kv[1]);
return;
}
}
}
$(function () {
$("a.reply").click(function (e) {
insertParamIntoField(this,"status_id",$("#status_id"));
insertParamIntoField(this,"reply_name",$("#reply_name"));
insertParamIntoField(this, "replyto", $("#inputField"));
$("#inputField").focus()
$("#inputField").val($("#inputField").val() + ' ');
e.preventDefault();
return false; // prevent default action
});
});
the loadmore jquery script:
$(function() {
//More Button
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ul.statuses").append(html);
$("#more" + ID).remove();
}
});
}
else
{
$(".morebox").html('The End');
}
return false;
});
});
EDIT: when i load more posts, and i click reply the page is refershed, so that ends up with loaded data being hidden again!!
If the reply button is being replaced by the ajax, this might be a workaround.
$(function () {
$("a.reply").live(click, function (e) {
insertParamIntoField(this,"status_id",$("#status_id"));
insertParamIntoField(this,"reply_name",$("#reply_name"));
insertParamIntoField(this, "replyto", $("#inputField"));
$("#inputField").val($("#inputField").val() + ' ').focus();
e.preventDefault();
});
});
Also... If the status_id, reply_name , replyto info is contained within your reply button, make sure these data exists for each reply button after the more button is clicked.

Categories