How can I refresh the append data without page refresh jquery? - javascript

I am trying to use ++ in jquery to append data, and I face a problem, I need to refresh the value again if I click other button without refresh page, how can I do that? The var count will increase as I clicked, I want to know if I can start over this count again when I click second button.
var count='1';
$('#good').on('click',function(){
$.ajax({
url: MyAjaxSearch.ajaxurl,
type:'POST',
cache: false,
data:data,
success: function(data){
count++
}
});
}):
$('#second').on('click',function(){
//refresh the var count, start from 1 again
count++
});

Updated Answer (based on clarification from OP):
I want to if I can start over this count again when I click second button
$('#second').on('click',function(){
//refresh the var count, start from 1 again
count = 1;
});
Live Example:
var count = 1;
$('#good').on('click', function() {
count++;
snippet.log("Incremented, count = " + count);
});
$('#second').on('click', function() {
//refresh the var count, start from 1 again
count = 1;
snippet.log("Reset, count = " + count);
});
<input type="button" id="good" value="Increment">
<input type="button" id="second" value="Reset">
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Or if you wanted the first incremented number to be 1, start with count = 0:
Live Example:
var count = 0;
$('#good').on('click', function() {
count++;
snippet.log("Incremented, count = " + count);
});
$('#second').on('click', function() {
//refresh the var count, start from 0 again
count = 0;
snippet.log("Reset, count = " + count);
});
<input type="button" id="good" value="Increment">
<input type="button" id="second" value="Reset">
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Original Answer:
I'm going to take a total guess at it here and say that in your ajax callback, you're modifying the page in some way, for instance:
$('#good').on('click', function() {
$.ajax({
url: MyAjaxSearch.ajaxurl,
type: 'POST',
cache: false,
data: data,
success: function(data) {
$("selector-for-some-elements").html("new content"); // <===
current_page++
}
});
});
And that you want a click on the other element to reset things back to the way they were when the page was first loaded.
If so, then you can do something like this (see comments):
var current_page = '1';
// *** A variable for remembering the original content
var originalContent;
$('#good').on('click', function() {
$.ajax({
url: MyAjaxSearch.ajaxurl,
type: 'POST',
cache: false,
data: data,
success: function(data) {
// Grab the elements we're going to change
var elementsToChange = $("selector-for-elements");
// If we don't have saved content...
if (!originalContent) {
// Save the original content
originalContent = elementsToChange.clone();
}
// Modify it
elementsToChange.html(/*....*/);
current_page++
}
});
});
$('#second').on('click', function() {
// If we have original content...
if (originalContent) {
// Put it back
$("selector-for-some-elements").replaceWith(originalContent);
current_page = 1;
}
});
Obviously, many aspects of the above would vary based on what you're actually trying to do, but as you haven't told us what that is, this is the best I can do...

Related

Ajax update post request on click jQuery

I would like to click on a previous or next button and update the ajax post request. The parameter I want to change is the variable called "page". The URL of the request takes this variable to show the right page. When I click on a previous or next button I want to change the "page" variable value. Thanks.
$(document).ready(()=>{
var pageSize = "pageSize=10";
//want to change the page number on click
var page = "page=1"
var requestIndex = $.ajax({
type: 'POST',
url: `url`,
beforeSend: function(){
$("#loading").show();
},
complete: function(){
$("#loading").hide();
}
});
// console.log(request)
requestIndex.done((data)=>{
var done = JSON.parse(data)
// console.log(done)
done.forEach((result, index)=>{
// res.push(result)
var firstName = result.FirstName;
var lastName = result.LastName;
var modelYear = result.ModelYear;
var make = result.Make;
var model = result.Model;
var dealership = result.Dealership;
$('#test>tbody').append(`
<tr>
<td>${firstName} ${lastName}</td>
<td>${modelYear}</td>
<td>${make}</td>
<td>${model}</td>
<td>${dealership}</td>
</tr>
`)
})
var tr = $('table').find("tr");
var resultQuant =[]
resultQuant.push(tr)
var pages = []
//loop over each result and create pagination
resultQuant.forEach(function(res, index){
console.log(res.length);
if(res.length > 9){
$('#prev_page').append(`
Prev Page
`)
$('#next_page').append(`
Next Page
`)
}
})
});
requestIndex.fail(function(jqXHR, textStatus) {
console.log('failed')
});
})
Here is a working snippet for what I think you're looking for. I had to make some changes, some for aesthetics, and some for functionality. Here's the functional changes/updates:
Your whole ajax/refresh table script needed to be outsourced to a function so it could be called multiple times.
The page and pageSize variables are better left as numbers rather than queryString strings
I created a delegated event listener on your buttons. It's one listener that will handle either button. The listener callback finds out if its the next or previous button that was clicked, then calls the goToPage() function with the incremented onPage variable
The table is now cleared before each new data batch is written to it, as you'd expect a paginated result to be
The buttons should disable/enable according to the pagination, so I put in a script to test if we're at the first page or the last page to disable/enable them
I changed all your vars to lets because that's the way we initialize block variables nowadays
let onPage, pageSize = 10;
$(document).ready(() => {
goToPage(1)
$('body').on('click', '#next_page, #prev_page', function() {
inc = 1;
if ($(this).attr('id') === 'prev_page') inc = -1;
goToPage(onPage + inc);
})
})
function goToPage(page) {
let requestIndex = $.ajax({
type: 'POST',
url: `url`,
beforeSend: function() {
$("#loading").show();
},
complete: function() {
$("#loading").hide();
}
});
requestIndex.done((data) => {
onPage = page;
$('#test>tbody').html('');
JSON.parse(data).forEach((result, index) => {
$('#test>tbody').append(`
<tr>
<td>${result.FirstName} ${result.LastName}</td>
<td>${result.ModelYear}</td>
<td>${result.Make}</td>
<td>${result.Model}</td>
<td>${result.Dealership}</td>
</tr>
`)
})
if (onPage > 1) $('#prev_page').removeAttr('disabled');
else $('#prev_page').attr('disabled', true)
if (JSON.parse(data).length === pageSize) $('#next_page').removeAttr('disabled');
else $('#next_page').attr('disabled', true)
});
requestIndex.fail(function(jqXHR, textStatus) {
console.log('failed')
});
}
#loading {
display: none'
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='loading'>Loading...</div>
<table id='test'>
<tbody></tbody>
</table>
<button id='prev_page'>Prev Page</button>
<button id='next_page'>Next Page</button>

How to get my dynamically created div to show up on page after ajax call

I have a project that I am trying to implement with jquery. I have an add button, so everytime it is clicked, it will create a new record on in my database. I am trying to figure out how to get my ajax call to recognize the new data and display it on the screen, without me having to manually refresh the screen, I was hoping to just use fadeIn or something similar to only show my new div.
This is for a checklist system,so someone can edit a checklist by adding steps on the fly and reorder existing steps
I wrote a loadData function to loop through my records and append the appropriate data, but not sure how to auto refresh my div when someone adds a new step. I don't want to reload the entire page, only the newly created div.
$(function() {
loadData();
});
// drag and drop steps and update the database
$('#steps').sortable({
update: function(event, ui) {
var data = $(this).sortable('serialize');
data = data + '&id=' + json.IDchecklist + '&ver=' + json.Version;
$.ajax({
data: data,
type: 'POST',
url: '../Processes/Reorder.php',
success: (function() {})
});
}
});
//load data
function loadData() {
$.ajax({
url: '../json/test.php',
type: 'GET',
dataType: 'json',
success: function(data) {
json = data
$('#details').find('h2').html(data.IDchecklist);
$('#details').find('h4').html(data.Status);
$.each(data, function(k, v) {
if (k == "Steps") {
count = 1;
$.each(v, function(key, value) {
$('#steps').append('<span>' + count + '</span><div id=step' + value.IDstep + '>' + value.StepText + '</div>');
count++;
text[count] = value.StepText;
})
}
})
}
})
}
//add new step
$('#add').click(function() {
console.log(count);
div = $('#step-' + count);
$.ajax({
type: 'POST',
data: {
id: json.IDchecklist,
ver: json.Version,
step: count
},
url: '../processes/addStep.php',
success: (function() {
div.fadeIn('fast')
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<div class="jumbotron"></div>
<div id="details">
<h2></h2>
<h4></h4>
</div>
<div id="steps">
</div>
<button id=add value="Add">Add</button>

Preventing multiple requests from ajax

I have "load more" button, and if I click it fast enough it load the same content twice, and I want to prevent it.
This is how I call to the load more with ajax:
<script type="text/javascript">
function loadmore() {
var val = document.getElementById("result_no").value;
var userval = document.getElementById("user_id").value;
$.ajax({
type: 'post',
url: 'fetch.php',
data: {
getresult: val,
getuserid: userval
},
context: this,
success: function(response) {
var content = document.getElementById("result_para");
content.innerHTML = content.innerHTML + response;
document.getElementById("result_no").value = Number(val) + 10;
}
});
}
</script>
<div id="content">
<div id="result_para">
</div>
</div>
<input type="hidden" id="user_id" value="<?php echo $userid;?>">
<input type="hidden" id="result_no" value="15">
<input type="button" id="load" onclick="loadmore()" value="Load More Results">
You could set a loading variable to true at the start of loadmore, and set it back to false in the ajax callback. loading should be declared outside of loadmore though (see what a closure is).
var loading = false;
function loadmore()
{
if (loading) {
return ;
}
loading = true;
var val = document.getElementById("result_no").value;
var userval = document.getElementById("user_id").value;
$.ajax({
type: 'post',
url: 'fetch.php',
data: {
getresult:val,
getuserid:userval
},
context: this,
success: function (response) {
loading = false;
var content = document.getElementById("result_para");
content.innerHTML = content.innerHTML+response;
document.getElementById("result_no").value = Number(val)+10;
},
error: function () {
loading = false;
}
});
}
Instead of using that variable, you could also programmatically disable/enable the button, but that means that your button will flicker if the request is fast.
You can prevent from this by disable the button after first click, so change this lines:
success: function (response) {
var content = document.getElementById("result_para");
content.innerHTML = content.innerHTML+response;
document.getElementById("result_no").value = Number(val)+10;
}
With this lines:
success: function (response) {
document.getElementById("load").disabled = true;
var content = document.getElementById("result_para");
content.innerHTML = content.innerHTML+response;
document.getElementById("result_no").value = Number(val)+10;
document.getElementById("load").disabled = false;
}
you could disable the button when the "load more" button is clicked then then use the javascript function setTimeout to remove the disabled attribute from the button after a period of time. This would mean that the button would not be able to be clicked after the first click and even if the ajax request returned an error the button would still be able to be clicked.
$('#load').click(function {
// disable the button
$(this).prop('disabled', true);
// after three seconds enable the button again
var timeout = setTimeout(function() { $(this).prop('disabled', false); }, 3000);
});

How to plus value with 1 When scroll to bottom and update into input form?

How to plus value with 1 When scroll to bottom page ?
First, Load page index.php
it's will show 1 (from echo $_POST[page]) and then scroll to bottom page it's will show 1 (from echo $_POST[page]) and 1 (from echo $_POST[page]) and 1 (from echo $_POST[page]) ...
i want to apply this code for work like this
First, Load page index.php
it's will show 1 (from echo $_POST[page]) and then scroll to bottom page it's will plus $_POST[page] with 1 and update into input id='page_number' it's will show 2 and 3 and 4 ...
How can i do that ?
index.php
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<script>
$("#fid").submit(f1());
</script>
<form method="post" id="fid" action="Javascript:void(0);" >
<input type='hidden' id='page_number' name='page' value='1'/>
</form>
<div id="demoajax">
<script>
function f1(){
$('#demoajax').hide();
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#fid').serialize(),
success: function(data){
$('#demoajax').show();
$('#demoajax').html(data);
}
});
return false;
}
// on load page call function code //
$(document).ready(f1());
</script>
<script type="text/javascript">
$(document).ready(function(){
$(window).scroll(function(){
var height = $('#demoajax').height();
var scroll_top = $(this).scrollTop();
if(($(window).scrollTop() + $(window).height() == $(document).height())){
//$('#demoajax').hide();
//$('#protect_form_between_ajax_process').show();
//$('#loading').show();
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#fid').serialize(),
success: function(data){
$('#demoajax').append(data);
}
});
return false;
}
return false;
});
});
</script>
test.php
<?PHP
echo "PAGE ".$_POST[page];
?>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
You have to increment the page number before each AJAX call:
before
if(($(window).scrollTop() + $(window).height() == $(document).height())) {
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#fid').serialize(),
success: function(data) {
$('#demoajax').append(data);
}
});
return false;
}
after
if(($(window).scrollTop() + $(window).height() == $(document).height())) {
var currentPage = parseInt($('#page_number').val(), 10);
currentPage = currentPage + 1;
$('#page_number').val(currentPage);
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#fid').serialize(),
success: function(data) {
$('#demoajax').append(data);
}
});
return false;
}
Beyond that, your code has some problems and could be written as follow:
<!-- Edit 1: HTML comes first, script come later -->
<!-- Edit 2: use real values in HTML attributes instead of JS code -->
<form method="post" id="fid" action="test.php" >
<input type="hidden" id="page_number" name="page" value="1"/>
</form>
<!-- Edit 3: you had unclosed div tag -->
<div id="demoajax"></div>
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<script>
// Edit 4: here, you can use only one script tag for all of your JS code
// Edit 5: declare functions first, use them later
// (you had the code $("#fid").submit(f1()); too early in the page)
function f1() {
$('#demoajax').hide();
var $form = $('#fid');
$.ajax({
// Edit 6: retrieve url and type parameter from the HTML form
// this avoid hard-coded values
url: $form.attr('action'),
type: $form.attr('method'),
data: $form.serialize(),
success: function(data) {
// Edit 7: use method chaining where you can
$('#demoajax').show().html(data);
}
});
// Edit 8: don't return false within event handler
}
// Edit 9: avoid premature call invocation problem
$("#fid").submit(f1);
// on load page call function code //
// Edit 10: avoid premature call invocation problem
$(document).ready(f1);
$(document).ready(function() {
$(window).scroll(function() {
// Edit 11: store and reuse jQuery variables
var $window = $(window);
var $demoajax = $('#demoajax');
// Edit 12: remove unused variables scroll_top and height
// Edit 13: use triple equal sign "===" instead of double equal "=="
if(($window.scrollTop()+$window.height() === $(document).height())) {
//$('#demoajax').hide();
//$('#protect_form_between_ajax_process').show();
//$('#loading').show();
// ==============================
// Edit 14: increment the counter
var currentPage = parseInt($('#page_number').val(), 10);
currentPage = currentPage + 1;
$('#page_number').val(currentPage);
// ==============================
var $form = $('#fid');
$.ajax({
// Edit 15: same as above, avoid hard-coded values
url: $form.attr('action'),
type: $form.attr('method'),
data: $form.serialize(),
success: function(data) {
$demoajax.append(data);
}
});
// Edit 16: remove unnecessary return statement here
}
// Edit 17: don't return false within event handler
});
});
</script>
However, personally I would have write it using the module pattern, something like this:
var infiniteScrollLoader = function($container, $form, initialPageNumber) {
var $window = $(window);
var $document = $(document);
var pageNumber = initialPageNumber;
// this function crawls the content of the next page
function requestNextPageContent() {
var request = $.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: pageNumber
});
// when a request is made, increment page number automatically
// avoid spaghetti code, use promise/deferred pattern
request.then(incrementPageNumber);
return request;
}
// use simple dedicated functions
function incrementPageNumber() {
pageNumber = pageNumber + 1;
}
function showContainer() {
$container.show();
}
function appendNextPageContent(data) {
$container.append(data);
}
function showNextPage() {
requestNextPageContent().then(appendNextPageContent);
}
function setPageNumber(pageNumber) {
pageNumber = pageNumber;
}
function onScroll() {
if(($window.scrollTop() + $window.height() === $document.height())) {
showNextPage();
}
}
function init() {
$window.scroll(onScroll);
$container.hide();
// do initial request
// this line should be self-explained and can be read as "text":
// request the content of the next page, then show the container
// then append the page content into the current page
requestNextPageContent()
.then(showContainer)
.then(appendNextPageContent);
}
return {
init: init,
showNextPage: showNextPage,
setPageNumber: setPageNumber
};
};
// init and don't do anything else
infiniteScrollLoader.init( $('#demoajax'), $('#fid'), 1 );
// or use it programatically
infiniteScrollLoader.showNextPage(); // show page 2
infiniteScrollLoader.showNextPage(); // show page 3
infiniteScrollLoader.setPageNumber(6);
infiniteScrollLoader.showNextPage(); // show page 6

Shopify 'View all' button implementation

Shopify has a max display limit of 50 products per page.
To get around this limitation I've made a jquery code snippet. The script grabs the url from each pagination link, and performs an ajax load - adding the result to the main content area.
It worked perfectly for me - but not for my friend. He was missing a page each time. So I thought it may be an async issue with his connection being slower than mine. So I rewrote the script a few times to be more explicit. But it still didn't work for him.
After much trouble shooting, it appears that if logged in as admin - everything works. If not logged in, then the middle page fails to load.
Here is my most recent code:
{% if template contains 'collection' %}
<script>
$(document).ready(function() {
$('#viewFewerProducts').hide();
// when viewAllProducts is clicked
$("#viewAllProducts").click( function (e) {
e.preventDefault();
$("#viewAllProducts , #paginationMagic").hide(); // hide pagination buttons
// and clear out collectionThumbs - but add the ViewAllRow back in.
$("#collectionThumbs").empty().html('<div class="row" id="viewAllRow"></div>');
// see how many pagination links there are. Add 1 because of index 0
var numberOfPages = $('#paginateNumbers .item').length + 1
var path = window.location.pathname;
var pageURL;
// this bit adapted from blog post... but cant remember url
for (var i=1;i<numberOfPages;i++) {
$.ajax(
{
type: 'GET',
url: pageURL = path + "?page=" + i, // build pagination page url
ajaxI: i, // Capture the current value of 'i'.
success: function(data)
{
i = this.ajaxI; // Reinstate the correct value for 'i'.
$(data).find('#collectionThumbs').each(function()
{
// Read data... and stick it in the page
var importedCollection = $(data).find("#collectionThumbs a").unwrap();
importedCollection.appendTo("#viewAllRow");
});
},
error: function(data)
{
// Handle errors here.
}
});
}
///
$("#viewFewerProducts").show();
});
// reload the window
$("#viewFewerProducts").click( function (e) {
e.preventDefault();
$("#viewFewerProducts").text('loading...').removeAttr('id');
location.reload();
});
});
</script>
{% endif %}
and I've written it several other different ways. It just doesn't work if not logged in? I've checked - and dont get any errors in the console either.
So my question is - does anyone know why it would work if logged in, but not if not logged in to admin? Its really bizzarre - as this is not running on any admin pages.
Edit:
{% if template contains 'collection' %}
<script>
$(document).ready(function() {
$('#viewFewerProducts').hide();
$("#viewAllProducts").click( function (e) {
e.preventDefault();
$("#viewAllProducts , #paginationMagic").hide();
var numberOfPages = $('#paginateNumbers .item').length + 1
var path = window.location.pathname;
// console.log(path);
var pageURL;
//
for (var i=1;i<numberOfPages;i++) {
// console.log(i + 'a')
$.ajax(
{
type: 'GET',
url: pageURL = path + "?page=" + i,
beforeSend: function() {
$("#collectionThumbs").empty();
},
ajaxI: i, // Capture the current value of 'i'.
success: function(data)
{
i = this.ajaxI; // Reinstate the correct value for 'i'.
$(data).find('#collectionThumbs').each(function() {
// Read data from XML...
$('<div class="row" id="viewAllRow' + i + '"></div>').appendTo("#collectionThumbs");
var importedCollection = $(data).find("#collectionThumbs a").unwrap();
importedCollection.appendTo("#viewAllRow" + i );
// alert("now showing " + ($("#viewAllRow" + i + " a").length) + " products" );
});
var numberOfRows = $('#collectionThumbs .row').length + 1
var viewAllRowItem = []
for (var x=1;x<numberOfRows;x++) {
//put each row into a variable
viewAllRowItem[x] = $("#viewAllRow" + x ).clone();
$("#viewAllRow" + x ).remove();
// console.log(viewAllRowItem[x])
}
for (var x=1;x<numberOfRows;x++) {
$(viewAllRowItem[x]).appendTo('#collectionThumbs');
}
},
dataType: "html",
error: function(data)
{
// Handle errors here.
}
});
}
$("#viewFewerProducts").show();
});
$("#viewFewerProducts").click( function (e) {
e.preventDefault();
$("#viewFewerProducts").text('loading...').removeAttr('id');
location.reload();
});
});
</script>
{% endif %}
The above code seems to work - not sure why... was a process of elimination. I did have to add a bit of code to reorder the elements once loaded (as some ajax responses came back more quickly than others - and appeared on the page in the wrong order).
$('[js-load-more]').on('click', function(){
var $this = $(this),totalPages = parseInt($('[data-total-pages]').val()),currentPage = parseInt($('[data-current-page]').val());
$this.attr('disabled', true);
$this.find('[load-more-text]').addClass('hide');
$this.find('[loader]').removeClass('hide');
currentPage = currentPage+1;
var nextUrl = $('[data-next-url]').val().replace(/page=[0-9]+/,'page='+currentPage);
$('[data-current-page]').val(currentPage);
$.ajax({
url: nextUrl,
type: 'GET',
dataType: 'html',
success: function(responseHTML){
$('.grid--view-items').append($(responseHTML).find('.grid--view-items').html());
},
complete: function() {
if(currentPage >= totalPages) {
$this.remove();
}
else {
$this.attr('disabled', false);
$this.find('[load-more-text]').removeClass('hide');
$this.find('[loader]').addClass('hide');
}
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="hidden" value="{{ paginate.next.url }}" data-next-url>
<input type="hidden" value="{{ paginate.pages }}" data-total-pages>
<input type="hidden" value="{{ paginate.current_page }}" data-current-page>
<div class="load-more_wrap">
<button class="btn" js-load-more>
<span load-more-text>Load more</span>
<span class="hide" loader></span>
</button>
</div>

Categories

Resources