how i can repeat code from line x to y in php By Ajax.
for example:
mycode:
$info_2=('<div id="infobox">');
echo $chat_2;
$info_query=mysql_query("SELECT * FROM info WHERE fuid='$uid' or luid='$uid' ");
$info_num=mysql_num_rows($info_query);
for($i=0;$i<$info_num;$i++)
{
$info_fetch=mysql_fetch_array($info_query);
echo($info_fetch['username'].':'.$info_fetch['text'].'<br>');
}
$info_3=('');
echo $info_3;
now i need repeat this code every x second.
One way you can resolve this, is by executing setInterval with an Ajax call.
Somethine like :
<div id="my_container">
</div>
<script>
$(function(){loadContent()}); // first time load content
setInterval(loadContent, 2000); // every 2 seconds (2000 millis)
function loadContent()
{
$.ajax({ url:'/my_content.php',
success(result):{$("#my_container).html(result)},
error(result):{console.log(result.responseText)}})
}
</script>
However, I don't like settings intervals because it does not take into account the server time.
So this is how I would do it (pseudo code):
<div id="my_container">
<!-- include content from 'my_content.php' -->
</div>
Now for "my_content.php".
<!--- some HTML content -->....
<script>
setTimeout(function(){$.ajax({ url:'/my_content.php',
success:function(result){ $("#my_container").html(result);},
error:function(result){ console.log(result.responseText);}
}})},2000) // 2 seconds since last result
</script>
This way this piece of code is "self contained" and only requires it to be wrapped with "my_container" element.
Related
I'm trying to get the first link of each page using $('.yuRUbf a')[0].href;, however, this code gets the data of all pages, and then prints the link of the first page multiple times.
What am I doing wrong?
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<?php
function pageNum($pageNum) {
include $pageNum.".html";
?>
<script>
$(document).ready(function(){
const el = $('.yuRUbf a')[0].href;
console.log(el);
});
</script>
<?php
}
pageNum("1");
pageNum("2");
?>
EDIT:
Let me explain in another way: I have 5 html pages, each html page includes 10 links, I want the first link of each html page.
So I used the jQuery script to extract the href attribute value which is the link, however, instead of extracting the first link of each page, it is extracting the first link of the first page 5 times as I have 5 files.
Given that the existing code returns links for all pages, I'll assume that each "page" contains something similar to
<div class='yuRUbf'>
...
<div>
In this case, you can collate all the first links into an array using a single call at the end (ie not inside the pageNum loop)
var links = $(".yuRUbf").map((i,e) => $(e).find("a")[0].href).toArray()
(if you're passing this to something else, eg links.addClass("active") then don't use the .toArray())
this is the equivalent of, if you prefer/need a loop rather than an array:
$(".yuRUbf").each(function(i, e) {
var el = $(this).find("a")[0].href;
console.log(el);
});
Example:
$(function() {
const first_links = $(".yuRUbf").map((i,e)=>$(e).find("a")[0].href).get();
console.log(first_links)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='yuRUbf'>
<div>
<a href='l1'>l1</a>
</div>
<a href='l2'>l2></a>
<a href='l2'>l2</a>
</div>
<div class='yuRUbf'>
<div>
<a href='l12'>l12</a>
</div>
<a href='l22'>l22></a>
<a href='l22'>l22</a>
</div>
I have search on stackover-flow about my question, but could not get a suiting answer. I have boxes generated by a loop from my back end code. this boxes a to be destroy after a countdown on the individual boxes. The time frame is supplied along side with the content of the boxes form the back end. Now depending on result from my back end code the boxes can be 10 or a million as the case may be. So i ran a jquery countdown timer on each of them in the loop. the problem there is that the countdown of the first box is used on all the rest boxes, so when the timer of the first comes to an end the destruction commands affect all the boxes.
below is an example of what am doing using laravel blade syntax.
#forelse($boxe_deatails as $box_detail)
<div class="box-v2-detail-o">
<div class="col-md-16 col-xs-6 pull-right" style="background: rgba(110, 151, 170, 0.57);min-width: 100%;min-height: 73px;float: right;padding: 10px;font-size: small;line-height: 2em;margin: 5px;">
Timer to Run
<div id="timer">
#include('partials/count-timer')
</div>
</div>
<img style="width: 60px;height: 60px;border: 3px solid #fff;" src="{{asset('asset/img/avatar.jpg')}}" class="img-responsive"/>
<h4>Name {{$box_detail->name}} </h4>
<big>Size {{ $box_detail->size}} </big>
</div>
#empty
hello Empty
#endforelse
Now that is the loop. those data where gotten from my database.
count-timer file am using jquery.countdown-2.2.0
so all i have to do is select the targeted dom element and run the timer animation on it.
<script type="text/javascript">
$('body').find("div#timer").countdown('{{$box_detail->created_at->addHours(13)}}', {elapse:true}).on('update.countdown', function(event) {
$(this).text(event.strftime('%H Hr(s) : %M Min(s) : %S Sec(s)'));
if (event.elapsed) {
$.ajax({
url : '{{url('/timer-delete-box/'.$box_detail->id)}}',
method : 'get',
success : function(response)
{
alertify.notify('You did not make your payment before time. So your account has been pause', 'error', 9)
}
})
}
});
</script>
so now the problem again is that the count down for the first box is use on all the boxes even when there timer are different i want the timer to run on each boxes. again the timer function for the first one is repeated on all the boxes whereas the time from the loop are different. When you view it you see a uniform time which is very wrong. Please someone should help me fix it .
Now i know the problem is that the function is running just once so how do call it multiple times base on the loop count.
I think if Implement the answer to your question it should look as this.
$('div#timer').each(function() {
var $this = $(this),
finalDate = '{{$box_detail->created_at->addHours(13)}}';
$this.countdown(finalDate, {elapse:true}).on('update.countdown', function(event) {
$this.text(event.strftime('%H Hr(s) : %M Min(s) : %S Sec(s)'));
if (event.elapsed) {
$.ajax({
url : '{{url('/time-pause-account/'.$Topay->id)}}',
method : 'get',
success : function(response)
{
alertify.notify('You did not make your payment before time. So your account has been pause', 'error', 9, function(){
$('body').css({
'opacity' : '0',
'transition' : 'all 1s'
})
$('body').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
window.location = 'home'
})
})
}
})
}
});
});
I have found the solution to the problem what i have to do is use the each j-query loop for the boxes. which i did initially before asking this question however i was concatenating the countdown to the each function until i saw the documentation of the countdown timer for multiple instance. they still use the each loop but however did not concatenate the countdown obj to it. Link to the answer of my question
I have a class which gets a result from the database and the result is being looped through, and the database is being updated regularly but i dont want to keep refreshing the page because of some reasons.
//file class.php
class order {
function getOrders(){
//gets data from database
}
}
//file main.php
$ai = new order();
$orders = $ai->getOrders();
foreach($orders AS $order){
//data displayed in a table
}
I want the table to be automatically updated without page reload.
I know i have to use ajax but i have no idea what to implement that in oop
Use something like this.
$(function () {
setInterval(function () {
$("#liveTable").load("path/to/orderList");
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="liveTable"></div>
You need to use javascript and jQuery on your html page so as to reload a portion of the page.
you can add the following in your html page's head:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function()
{
theIntervalHandle = setInterval(fetchNewOrders,3000);
});
function fetchNewOrders()
{
$('#ordersDiv').load('http://your.web.address/class.php');
}
</script>
and that
<div id="ordersDiv"></div>
inside your html file's body where you want the dynamic content to appear.
this assumes that the file that creates the output is called class.php and fetches data each 3 seconds as per second is quite often and can cause problems should your traffic increase beyond a few tens of users...
I would like to make a while loop which executes and echos out the values between 1 and 90, each being 1 second apart. However, instead of them all being written in a row, I'd just like it to increase the one echoed value, if that makes sense. It's supposed to be for a football game and is basically a timer. I am not too sure on how to do it so any assistance would be greatly appreciated!
Thanks!
You will hang the PHP engine for a minute and a half if you use PHP for the counter. The result that is shown to the user is a page with the number 90 that took 90 seconds to load. What you need is javascript to increase the values of a text span after a second.
In PHP, echo just the first number, and use JS to increment every second.
<?php
echo '<head>
<script type="text/javascript">
function advance() {
var txt = parseInt(document.getElementById("timertext").innerHTML);
document.getElementById("timertext").innerHTML = txt + 1;
if(txt != 89) {
setTimeout("advance()", 1000);
}
}
</script>
<head>
<body onload="advance()">
<span id="timertext">1</span>
</body>';
?>
The thing is, I can do both, but I can't make them work immediately one after another, it does the first in the 1st clock, and the second in the 2nd clock. I've also tried with 1 div inside another but it's the same. Here's the code:
the script:
$(document).ready(function() {
$("#chatRoomSub").load("chatUpdate.php");
refreshId = setInterval(function() {
$("#chatRoomSub").load('chatUpdate.php');
var object = document.getElementById('chatRoom');
object.scrollTop = object.scrollHeight;
}, 5000);
$.ajaxSetup({ cache: false });
});
the body:
<div class='chatRoom' id="chatRoom">
<div class='chatRoomSub' id="chatRoomSub">
ainda nada foi escrito...
</div>
</div>
You need to use a callback function on the .load() which does the scrolling.
$("#chatRoomSub").load("chatUpdate.php", function() {
// scroll down
});
This way, the scrolling will occur immediately after the content is loaded.
You need to use call back function of jquery. Call back function is something that executes after event if i take an example .load("You code",function())..after loading your code, it will execute "code", it will execute function...