jquery addclass keeps reseting inside setinterval - php

I have an HTML DIV which is updated by ajax function using setinterval. What I'm trying to do is addclass to the result of ajax. But when setinterval the addedclass is reset and displays the initial class. how to solve this issue.
<html>
<body>
<div id="something"></div>
<script>
$(document).ready(function(){
var id;
setInterval(function(){
somepage();
addactiveclass();
}, 5000);
function somepage(){
$.ajax({
url:"fetchcontents.php",
method:"POST",
success:function(data){
$('#something').html(data);
}
})
}
function addactiveclass(){
$('#list-'+id).addClass("active");
}
// UPDATED
$(document).on('click', '.mycontents', function(){
id = $(this).data('id');
$('#list-'+id).addClass("active");
}
});
</script>
</body>
</html>
UPDATE: fetchcontents.php
<?php
$output .= '<div class="list-item mycontents" data-id="'.$row['id'].'" data-name="'.$row['username'].'" id="list-'.$row['id'].'">';
//.... some php function to generate some contents inside the above div.....
// Contents do not interfere with this question.
$output .= '</div>';
echo $output;
?>
What happens is the active clas is not added to the div id="list-'.$row['id'].'". As you know setinterval keeps on executing ajax function after 5sec and the active class is reset and not displayed.
Could anyone please guide me to accomplish this issue.
Thanks in advance.

I just ran your code in jsfiddle, but replaced the ajax with a string defining a new div as contents of #something, and it works.
However it did require me to put the js inside a $(document).ready block
$(document).ready(function() {
//your js in here
})
Try that. What this does is not define the js until all the HTML is rendered. My guess is that you were referencing #something before it existed.
EDIT:=============================================
You have changed your code considerably since my answer was written, but to backup my claim to have a solution to what I believe was your question, I have re-done my jsfiddle test: https://jsfiddle.net/uf5h0sgw/
<html>
<body>
<div id="something">AAAA</div>
<script>
$(document).ready(function(){
var id;
var cnum = 1;
setInterval(function(){
somepage();
addactiveclass();
}, 1000);
function somepage(){
$('#something').html('<div class="abc">BBBB</div>');
/*$.ajax({
url:"fetchcontents.php",
method:"POST",
success:function(data){
$('#something').html(data);
}
})*/
}
function addactiveclass(){
/*$('#list-'+id).addClass("active"); */
$('#something div').addClass("active" + cnum++)
}
});
</script>
</body>
</html>
I cannot reproduce your ajax response, so I have just added some code to insert a DIV into #something every time the interval expires (reduced to 1000ms for the test).
Then the function addactiveclass() changes the class of the Div that has been added. I change the class name on a counter each loop so you can see that the class is updated every time around.
You will obviously have to adapt my code to handle what ever content your AKAX adds, but the approach should achieve what I think you want.

Related

How to load php instantly from ajax?

I am trying to directly load a page using ajax. Here are the details:
HTML:
<div id="feedback"> </div>
<script type="text/javascript" src="script.js"></script>
script.js:
$(document).ready(function() {
$.ajax({
url: 'do.php',
success: function(data){
$('#feedback').html(data);
});
});
do.php:
<?php
//Do whatever...
echo "Done!";
?>
What I am seeing is: the page first loads, and there is a delay before the "feedback" div gets written. How can I solve this?
As far as I know of course it will have that delay. Suppose your page containing <div id="feedback">[…]</div> is loaded at 0th second now:
$(document).ready(function() {
$.ajax({
url: 'do.php',
success: function(data){
$('#feedback').html(data);
});
});
Is called as apparently it’s visible when document loads. So suppose its called at 3rd second when the document is ready—you can refer to this page for details—now you will be seeing that feedback div blank for 3 seconds.
I can suggest 2 things:
You can place a loader image by default inside the div so your code will change to <div id="feedback"><img src='loader.gif'></div> (Assume you have the loader.gif in the same directory of the page). By doing this you will make the user visually understand that some processing is going on and will load data.
Instead if you can place file_get_contents() or include() so it will look something like this <div id="feedback"><?php file_get_contents('do.php');?></div> or <div id="feedback"><?php include('do.php');?></div> As far as I know file_get_contents will execute the page and then load while include will load and then execute hence in include() you have the variables in the page available whereas in file_get_contents are not available but CSS would work in both cases.
You could start loading immediately and then add the data when everything has completed.
var _data = null;
var _ready = false;
$.ajax({
url: 'do.php',
success: function(data){
_data = data;
tryAddData();
}
});
$(document).ready(function() {
_ready = true;
tryAddData();
});
function tryAddData(){
if(_ready && _data !== null){
$('#feedback').html(_data);
}
}

refresh div with new data as if it was a page refresh

Is it possible using jQuery to literally refresh a div?
Nothing like submitting a form or anything like that.
I have a data stream which is updated else where and all I want to do is refresh the div and all its contents as if it were a page refresh. I can't link to that page to make a return that populates as the only output is just raw data.
The div itself contains all the data display processing. Nothing needs to be fetched as the data is already there.
you have to use setinterval with ajax function,
$(document).ready(function(){
setInterval(function(){ refreshDiv(); }, someInterval);
});
function refreshDiv(){
$.ajax({
url: "http://yourrequestpath",
.....
});
}
<div id="data"></div>
<script>
$('#div').load("loaddata.php", function() {
window.setInterval("loadData", 60000);
});
function loadData()
{
$('#div').load("loaddata.php");
}
</script>

Global variable inside Ajax function

I'm learning the Ajax method with jQuery. I've a simple code here. It's to load data from a csv file by jQuery Ajax method, and put it into an array for further use. But it seems the array lost outside of the Ajax function even I do make the array global in the first place.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var db=[];
$(document).ready(function(){
$.ajax({
url: 'loaddata.php',
success: function(data){
var arr = data.split('|');
for(var i=0; i<arr.length; i++){
var miniArr = arr[i].split(',');
db.push(miniArr);
}
printTest(); //work here
}
});
printTest(); //not working and collapse here
});
function printTest(){
document.getElementById('test').innerHTML += db;
}
</script>
</head>
<body>
<div id="test" />
</body>
</html> `
My php file should be fine,
<?php
$database = file('database');
foreach($database as $item){
if ($item===end($database))
echo $item;
else
echo $item.'|';
}
?>
Thanks in advance.
Your second printTest() is where the .ajax parameters go, so there's a syntax error there. The reason the first call works is because it's inside the success callback, and since AJAX is asynchronous this is called when the call has completed.
If you put the printTest() call after the AJAX call, it will be called immediately after the AJAX call has started, not waiting until it completes, due to async.
You can't call your second printTest() here.
And for the record, try to use JSON to retrieve your datas, it's way much easier.

How to pass php variables to jquery AJAX?

I have started learning jquery AJAX. I have run into a problem, and was wondering if you guys could help me. I am trying to pass a php variable back to jquery, but it displays as [object Object]. I will be posting my code below.
index.html:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function() {
$("p").text($.get("return.php"));
});
});
</script>
</head>
<body>
<p>This is a test!</p>
<button>Click Here</button>
</body>
</html>
return.php:
<?php
$message = "Another test!";
echo $message;
?>
So what is it that I need to do to pass php variable $message into the paragraph using jquery ajax?
I know I could simply do if I changed index.html to index.php, but then if $message later changes, I have to reload the page. I am trying to learn how to make dynamic content without having to reload the page.
Thanks ahead of time for any help you provide! :-)
You'll have to wait until the data is returned before you can use it:
$(document).ready(function(){
$("button").click(function() {
$.get("return.php", function(data) {
$("p").text(data);
});
});
});
Add a callback to get.
$.get("return.php", function(data) {
$("p").text(data);
});
You can use callback function in .get function.
$(document).ready(function(){
$("button").click(function() {
$.get("return.php",function(data){
$("p").text(data);
});
});
});
Here you can pass the datatype as well in which form you want the response from server.
Suppose you want to return anyother datatype(i.e. json)from server, just use datatype with it like this :
$(document).ready(function(){
$("button").click(function() {
$.get("return.php",function(data){
$("p").text(data);
},"json");
});
});
For more detail,refer : http://api.jquery.com/jQuery.get/

How can I use jQuery effects on Ajax loaded content?

Hi and thanks for taking some time to look at my question. I have a part of the page where content is dynamicly loaded into from another file. Reason for this is it needs to be live updated. Now I want to be able to apply jquery effects that are usually used for show/hiding content (slide, fade etc) to animate the difference between the current data and the new data. This is the code used to get the content and load it into the div:
function k() {
$.post("../includes/ajaxAgenda.php", {
limit : value
}, function(data) {
$('#tab-agenda').html(data);
});
};
$(document).ready(function() {
k();
$('#tab-agenda').scroll(function() {
loadMore();
});
});
var refreshId = setInterval(function() {
k();
}, 1000);
So I guess my question is how do I animate what gets loaded in so it doesn't just "pop" from one content to another?
edit: I tried using the .live instead of .scroll but it doesn't seem to work:
$(document).ready(function() {
$('#tab-agenda').live("scroll",function() {
alert("hi");
loadMore();
});
});
You need to use live function of jquery to bind the dynamically added elements.
Ref: http://api.jquery.com/live/
Try this :
$('#tab-agenda').live("scroll",function() {
loadMore();
});
I suggest you to add the ajax loader image with proper css over the content/ div as like below.
function loadmore(){
$("#loader").css('display','block');
//your
//code
//here
$("#loader").css('display','none');
}
html
<img id="loader" src="ajax-loader.gif" style="display:none" />
<div id="content">
your cont to display
</div>

Categories