I have a page with many checkboxes on it, I wrote a JS code that makes call to PHP page for each page, I want to refresh the page after the call has completed..
Here is my code
$(".matchFrnds").each(function(){ //For each CheckBox
if($(this).is(':checked')){
var sendData= $(this).val();
$.post('Call to PHP Page',{sendData:sendData},function(data){
window.location.reload();
});
}
});
The problem is that the page reloads after completing few checboxes, so if there are 60 checkboxes, the page reloads after making call for 10 checkboxes. I also changed the place for window.location.reload(); but the results are same, I want that once the call for all the checkboxes is completed then it reloads.
You can check how many calls you have finished then reload
var boxes = $(".matchFrnds:checked").length;
var calls = 0;
$(".matchFrnds").each(function(){ //For each CheckBox
if($(this).is(':checked')){
var sendData= $(this).val();
$.post('Call to PHP Page',{sendData:sendData},function(data){
calls++;
if(calls >= boxes) {
window.location.reload();
}
});
}
});
It is really easy.
You just need to set a counter, and call reload() on the last one.
The idea would be to have another variable...
// Save the element to iterate in a variable
var matchFrnds = $(".matchFrnds"),
//and save its length too
length = matchFrnds.length;
//Iterate over it
matchFrnds.each(function() {
// modify the counter
--length;
if ($(this).is(":checked")) {
// do your things
$.post( ... , function(data) {
//do what you need to do with the data...
// ....
// ....
});
}
//and, if it's the last element
if (!length) {
// LAST ITERATION!
window.location.reload();
}
});
And that's it.
You could use the .ajaxStop-Event
http://api.jquery.com/ajaxStop/
you can try with this after complete your request:
location.reload();
Related
I have two scripts, first of them clicks on the button and after that browser opens a new window, where i should click on the other button by the second script, is it possible to run them both at the same time, I mean like unite those scripts together?
function run() {
var confirmBtn = document.querySelector(".selector,anotherSelector ");
}
after this new window appears and here`s the second part of my script
var rooms = document.querySelectorAll(" .btn-a-offers");
console.log(rooms);
for (var room = 0; room < rooms.length; room++) {
rooms[room].click();
}
var prices = document.querySelectorAll(" .li-right-side>strong");
console.log(prices);
for (var price = 0; price < price.length; price++) {
}
var prices = [];
document.querySelectorAll(".new-pa-hotelsoffers .li-right-side > strong").forEach(function(price) {
prices.push(parseFloat(price.innerHTML.replace(/[^0-9.]/g, "")))
})
console.log(
Math.min(...prices).toFixed(2)
)
My English is not that good so I want to be sure that I explained everything right, second script must be executed in the new window, that opens after first script
Depending on the logical dependancy of your application and the use of the functions, you could execute the second function in a document.ready function on the second page.
Example:
<script>
//jQuery
$( document ).ready(function() {
secondFunction();
});
//Pure JS
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
r(function() {
secondFunction();
});
</script>
However, if the page is to act independantly, and the second function is only to respond upon the execution of the first function, then that solution would not be the one you are looking for.
In the case where the function has to act entirely dependant on the use of the first function you could parse a value in the URL (better known as a GET variable) and check if that value is set.
Example:
<script>
functionOne() {
window.location.href = '/your_page.php?click=1';
}
</script>
Then on your second page you need to retrieve the GET variable.
<?php
$clicked = $_GET['click'];
?>
You can then perform a check to see if the variable has been set and fire your function upon that logic.
<?php
if($clicked != "") {
echo '
<script>
functionTwo();
</script>';
}
?>
Another way of doing it could be by the use of AJAX and have the other function execute in the AJAX' success function. That way you can eliminate the use of the GET variable, which is visible in the URL.
Example:
<script>
functionOne() {
$.ajax({
type : "POST", //or GET
url : "/your_page.php",
data : {
//parse your POST variable data if any
// variable : value,
// anotherVairable : anotherValue
// [....]
},
success: function (html) {
//Success handling
secondFunction();
}
})
}
</script>
Note that the AJAX used in the example is jQuery AJAX, so if you want to use some AJAX logic involving this structure, you'll need to include a jQuery library.
You should pass some parameter in the URL query like this:
// first-script.js
openNewWindow('http://example.com?run-second-script=1') // openNewWindow is fake function, just for demo
// second-script.js
if (window.location.search.includes('run-second-script=1')) { ... your code here ...}
I have a page displaying data from a json feed and I also have a button which loads more of the feed on click of a button. My aim is to append some content inside the page for each feed item. I have been able to create a function which does this on load of the page, but I am unsure how to make this work with the aysynchronous loading of more data.
I understand I need to use the .done() callback to make this work but need some guidance how to implement it correctly.
This function appends the new content initially:
function appendFeed() {
$('.feed__item').each(function (index) {
$feedItem = $('.feed__item', $(this));
$feedItem.append('<div class="feed-gallery"></div>');
for (var i = 1; i <= 5; i++) {
var $count = i;
if ($count > 1) {
$('.feed.gallery', $(this)).append('<div><img data-lazy="//placehold.it/50x50"></div>');
};
});
}
This is where the .done() callback is referred, on click of a button:
$('button').click(function(){
$.getJSON(uri, function (json, textStatus) {
// do stuff
}).done(function (json) {
// do stuff - in my case this would be appendFeed()
});
});
I have already called the appendFeed() function, but if I put it inside the .done() callback on click the button, then it appends the feed again. How do i prevent the duplication for the feed that is already on the page?
This is how you will write.
<script type="text/javascript">
$.getJSON("/waqar/file.php").done(function (data) {
$(".output").append(data);
});
</script>
I am using ajaxComplete to run some functions after dynamic content is loaded to the DOM. I have two separate functions inside ajaxComplete which uses getJSON.
Running any of the functions once works fine
Running any of them a second time causes a loop cause they are using getJSON.
How do I get around this?
I'm attaching a small part of the code. If the user has voted, clicking the comments button will cause the comments box to open and close immediately.
$(document).ajaxComplete(function() {
// Lets user votes on a match
$('.btn-vote').click(function() {
......
$.getJSON(path + 'includes/ajax/update_votes.php', { id: gameID, vote: btnID }, function(data) {
......
});
});
// Connects a match with a disqus thread
$('.btn-comment').click(function() {
var parent = $(this).parents('.main-table-drop'), comments = parent.next(".main-table-comment");
if (comments.is(':hidden')) {
comments.fadeIn();
} else {
comments.fadeOut();
}
});
});
Solved the problem by checking the DOM loading ajax request URL
$(document).ajaxComplete(event,xhr,settings) {
var url = settings.url, checkAjax = 'list_matches';
if (url.indexOf(checkAjax) >= 0) { ... }
}
I am trying to display the database table using php. When the page is loaded I need to show all table data and when I select the dropdown select, I neeed to display only data related to it ie.using where condition. I don't need any sql query or php code for it, I just need jquery.
$(document).ready(function()
{
$('#myHref').change(function()
{
var value = $('#myHref').val();
$.get('get_projectName.php',{id:value},function(data)
{
$('#projectDetail').html(data);
});
});
$('#myHref').on('change',function()
{
$('#projectDetail').fadeIn();
});
});
Here when I select drop down menu id="myHref" execute get_projectName.php, but I need to execute get_projectName.php when page is load before select dropdown so I can display all data
Plz Help!!
bt I need to execute get_projectName.php when page is load before select dropdown so i can display all data
So I see you want to initially load execute get_projectName.php once when page loads and also execute it if there are any changes in the dropdown. So you can do like below
$(document).ready(function() {
//make a call initially on page load
var firstOptionValue = $("#myHref option:eq(1)").val() // take first option value as default
$.get('get_projectName.php',{id:firstOptionValue},function(data)
{
$('#projectDetail').html(data);
});
$('#myHref').change(function(){
var value = $('#myHref').val();
$.get('get_projectName.php',{id:value},function(data)
{
$('#projectDetail').html(data);
});
});
$('#myHref').on('change',function(){
$('#projectDetail').fadeIn();
});
});
Refactoring the code, you can just pull out the common logic into a function and call that function by passing the required value, See below
$(document).ready(function() {
//make a call initially on page load
var firstOptionValue = $("#myHref option:eq(1)").val(); // take first option value as default
GetProjectDetails(firstOptionValue);
$('#myHref').change(function(){
var value = $('#myHref').val();
GetProjectDetails(value);
});
$('#myHref').on('change',function(){
$('#projectDetail').fadeIn();
});
function GetProjectDetails(value){
$.get('get_projectName.php',{id:value},function(data)
{
$('#projectDetail').html(data);
});
}
});
In the above code you are trying to pass the selected id to php file through $.get() when the dropdown is changed. it is fine, if you want to display all the data when page is loaded then you should have another php which returns all the data in db and doesn't take any value. And write the code as below
$(document).ready(function() {
$.get('get_allDataFromDb.php',function(data)
{ $('#projectDetail').html(data);
});
$('#myHref').change(function(){
var value = $('#myHref').val();
$.get('get_projectName.php',{id:value},function(data)
{ $('#projectDetail').html(data);
});
});
$('#myHref').on('change',function(){
$('#projectDetail').fadeIn();
});
});
function getData(value) {
params = {};
if value
params.id = value;
$.get('get_projectName.php', params, function (data) {
$('#projectDetail').html(data);
});
}
// Get Data onLoad
getData($('#myHref').val());
$('#myHref').on('change',function(){
getData($('#myHref').val());
$('#projectDetail').fadeIn();
});
Looks like your element (e.g. #myHref) don't exist at time when your script . And when you want to show all data on load just call function eg.
function getData(){//ajax here}
getData();
running. Are there any errors? or something that can help?
Try like this
$(document).on("change", "#myHref" , function() {
// Your Code Here
});
let me know in case it still dont work.
Ok , here is my another answer that how you can trigger some event after our document get ready .
hope this will be helpful to you .
<script>
$(document).ready(function(){
//Function for AJAX Call
function GetData(){
var value = $('#myHref').val();
$.get('get_projectName.php',{id:value},function(data)
{
$('#projectDetail').html(data);
//
$('#projectDetail').fadeIn();
// Any other code here you want to write.
});
}
$('#myHref').change();
//OR you can use
$("#myHref").trigger("change");
});
$(document).on("change", "#myHref" , function() {
// Call the function as change evvent is triggered
GetData();
});
</script>
I'm trying to create a PHP page that periodically updates values of several elements on the page. I'm using a host that limits my hits per day, and each hit to any page they're hosting for me counts against my total. Therefore, I'm trying to use JQuery/AJAX to load all of the information that I need from other pages at one time.
I'm calling the following index.php. This method achieves the desired affect exactly the way I want it, but results in three hits (dating.php, dgperc.php, and pkperc.php) every two seconds:
var focused = true;
$(window).blur(function() {
focused = false;
});
$(window).focus(function() {
focused = true;
});
function loadData() {
if (focused) {
var php = ["dating", "dgperc", "pkperc"];
$.each(php, function(index, value) {
$('#'+this).load(this+'.php');
});
}
}
$(document).ready(function() {
loadData();
});
setInterval(function() {
loadData();
}, 2000);
I'm calling the following index1.php. This is where I'm at as far as a method that only results in one hit every two seconds. My workaround is that I have combined the three php pages that I was loading into one, dating1.php. I load this into a div element, #cache, all at once. This element is set to hidden using CSS, and then I just copy its inner HTML into the appropriate elements:
var focused = true;
$(window).blur(function() {
focused = false;
});
$(window).focus(function() {
focused = true;
});
function loadData() {
if (focused) {
var php = ["dating", "dgperc", "pkperc"];
$('#cache').load('dating1.php');
$.each(php, function(index, value) {
$('#'+this+'1').html($('#'+this).html());
});
}
}
$(document).ready(function() {
loadData();
});
setInterval(function() {
loadData();
}, 2000);
Dating1.php will produce different outputs every time it's run, but here is an example of the output:
<span id = "dating">4 years, 7 months, 3 weeks, 10 seconds ago.</span>
<span id = "dgperc">21.9229663059</span>
<span id = "pkperc">22.2121099923</span>
On document ready, index1.php does not function properly: the #cache element isn't filled at all, so the other elements don't get filled either. However, after two seconds, the loadData() function runs again, and then the #cache element is filled correctly, and so are the other elements. For some reason, this isn't a problem on my index.php page at all, and I'm not sure why there's a difference here.
How can I get #cache to load the first time so that the page loads correctly? Or is there a better way to do this?
Each AJAX call is basically a page visit in the background. Like telling your assistant three different times to get you one coffee. Or telling them one to get you three coffees.
If you don't want to combine your three PHP pages into one - thus keeping code separate and easier to maintain. Consider creating one "cache.php" script and inside it:
cache.php:
$outputData = array('dating' => false, 'dgperc' => false, 'pkperc' => false);
foreach($outputData as $file => &$data)
{
//buffer output
ob_start();
//run first script (be smart and file_exists() first)
include_once($file . '.php');
$data = ob_get_clean();
}
//output JSON-compliant for easy jQuery consumption
echo json_encode($outputData);
Then in your javascript:
function loadData() {
if (focused) {
//call ajax with json and fill your spans
$.ajax({
async: true,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqxhr) {
$('#dating').html(data.dating);
$('#dgperc').html(data.dgperc);
$('#pkperc').html(data.dgperc);
// NOTE... do a console.dir(data) to get the correct notation for your returned data
},
url: 'cache.php'
});
}
You are calling cache.php once every two seconds, saving on the 3-hits of calling the php files individually. Using a middle-man file you keep your scripts separate for maintainability.