Retrieve comments on runtime? - javascript

I want to call Ajax which fetches all the comments from database.
Now how to put a check on that Ajax Script to Run, when only someone comments.
Same as the stackoverflow notifications. When we comment on question, The Notification appears without reloading page (i.e On Runtime ).
Right now I am Running the same Ajax Script after each 10 seconds again and again, when I think is a bad way .So Here is my working Ajax Code:
$(document).ready(function(){
setInterval(function(){
$.ajax({
type: "GET",
url: "ajax_files/reload_notifications.php"
}).done(function(result) {
var $notifications = $('#notification_area');
if ($notifications.length > 0) {
$notifications.html(result);
}
});
}, 10000);
});

When a comment is entered, do a similar AJAX request that will save the comment and on it's success callback, call another function which will also hit another AJAX request which fetches the comments. For e.g.
function insertComment() {
$.ajax({
type: "GET",
url: "ajax_files/insert_comment.php"
}).done(function(result) {
fetchComments();
}
});
}
function fetchComments() {
$.ajax({
type: "GET",
url: "ajax_files/reload_notifications.php"
}).done(function(result) {
var $notifications = $('#notification_area');
if ($notifications.length > 0) {
$notifications.html(result);
}
});
}
Hope this helps!

Related

If statement in jQuery and HTML?

I m running the following script with success : it updates the text every 3s
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(function() {
window.setInterval(function() {
loadNewText()
}, 3000)
function loadNewText() {
$.ajax({
url: "/update_report",
type: "POST",
dataType: "json",
success: function(data) {
$(report).replaceWith(data)
}
});
}
});
</script>
I want to change the function in HTML to run 'loadNewText()' only if there's changes in certain variable in Python code !
I've put the variables in python route :
#app.route('/console-output')
def console_output():
fileHandle = open("console_output.txt", "r")
lineList = fileHandle.readlines()
fileHandle.close()
last= lineList[len(lineList)-1]
with open('console_output.txt', 'r') as r:
co =r.read()
return render_template("console-output.html",console_output_msg=console_output_msg, last=last, co=co)
and write the following code in HTML :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(function() {
if (last != console_output_msg) {
loadNewText();
}
function loadNewText() {
$.ajax({
url: "/update_text",
type: "POST",
dataType: "json",
success: function(data) {
$(new_text).replaceWith(data)
}
});
}
});
</script>
This method is not working ! I don't have a big experience with Javascript! I don't know if I m not calling the variables (last, console_output_msg) the right way or my function is not valide !
If there's any way to correct it or any other suggestion to call 'loadNewText()' when changes happens in python code !
Thanks!
There are 2 popular ways to update the text when there is a change in Python:
Long polling
Using setInterval() function to trigger an ajax call to the server to check if there are any changes.
WebSocket
Implement a WebSocket connection between the server and browser. Receive the message sent from the server.
Link for implement WebSocket in Python.
https://websockets.readthedocs.io/en/8.1/intro.html
You can't access server variables on the client.
You could save the previous output in a JavaScript variable, and only update the DOM if it has changed. You need to put the if statement inside the loadNewText() function, after it has received the response, so it can compare it.
This won't skip the AJAX call, but it will avoid refreshing the page when nothing has changed.
$(function() {
let last_output;
window.setInterval(loadNewText, 3000)
function loadNewText() {
$.ajax({
url: "/update_report",
type: "POST",
dataType: "json",
success: function(data) {
if (data != last_output) {
$(report).replaceWith(data);
last_output = data;
}
}
});
}
});

Calling ajax request continually until a certain search request is found

I am trying to keep sending AJAX GET requests to a certain page that inputs from a cgi script until a specific set of keystrokes shows up.
However, my requests aren't coming up continuously, in fact they aren't even taking place when I am using a function and trying to call the function. I had to use the complete with the success, because for whatever reason, with the success I could not properly store the value retrieved.
Here is what I have:
function posts() {
$.ajax({
type: "GET",
url: 'http://checkvaluestatus.sh',
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
if (version != null) {
console.log(version);
} else {
posts();
}
},
error: function() {
console.log('failed');
posts(); //calling the ajax again.
}
});
Is there not a way to keep sending requests based on a condition being met and having the value still stored?
This is my AJAX call that worked to print the value:
$.ajax({
url: 'http://checkvaluestatus.sh',
type: "GET",
dataType: "json",
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
document.write(version);
},
});
salam,
the value you are looking for in success function is the 'data' ,not "data_response.responseText" because in "success" function data is your response text ,but in the "complete" function "data_response" is a jqXHR object contain more information.
to print your text in success function replace
alert(data_response.responseText);
by
alert(data);
for more details "jquery.ajax"

Ajax link to run codeigniter controller then update html

Sorry for the most simplest of questions but I can't seem to get anything to work. It's the first time I've really played around with AJAX.
I'm developing in codeigniter and I have a link that when clicked runs the controller: photo function: like and allows the logged in user to like the photo then redirects the user back to the photo and displays a slightly different version of the button showing that the user likes the photo.
<?php if ( $like_count > '0' ) { echo $like_count; } ?>
It works fine but I thought it would be cool to replace it with an ajax function so it's more of a fluid motion instead of navigating off the page and then back again.
Any help would be greatly appreciated.
$(".uk-button").click(function(e) {
e.preventDefault();
//Here you can add your ajax
$.ajax({
url: site_url + 'photo/like',
data: {
liked : 1
},
type: 'POST',
dataType: 'json',
async : false,
success: function(success_record) {
console.log(success_record,":success_record");
//You might receive your like count from PHP here
}
});
});
In your success record you would get your PHP record values. Based on that you can increment or decrement count in success function
You can do something like this:
$(document).ready(function()
{
$('.likeLink').on('click', funciton()
{
var obj = $(this);
var id = obj.attr('id'); //anything you want to pass to update your like somewhere
$.ajax(
{
type: 'POST',
url: 'YourFilePathWhereYouWillDoTheLike',
data:
{
id: id,
},
cache: false,
success: function(response)
{
obj.html("You have liked this!");
}
});
return false;
})
})

How do you repeatedly make an ajax request with jquery?

I have the following ajax request that runs when the page is loaded
var city_id = $(".feed-selected-city").attr('id');
$("#cityfeed").html("<div class='feed-loading'>The feed is loading ...</div>");
var ajaxOpts = {
type: "get",
url: "ajax_getcityfeed.php",
dataType: 'json',
data: "&city=" + city_id,
success: function(data) {
$('#cityfeed').html(data.data);
}
};
$.ajax(ajaxOpts);
How can I run this piece of code every 10 seconds after that?
Wrap it in a function, and use setTimeout to continuously call the function.
function tick() {
var city_id = $(".feed-selected-city").attr('id');
$("#cityfeed").html("<div class='feed-loading'>The feed is loading ...</div>");
var ajaxOpts = {
type: "get",
url: "ajax_getcityfeed.php",
dataType: 'json',
data: "&city=" + city_id,
success: function(data) {
$('#cityfeed').html(data.data);
}
};
$.ajax(ajaxOpts);
setTimeout('tick()',10000);
}
$(document).ready(function() {
tick();
}
#Yegor
Wrap the above function using a name. Then use setTimeout(function(){//call the function here},10000); -
I would suggest you not to make this kind of implementation. Make some alternative.
Use a infinite loop with setTimeout. And put that inside.
Though I don't recommend this to achieve what you're trying todo. I think what you require is some kind of polling; this will probably kill your server if there's a high amount of simultaneous users; since each visitor will send a http request every 10 seconds.
function timedCount()
{
console.log('Hello');
setTimeout("timedCount()",10000);
}
timedCount();

How do I reload the page after all ajax calls complete?

The first time a user is visiting my website, I am pulling a lot of information from various sources using a couple of ajax calls. How do I reload the page once the ajax calls are done?
if(userVisit != 1) {
// First time visitor
populateData();
}
function populateData() {
$.ajax({
url: "server.php",
data: "action=prepare&myid=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
_id = response[json].id;
getInformation(_id);
}
});
}
function getInformation(id) {
$.ajax({
url: "REMOTESERVICE",
data: "action=get&id=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
$.ajax({
url: "server.php",
data: "action=update&myid=" + id + '&data=' + json.data.toString(),
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
}
});
}
});
}
So what the code does is, it gets a list of predefined identifiers for a new user (populateData function) and uses them to get more information from a thirdparty service (getInformation function). This getInformation function queries a third party server and once the server returns some data, it sends that data to my server through another ajax call. Now what I need is a way to figure out when all the ajax calls have been completed so that I can reload the page. Any suggestions?
In your getInformation() call you can call location.reload() in your success callback, like this:
success: function(json) {
if(!json.error) location.reload(true);
}
To wait until any further ajax calls complete, you can use the ajaxStop event, like this:
success: function(json) {
if(json.error) return;
//fire off other ajax calls
$(document).ajaxStop(function() { location.reload(true); });
}
.ajaxStop() works fine to me, page is reloaded after all ajax calls.
You can use as the following example :
$( document ).ajaxStop(function() {
window.location = window.location;
});
How it's works?
A: Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event.
Hope help y'all, furthermore information, I'm sharing the link of the documentation following.
source: https://api.jquery.com/ajaxstop/
You could just redirect to the same page in the server.php file where the function is defined using a header('Location: html-page');
//document.location.reload(true);
window.location = window.location;
See more at: http://www.dotnetfunda.com/forums/show/17887/issue-in-ie-11-when-i-try-to-refresh-my-parent-page-from-the-popupwind#sthash.gZEB8QV0.dpuf

Categories

Resources