loaded content using ajax gets lost? - php

I am using AJAX to load content from mysql database when I CLICK on LINKS.
once I load the content successfully, I refresh the container every 5 seconds so the new content will be displayed.
the content gets loaded fine and the refresh part works fine too.
but the issue that I have is that when the refresh happens, the loaded content gets lost.
by "it gets lost" i mean that it will display the LAST result from the mysql database.
so, to help you understand the situation I will explain it further:
Lets say I have 3 results stored in mysql database.
I create <a></a> from each result in mysql using PHP. i am doing this without any issue.
I click on the link 2. (works fine)
the content of the link 2 will load on the page using AJAX. (works fine)
The container of content will refresh every 5 seconds. (works fine)
(THIS IS WHERE THE PROBLEM STARTS) once the refresh happens, the content of link 3 will be displayed even though I haven't clicked on the link 3!
so basically, for some strange reason, the content of the last Link or last mysql result will be displayed at all time which is un-wanted. I need to load the content of the CLICKED link and make it stay until another Link is clicked.
I hope I haven't confused you. :)
here is my html code:
<div id="chattercontent" style="width:90%; height:150px; resize:none; border:solid 1px #ccc; background:#F2EDF0; overflow:scroll; text-align:left;"></div>
<script type="text/javascript">
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "file.php?u_id=<?php echo $u_id; ?>",
dataType: "html", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
setTimeout(load, 5000)
}
});
}
load();
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".list-group-item").click(function(e) {
e.preventDefault();
$("#chattercontent").load(this.href);
return false;
});
});
</script>
and PHP code for the links:
while (mysqli_stmt_fetch($stmt)) {
$product_list .= "<a id='listc' class='list-group-item' href='file.php?u_id=".$u_id."' >".$u_id." ".$date_added." <img src='light-red-flash.gif' width='20' /></a>";
}
}
any help would be appreciated.
Thanks
edit:
this is the code for file.php
<?php
session_start();
if (isset($_GET['u_id'])) {
$u_id = $_GET['u_id'];
$sql = "SELECT * FROM chat WHERE u_id='$u_id' ";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$user_message = $row["user_message"];
}
} else {
echo "Sorry, there was an error.";
exit();
}
echo $user_message;
}
?>
as I mentioned before, the file.php returns the result properly according to the link that have been clicked on but then it will JUMP on the last result after each refresh!

You need to keep track of the current url the user has selected:
$(document).ready(function () {
//set url 1st time
var currentUrl = "file.php?u_id=<?php echo $u_id; ?>";
//variable to reference the timeout
var timer;
function load(url) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: url,
dataType: "html", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
timer = setTimeout(function(){
load(currentUrl);
}, 5000);
}
});
}
load(currentUrl);
$(".list-group-item").click(function(e) {
e.preventDefault();
//update url on click
currentUrl = this.href;
//cancel existing timer
clearTimeout(timer);
load(currentUrl);
});
});

You aren't loading your dynamic content with the javascript function. Check out the following, hope it will fix your problem.
function load(href) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: href,
//url: "file.php?u_id=<?php echo $u_id; ?>", <-- NON DYNAMIC CONTENT
dataType: "html", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
setTimeout(function() {
load(href);
}, 5000)
}
});
}
var _currentUrl;
function load(href) {
if (!href) {
href = _currentUrl;
}
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: href,
//url: "file.php?u_id=<?php echo $u_id; ?>", <-- NON DYNAMIC CONTENT
dataType: "html", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
setTimeout(load, 5000)
}
});
_currentUrl = href;
}

I am a bit confused. I would be glad if you would explain it a bit more with some examples.
Anyway from what I could get from your text is that, the previous result is being overwritten.
In order to stop that, as we do while making a chatbox, you need to add the response "after" the previous result as in -
<script type="text/javascript">
/* A variable to hold the last response */
var lastResponse = "";
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "file.php?u_id=<?php echo $u_id; ?>",
dataType: "html", //expect html to be returned
success: function (response) {
/* Check if it is the same response or not */
if (lastResponse != response)
{
/* Save the last response */
lastResponse = response;
/* Add content after the previous */
$("#chattercontent").html($("#chattercontent").html()+response);
}
setTimeout(load, 5000)
}
});
}
load();
});
</script>

Related

AJAX Load PHP Response

How can I load data from my PHP response via ajax into a panel?
My PHP outputs correctly and I can see a table in the response, but I can;t get it to build the data on my webpage.
Here is my jquery/ajax so far. It passed the value to PHP correctly and PHP builds the table via its echo, but what am I missing for AJAX to display the table?
PHP:
<?php
foreach ($lines as $value) {
echo "<input name='data[]' value='$value'><br/>";
}
?>
JQUERY:
$(function () {
$('#rotator').change(function (e) {
var rotator = $("#rotator").val();
$.ajax({
type: "POST",
url: "tmp/JFM/National/national.php",
data: {
rotator: rotator
},
success: function (result) {
$('#panel').load(result);
}
})
return false;
});
});
The answer to this was two fold.
I was attempting to append to my main div, which apparently can't happen. I created a new empty div and was able to load the results there.
Beyond that, the comments to change .load(results) to .html(results) were needed.
The correct jquery code is below.
$(function () {
$('#rotator').change(function (e) {
var rotator = $("#rotator").val();
$.ajax({
type: "POST",
url: "tmp/JFM/National/national.php",
data: {
rotator: rotator
},
success: function (result) {
console.log(result);
$('#test').html(result);
}
})
return false;
});
});
move your function from:
$.ajax({...,success: function(){...}});
to
$.ajax({..}).done(function(){...});
if it doesn't work, try to add async:false into the ajax object...
$.ajax({...,async:false}).done(function(){...});
Hope it helps... =}

I need to send my values using ajax twice first on page 1 then from that two page 2

I am trying to send my values using ajax from original page to the page one and then to page 2 this is my code but it seems to be not working.
This is the code on the original page here I have only given the script as I am just using the click event of my div to send the values
<script>
function displayRecords(numRecords, pageNum,x,catg) {
$.ajax({
type: "GET",
url: "button.php",
data: {
show:numRecords,
pagenum:pageNum,
val12:x,
catg12:catg,
},
cache: false,
success: function(data) {
$("#tabs1-html").html(data);
}
});
}
function changeDisplayRowCount(numRecords) {
displayRecords(numRecords, 1);
}
$(document).ready(function() {
$('.tab12').click(function(){
var catg=$('#cat').val();
var x =$(this).val();
displayRecords(5,1,x,catg);
});
});
</script>
now for the code on my page 1
here
<script type="text/javascript">
function get_data(no,x,catg) {
$.ajax({
type:'post',
url:'question_call.php',
data:{
row_no:no,
X:x,
category:catg,
},
success:function(response) {
document.getElementById("pagination_div").innerHTML=response;
}
});
}
$(document).ready(function() {
$('#tota_page_div').click(function(){
var catg = $category.val();
var x = $X.val();
get_data(no,x,catg);
});
});
</script>
and these are the values where i saved the previous ones
$X = $_GET['val12'];
$category = $_GET['catg12'];
Now when I try to use print_r on my page 2 it only shows row_no not catg12 and val12

Issue with using a value in JQuery/Javascript

I have a PHP populated table from Mysql and I am using JQuery to listen if a button is clicked and if clicked it will grab notes on the associated name that they clicked. It all works wonderful, there is just one problem. Sometimes when you click it and the dialog(JQuery UI) window opens, there in the text area there is nothing. If you are to click it again it will pop back up. So it seems sometimes, maybe the value is getting thrown out? I am not to sure and could use a hand.
Code:
$(document).ready(function () {
$(".NotesAccessor").click(function () {
notes_name = $(this).parent().parent().find(".user_table");
run();
});
});
function run(){
var url = '/pcg/popups/grabnotes.php';
showUrlInDialog(url);
sendUserfNotes();
}
function showUrlInDialog(url)
{
var tag = $("#dialog-container");
$.ajax({
url: url,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
function sendUserfNotes()
{
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text()
},
success: function(response) {
$('#notes_msg').text(response.the_notes)
}
});
}
function getNewnotes(){
new_notes = $('#notes_msg').val();
update(new_notes);
}
// if user updates notes
function update(new_notes)
{
$.ajax({
type: "POST",
//dataType: "json",
url: '/pcg/popups/updateNotes.php',
data:
{
'nameNotes': notes_name.text(),
'newNotes': new_notes
},
success: function(response) {
alert("Notes Updated.");
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
});
}
/******is user closes notes ******/
function closeNotes()
{
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
Let me know if you need anything else!
UPDATE:
The basic layout is
<div>
<div>
other stuff...
the table
</div>
</div>
Assuming that #notes_msg is located in #dialog-container, you would have to make sure that the actions happen in the correct order.
The best way to do that, is to wait for both ajax calls to finish and continue then. You can do that using the promises / jqXHR objects that the ajax calls return, see this section of the manual.
You code would look something like (you'd have to test it...):
function run(){
var url = '/pcg/popups/grabnotes.php';
var tag = $("#dialog-container");
var promise1 = showUrlInDialog(url);
var promise2 = sendUserfNotes();
$.when(promise1, promise2).done(function(data1, data2) {
// do something with the data returned from both functions:
// check to see what data1 and data2 contain, possibly the content is found
// in data1[2].responseText and data2[2].responseText
// stuff from first ajax call
tag.html(data1).dialog({
width: '100%',
modal: true
}).dialog('open');
// stuff from second ajax call, will not fail because we just added the correct html
$('#notes_msg').text(data2.the_notes)
});
}
The functions you are calling, should just return the result of the ajax call and do not do anything else:
function showUrlInDialog(url)
{
return $.ajax({
url: url
});
}
function sendUserfNotes()
{
return $.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data: {
'nameNotes': notes_name.text()
}
});
}
It's hard to tell from this, especially without the mark up, but both showUrlInDialog and sendUserfNotes are asynchronous actions. If showUrlInDialog finished after sendUserfNotes, then showUrlInDialog overwrites the contents of the dialog container with the data returned. This may or may not overwrite what sendUserfNotes put inside #notes_msg - depending on how the markup is laid out. If that is the case, then it would explains why the notes sometimes do not appear, seemingly randomly. It's a race condition.
There are several ways you can chain your ajax calls to keep sendUserOfNotes() from completing before ShowUrlInDialog(). Try using .ajaxComplete()
jQuery.ajaxComplete
Another ajax chaining technique you can use is to put the next call in the return of the first. The following snippet should get you on track:
function ShowUrlInDialog(url){
$.get(url,function(data){
tag.html(data).dialog({width: '100%',modal: true}).dialog('open');
sendUserOfNotes();
});
}
function sendUserOfNotes(){
$.post('/pcg/popups/getNotes.php',{'nameNotes': notes_name.text()},function(response){
$('#notes_msg').text(response.the_notes)
},"json");
}
James has it right. ShowUrlInDialog() sets the dialog's html and sendUserOfNotes() changes an element's content within the dialog. Everytime sendUserOfNotes() comes back first ShowUrlInDialog() wipes out the notes. The promise example by jeroen should work too.

ajax like/unlike button not switching back

I am trying to make a like button on a page and cant seem to get it to work right. Basically there are three function that use ajax to send the data to a php page that updates the database. Ive checked the db and all three update correctly. If the user doesnt originally like and clicks, it correctly shows the unlike button but then, if you click unlike it doesnt switch back (although it does update the database).
Is this the correct way to set this up? Im pretty new to ajax and am not sure if this is the right approach. THanks in advance
Steve
public function likesScript($p){?>
<script>
//display list of people who like this
function getLikes(){
$.ajax({
type: "POST",
url: "likelist.php",
data: { p: "<?php echo $_GET['p']?>"}
}).success(function(res) {
//check to see if current user likes this
if($('li#<?PHP echo $_SESSION['userId']; ?>').length){
$(".Like").addClass('hidden');
$(".UnLike").removeClass('hidden');
}
else{
$(".UnLike").addClass('hidden');
$(".Like").removeClass('hidden');
}
$("#likedBy").append(res);
console.log(res);
});
}
function removeLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "0" }
})
getLikes();
return false;
}
function addLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" }
})
getLikes();
return false;
}
$(document).ready(function() { getLikes();
$(".UnLike").live('click',removeLike);
$(".Like").live('click',addLike);
});
</script>
likelist.php:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/view.class.php';
$view = new view();
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';
$profile = new profile($dbh);
if(isset($_POST)){
$p = $_POST['p'];
$view->printLikes($profile->getLikes($p));
}
likedata.php:
<?php
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';
$profile = new profile($dbh);
if(isset($_POST)){
$liker = $_POST['arg1'];
$likee = $_POST['arg2'];
$likeYesNo = $_POST['arg3'];
$profile->insertLikes($liker, $likee, $likeYesNo);
}
?>
AJAX is ayshcronous so the getLikes functions will fire before the AJAX is completed in both addLike and removeLike. You definitely need to put getLikes into the success callback of $.ajax so it doesn't retrieve data that may not have been updated
function addLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" },
success: getLikes
})
}
Ok... this is what I have learned from using ajax repeat calls...
IE hates them and sometimes they just don't work the way they should.
Try this
function addLike() {
var randnum = Math.floor(Math.random()*1001); //Add This Here on all Ajax Calls
$.ajax({
type: "POST",
url: "likedata.php",
cache: false, //Add This Here - Assists in helping Browsers not to cache the Ajax call
data: yourdata + '&random=' + randnum, // Add this to the end of your data you are passing along *'&random=' + randnum,*
success: function() {
getLikes();
}
})
}
Adding a random piece of data causes the browsers to think its a new call.
Also, the random=randnum wont effect anything on the php side.

JQuery: How to apply this click function to all elements of the same class on the page?

My page consists of a list of records retrieved from a database and when you click on certain span elements it updates the database but at present this only works for the first record to be displayed.
(Basically changes a 0 to 1 and vice versa)
These are my two html elements on the page that are echoed out inside a loop:
Featured:<span class="featured-value">'.$featured.'</span>
Visible:<span class="visible-value">'.$visible.'</span>
Here is what I have:
$(document).ready(function() {
$('.featured-value').click(function() {
var id = $('.id-value').text();
var featured = $('.featured-value').text();
$('.featured-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$('.featured-value').html(data);
$('.featured-value').fadeIn('slow');
}
});
return false;
});
// same function for a different span
$('.visible-value').click(function() {
var id = $('.id-value').text();
var visible = $('.visible-value').text();
$('.visible-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&visible="+visible,
success: function(data) {
$('.visible-value').html(data);
$('.visible-value').fadeIn('slow');
}
});
return false;
});
});
It was working fine with one using id attributes but now I'm using class the fadeIn part of the success query isn't working but I'm hoping the .each will fix this.
UPDATE
The full loop is as follows:
while ($event = $db->get_row($events, $type = 'MYSQL_ASSOC'))
{
// open event class
echo '<div class="event">';
echo '<div class="id"><span class="row">Event ID:</span><span class="id-value"> '.$id.'</span></div>';
echo '<div class="featured"><span class="row">Featured: </span><span class="featured-value">'.$featured.'</span></div>';
echo '<div class="visible"><span class="row">Visible: </span><span class="visible-value">'.$visible.'</span></div>';
echo '</div>';
}
Cymen is right about the id selector causing you trouble. Also, I decided to refactor that for you. Might need some tweaks, but doesn't everything?
function postAndFade($node, post_key) {
var id = $node.parents('.id').find('.id-value').text();
var post_val = $node.text();
$node.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&"+post_key+"="+post_val,
success: function(data) {
$node.html(data);
$node.fadeIn('slow');
}
});
return false;
}
$('.featured-value').click(function() { return postAndFade($(this), 'featured'); });
$('.visible-value').click(function() { return postAndFade($(this), 'visible'); });
The click function is getting the same id and value on each click because you've bound it to the class. Instead, you can take advantage of event.target assuming these values are on the item being clicked. If not, you need to use event.target and navigate to the items within the row.
$('.featured-value').click(function(event) {
var $target = $(event.target);
var id = $target.attr('id');
var featured = $target.text();
$target.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$target.html(data).fadeIn('slow');
}
});
return false;
});
So something like that but it likely won't work as it needs to be customized to your HTML.

Categories