I am using CodeIgniter.
I have a function called as reloadCart(). I have to reload this function every time because this function will reload the amount anything changes happened. This is working perfect but the issue is when I am refreshing the page then it displays the new amount.
$(document).ready(function(){
reloadCart();// function reload on page refresh
function reloadCart(){
$.ajax({
url: "<?php echo base_url(); ?>Member_controller/primaryCartload",
context: document.body,
success: function(data){
if (data !=0) {
var obj = JSON.parse(data);
if (obj.qty != 0) {
$('#totalDetails').html(obj.cart_total);
$('#totalQty').html(obj.totalQty);
}
}
else{
//alert('empty')
$('#totalDetails').html('0');
$('#totalQty').html('0');
}
}
});
}
});
Can we use something like?
load({
reloadCart();
});
You can just update your price by running that AJAX call time to time, for that you'll need to set a time after that specific time your call will be run again.
var count = 20;
setInterval(function () {
count--;
if (count === 0) {
count = 20;
reloadCart();
}
}, 1000);
So after every 20 sec this function will be called, you can amend it as required.
Related
I am making chat for my student group, and I am using AJAX to get my messages like this
//Initial call i make so user do not wait 2 seconds for messages to show
function marko() {
$("#porukice").load("messages.php"); //Load the content into the div
}
marko();
//autorefresh every 2 seconds
var auto_refresh = setInterval(
(function () {
$("#porukice").load("messages.php"); //Load the content into the div
}), 2000);
To send messages I am also using ajax, like this
var frm = $('#form1');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
document.getElementById("message").value = "";
document.getElementById('play').play();
}
});
ev.preventDefault();
});
This is part of message.php (where messages are generated)
$sql = $conn->query('(SELECT * FROM chat ORDER BY time desc limit 0, 10) ORDER BY time');
while($row = mysqli_fetch_array($sql))
{
$rows[] = $row;
}
foreach($rows as $row){
$time = date('H:i:s', strtotime($row['2']));
echo '['.$time.'] <b>'.$row['0'].'</b>: '.stripslashes($row['1'])."<br/>";
}
I am trying to play a sound when new message arrives>
only solution I came up with is to play a sound when message is sent with
document.getElementById('play').play();
as you can see in above code. I have no clue how to play it when messages are coming, when mysql row is updated.
I saw other answers on stackoverflow but they are not helping me.
NOTICE: $row['1'] is message, $row['0'] is user name and $row['2'] is time.
You could pass, from the PHP script that gets the messages, the value of the last id you got. Then, store it in a jQuery variable, and after you reload the messages, check if the ids are different, if they are (that means a new message came up), play the sound.
For example, after the foreach loop:
return json_encode(array('last_time' => $rows[count($rows)-1][2]));
On your jQuery:
var last_time = 0; // <--- New
var new_time = 0; // <--- New
// Initial call i make so user do not wait 2 seconds for messages to show
function marko() {
$("#porukice").load("messages.php"); //Load the content into the div
// New
if (last_time < new_time) {
document.getElementById('play').play();
last_time = new_time;
}
}
marko();
//autorefresh every 2 seconds
setInterval(function () { // <--- Some edits here
marko(); // <--- Some edits here
}, 2000);
// ....
var frm = $('#form1');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
document.getElementById("message").value = "";
last_time = new_time; // <--- New
new_time = data.last_time; // <--- New
}
});
ev.preventDefault();
});
I've not tested this, but you're free to do it and let me know.
EDITED to use time instead of id
I fixed this problem by creating separate file called sound.php
Sound.php is answering to get request with json response including date and time of last message
{"last_time":"2017-02-25 17:45:55"}
Then I am calling this file every 2 seconds with ajax, and if last_time has changed i play a sound
var skipped_once = false;
var old_time = 0
var auto_refresh = setInterval(function() {
$.get("sound.php", function(data) {
// if old_time different than last_time play sound
if (old_time != data.last_time) {
//do not play sound on first page load
if (skipped_once) {
document.getElementById('play').play();
out.scrollTop = out.scrollHeight - out.clientHeight;
}
skipped_once = true;
old_time = data.last_time;
}
});
}, 2000);
I have a jQuery function that loads a PHP file (which gets a JSON response from an application) every 100ms. What I am trying to do is have two different counters, one which will increment every time a request is sent and another counter which will increment as soon as it gets a JSON response. At the moment I have the following which is not working, they are both just counting the number of requests being sent:-
JQUERY
$(function() {
var MAXNUM = 9;
var count = 0;
var countSuccess = 0;
function newAsyncRequest() {
setTimeout(function() {
newAsyncRequest();
count++;
$(".request").html(count);
$.get('test.php', function(data) {
countSuccess++;
$( ".log" ).html(countSuccess);
});
}, 100);
}
newAsyncRequest();
});
PHP
require_once('scripts/php/controllers/curl.controller.php');
$postcode = 'LE11 5';
$postcode = rawurlencode($postcode);
$uri = 'http://192.168.1.110:8290/?pc='.$postcode; // Home
$response = CurlController::request($uri);
So my question is basically, how can I count the number of successful responses I am getting from .$get command?
Need to print count to .request, you were using countSuccess in both the statements
$(function() {
var MAXNUM = 9;
var count = 0;
var countSuccess = 0;
function newAsyncRequest() {
setTimeout(function() {
newAsyncRequest();
count++;
$(".request").html(count);
//need to print here
$.get('test.php', function(data) {
countSuccess++;
$( ".log" ).html(countSuccess);
});
}, 100);
}
newAsyncRequest();
});
You can use $.ajax's success parameter. The function passed to this parameter will only run if an ajax request is successful.
$.ajax({
url:"",
type: "get",
beforeSend: function(){ requestCounter++ },
success: function(){ successCounter++ }
});
What are you defijning as a success?
The .get 'success' is that the server responded which it hopefully always will do.
If you are definign success as somthign working in the PHP script then in the PHP then in the jquery success function check what was returned in 'data' to see if it was succesful.
I generally return a Json encoded array with an element called 'result' that is either set to ture or false by the PHP and the jquery can simple act on that record.
I am trying to update on screen without refresh the current percentage that is updated into a database when the user checks something but failed to accomplish this.
Problem is that in the console I get the error TypeError: a is undefined ..."resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b
and the GET request is repeated infinite. Within the get request, the response is:
{"percentage":null}. An additional problem is that the GET request seams to load complete (like getting the final response) only when the php script finishes.
I checked the database and every time I refresh the database dynamically I can see the percentage updating. So it's not a problem from the PHP or SQL, may be a problem from getter.php (file that is printing the result) and the json script.
Please help me on this issue I checked the entire day + yesterday on how to echo value from database live and tried lots of examples but did not understood complete how to do it (this is mostly related to jquery knob, want to implement it there after success). Your help is much appreciated.
Jquery:
jQuery_1_11_0('#check').on('submit', function (e) {
done();
function done() {
setTimeout(function () {
updates();
done();
}, 1000);
}
function updates() {
$.getJSON("lib/getter.php", function (data) {
$("#progressbar").empty();
$.each(data.result, function () {
percentage = this['percentage'];
if (percentage = null) {
percentage = 100;
$("#progressbar").html(percentage);
}
});
});
}
});
process.php
$urlsarray = array('google.com', 'yahoo.com', 'bing.com');
// this is a dynamic array created by the user, I am giving just a simple example
$counter = 0;
$total = count($urls1);
$session_id = rand(100000000000000, 999999999999999);
$db->query("INSERT INTO sessions (session_id, percentage) VALUES ('$session_id', '$counter')");
foreach ($urlsarray as $urls) {
doing some things
$counter++;
$percentage = ($counter/$total) * 100;
$db->query("UPDATE sessions SET percentage = '$percentage' WHERE session_id = '$session_id'");
}
$db->query("DELETE FROM sessions WHERE session_id = '$session_id'");
$percentage = 100;
getter.php
include("process.php");
global $session_id;
$readpercentage = $db->query("SELECT percentage FROM sessions WHERE session_id = '$session_id'");
$percentage = $readpercentage->fetch_assoc();
echo json_encode(array('percentage' => $percentage));
ob_flush();
flush();
EDIT 2 UPDATE
function updates() {
$.getJSON("lib/getter.html", function (data) {
$("#progressbar").empty();
$("#progressbar").html(data.percentage);
});
}
EDIT 3
var myInterval = setInterval(function(){ updates(); }, 1000);
function updates() {
$.getJSON("lib/getter.html", function (data) {
//$("#progressbar").empty();
console.log(data);
$("#progressbar").html(data.percentage);
if(data.percentage >= 100){
clearInterval(myInterval);
}
});
}
EDIT 4. changed getter.php
include("process.php");
//global $session_id;
//echo $session_id;
$readpercentage = $db->query("SELECT percentage FROM sessions WHERE session_id = '$session_id'");
$percentage = $readpercentage->fetch_assoc();
$percentage = (int) $percentage['percentage'];
if ($percentage = 100) {
$percentage = 100;
}
echo json_encode(array('percentage' => $percentage));
ob_flush();
flush();
and the js script
var jQuery_1_11_0 = $.noConflict(true);
jQuery_1_11_0('#check').on('submit', function (e) {
var myInterval = setInterval(function(){ updates(); }, 1000);
function updates() {
$.getJSON("lib/getter.html", function (data) {
var percentage = data.percentage;
$("#progressbar").html(percentage).show();
if(percentage >= 100 || typeof percentage !== 'undefined'){
clearInterval(myInterval);
}
});
}
});
// second script is for posting the result
jQuery_1_11_0('#check').on('submit', function (e) {
var validatef = $("#url").val();
var validaterror = $('#errorvalidate');
if (validatef == 'Enter Domains Separated By New Line -MAX 100 DOMAINS-') {
validaterror.text('Please enter domain names in the text area');
e.preventDefault();
} else {
validaterror.text('');
$.ajax({
type: 'post',
url: 'lib/process.php',
data: $('#check').serialize(),
success: function (data) {
$("#result").html(data); // apple
// $("#progressbar").knob().hide();
}
});
e.preventDefault();
} // ending the else
});
I cant help but wonder:
done();
function done() {
setTimeout(function () {
updates();
done();
}, 1000);
}
How does this recursion stops? Because to me it seems like this timeout will keep on firing eternally. You really need a timeInterval here, set it to a variable, and clear the interval when 100% has been reached.
Maybe replace the above with:
var myInterval = setInterval(function(){
updates();
}, 1000);
then, on the updates function
if(percentage >= 100){
clearInterval(myInterval);
}
By the way, doing:
if(percentage = null){
...
}
Did you mean to compare using = instead of == ? If you want to verify that percentage is set and is a valid number, it would probably be a good idea to do:
if(typeof percentage !== 'undefined' && !isNaN(parseFloat(percentage)){
...
}
Look at what you're sending back to your JS code from PHP:
echo json_encode(array('percentage' => $percentage));
Literally that'll be
{"percentage":42}
In your JS code, you then have:
$.getJSON("lib/getter.php", function (data) {
^^^^---the data coming back from PHP
....
$.each(data.result, function () {
^^^^^^---since when did you put a "result" key into your array?
For this JS code to work, you'd have to be doing
echo json_encode(array('result' => $percentage));
^^^^^^---note the new key.
And note that since you're sending back a SINGLE object in the JSON, with a single key:value pair, there is literally no point in using your inner $.each() loop. You could just as well have
$("#progressbar").html(data.percentage);
I have added an ajax loader to my code below. The problem is when the data from database is over, still the scroll function is going to an infinite loop and also the ajax scroll image is displayed. I want to stop the scroll function once the data is finished and also disable the ajax loader image. THis is my code
var counter=25;
$(window).on('scroll',function(){
if($(window).scrollTop()==($(document).height()-$(window).height())){
$('div#lastPostsLoader').html('<img src="loading-icon.gif">');
//Get older posts
$.ajax({
type: 'POST',
url: 'getdata.php?start_row=' + counter,
success: function(oldposts){
if(oldposts)
{
//Append #postsDiv
$('#data').append(oldposts);
counter += 15;
}
else
{
$('#lastPostsLoader').hide();
}
}
});
}
});
Try with this:
var counter = 25;
$(window).on('scroll', function () {
if ($(window).scrollTop() == ($(document).height() - $(window).height())) {
$(document).ajaxStart(function() {
$('div#lastPostsLoader').html('<img src="loading-icon.gif">');
});
$.ajax({
type: 'POST',
url: 'getdata.php?start_row=' + counter,
success: function (oldposts) {
if ($('#data')) {
$('#data').append(oldposts);
counter += 15;
}
}
});
$(document).ajaxComplete(function() {
$('div#lastPostsLoader').find('img[src^="loading"]').remove();
});
}
});
If i am not wrong, in the success function, if you get the data, you should hide the loader there itself. I am not getting what is the purpose of hiding the $('#lastPostsLoader') in the else part ???
From what I understand is that you are hiding the loader if you dont get any data.
#pavan
if ($('#data')) {
//if you have data process your business logic.
}
else
{
//Hide the loader.
//remove the event handler you can use .off for it.
}
For removing event handler http://api.jquery.com/off/
I've my site pages structure as
1) index.php which calls addline.php using ajax and the html returned is appended to the index.php
2) the addline.php calls another page more.php using ajax which again appends the returned html to it
3) Again more.php calls another file update.php and in the update.php, I've my following js codes
var number = parseInt("<?php echo $delFlag; ?>");
if ( number == 1) {
// Calling updateLine() function after 5 mins
timer = setTimeout("updateLine()",1000*5*60);
}
function updateLine() {
var flagId = <?php echo $flagId; ?>;
var dataPass = 'flagId=' + flagId;
$.ajax({
type: "POST",
url: "proc/updateLine.php",
data: dataPass,
cache: false,
success: function(){
// Show error if error is there
}
});
}
All the time, my location is still index.php.
The javascript function works properly if I do not reload the page. If I reload the page, it doesn't work. I want the setTimeOut() call to be active in the background even after the reload takes place. It should trigger the function call after 5 mins.
How do I achieve it??
Reloading a page resets the Javascript state and there is no direct way to keep things running in the background.
If the requirement is to continue the timeout counter automatically after the page reload, then the counter state has to be persisted somehow.
It means that every timeout start has to be accounted for. One option would be to do it with PHP and load and unload events, along the lines of:
// timeout.php -- persists and returns the last timeout start by session
<?php
session_start();
$key = 'lastTimeoutStart';
if (isset($_GET[$key]))
$_SESSION[$key] = $_GET[$key];
else if (isset($_SESSION[$key]))
echo $_SESSION[$key];
?>
Plus the Javascript part that handles persisting and loading:
var lastTimeoutStart = 0;
if ( number == 1) {
// Calling updateLine() function after 5 mins
lastTimeoutStart = new Date().getTime();
timer = setTimeout("updateLine()",1000*5*60);
}
//
// Other code
//
$(document).load(function () {
$.get('timeout.php', function (data, textStatus, jqXHR) {
var persistedStart = data.lastTimeoutStart;
var tempTimeout = persistedStart + 1000*5*60 - new Date().getTime();
if (tempTimeout > 0) {
clearTimeout(timer);
timer = setTimeout("updateLine()", tempTimeout);
}
});
});
$(document).unload(function () {
var data = {"lastTimeoutStart": lastTimeoutStart};
$.get('timeout.php', data, function (data, textStatus, jqXHR) {});
});
There may be bugs in the above code but hopefully you get the idea.