javascript get file contents - javascript

I would like to know it there is something in JavaScript that loads the contents of a given file. For example, I have a file called timer.php which on certain conditions it prints either a 1 or a 0 and I need JavaScript to read it and use it as a variable in order to execute a function.
So something like:
function dothis() {
var timer = getfilecontents(timer.php);
if(timer == 1) {
somefunction();
}
}
And thats pretty much it. What can I do?

try again AJAX
dothis
<script>
function dothis(){
$.ajax({
type: 'get',
cache: false,
url: 'http://example.com/timer.php',
beforeSend:function() {
console.log('loading...');
},
success: function(response) {
console.log(response)
}
});
}
</script>

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;
}
}
});
}
});

Call python function with ajax and flask continously

I need to call flask function in python with ajax continously. To that I have following script in html file.
<script >
var ajaxFUN = function () {
$.ajax({
url: '/toAjax',
dataType: 'json',
success: function (data) {
console.log('get info');
$('#data').html(data['data']);
}
});
}
setTimeout(ajaxFUN, 1);
</script>
And here is the python code
#app.route('/toAjax')
def ajaxTo():
print("AJAX WAS HERE")
data= reader.getToAjax()
info = {
"data": data
}
return jsonify(info)
I need to call /toAjax header route in the python continously without hitting any button or any kind of method.
But that implementation prints only once AJAX WAS HERE. Where is the missing part ? How can I fix it ?
Here is the similiar questions which I have looked:
setTimeout() and setting parameters
how to make ajax calls continuously for 5 seconds once
setTimeout triggers exactly once (unless cancelled)
you could use setInterval, but that's likely to flood your server at the rate you've used for setTimeout
I would recommend the following
var ajaxFUN = function () {
$.ajax({
url: '/toAjax',
dataType: 'json',
success: function (data) {
console.log('get info');
$('#data').html(data['data']);
ajaxFUN(); // this calls the function again
}
});
}
ajaxFUN();
In case you're worried, there's no "recursion", since ajaxFUN() is being called in an asynchronous callback

Multiple load functions?

I'm curious if there is a better way to handle multiple load() functions on one page? I've got this code right here:
setInterval(function update() {
if (denial) return;
denial = true;
$.ajax({
url: 'update.php',
error: function () {
denial = false;
},
complete: function () {
denial = false;
$('#loader').hide("slow");
$('#credits').load('world1.php?mode=money');
$('#fuelleft').load('world1.php?mode=fuel');
$('#energyleft').load('world1.php?mode=energy');
$('#starmap').show("slow");
$('#upgrade-holder').load('world1.php?mode=up');
},
});
}, 1000);
It works perfectly fine, but is there any way I could improve this code?
update.php could include all the content that needed to be updated. You could then update that with html, e.g.:
$.ajax({
url: 'update.php',
dataType: 'json',
success: function(data) {
$('#credits').html(data.money);
$('#fuelleft').html(data.fuel);
$('#energyleft').html(data.energy);
// ...
}
});
This code here assumes that update.php returns JSON that looks like this:
{"money":"<p>some HTML to go into #credits</p>","fuelleft":"<p>more HTML</p>",…}
…but you could easily modify it for other output formats.

Check for ajax call completion

I'm having a problem filling and accessing a global variable with ajax. I have the following code (stripped down a bit):
var answers;
$(document).ready(function() {
showResults();
console.log(answers);
}
function showResults(){
$.ajax({
url: "/wp-content/themes/hoekiesikeenschool/question-storage.php",
data: { action: "get_results" },
type: "post",
dataType: "json"
}).done(function (data) {
answers = data.questionary;
return answers;
});
}
My question is the following: When I log answers in the done function it gives me a nice array. That would mean the array variable is filled. But when I log it from $(document).ready, It returns an empty variable. This is probably because the AJAX call is asynchronous, and the log gets executed before the variable is filled.
However, I need to use that variable on another page, so I need to access it from the $(document).ready ... Any idea about how to check if the variable is filled? Or when the showResults() is completed? Thanks in advance for your help!
Edit -
Thanks for your replies! But I'm still struggling with the following: As I understand, I can call another function from the ajax callback, and pass it the data. The thing is, I have to do a lot of different stuff with it after the call, and the only way I can get it to work now is by calling a function in the ajax callback, then calling another one from that one, etc...
So I end up wit showResults(); in the doc.ready, which then executes a lot of functions that are all "linked" together. Is there anyway I can return the data to the variable, for use in other places? I hope I have made this clear, English is not my native language, sorry.
Execute the functionality that is dependent on the answers array after the AJAX call. Call your function from within done(..)
A very rough idea:
var answers;
function functionalityDependentOnAnswers() {
//the code dependent on answers array.
}
$(document).ready(function() {
showResults();
//Move code here to functionalityDependentOnAnswers()
}
function showResults(){
$.ajax({
url: "/wp-content/themes/hoekiesikeenschool/question-storage.php",
data: { action: "get_results" },
type: "post",
dataType: "json"
}).done(function (data) {
answers = data.questionary;
functionalityDependentOnAnswer();
});
}
You can use the when method provided by jQuery (look at this SO link).
Or look at this SO link where a similar situation is explained.
Check the documentation for success: this will only be executed when successful callback is done.
var answers;
$(document).ready(function() {
showResults();
}
function showResults(){
$.ajax({
url: "/wp-content/themes/hoekiesikeenschool/question-storage.php",
data: { action: "get_results" },
type: "post",
dataType: "json"
}).when(function (data) {
console.log(answers);
answers = data.questionary;
return answers;
});
}
Idea: Have a hidden input field and add change listener to it.
<input type="hidden" id="answers_input" />
Now have a listener to this.
var answers;
$(document).ready(function() {
$('#answers_input').on('change', function() {
// trigger your custom code
console.log(answers);
})
showResults();
console.log(answers);
}
function showResults(){
$.ajax({
url: "/wp-content/themes/hoekiesikeenschool/question-storage.php",
data: { action: "get_results" },
type: "post",
dataType: "json"
}).done(function (data) {
answers = data.questionary;
$('#answers_input').val(answers);
});
}
Solution is kinda like a hack, let me know if this works for you
You're in the right way.
Do stuff with answers inside the DOM callback.
var answers;
$(document).ready(function() {
showResults();
}
function showResults(){
$.ajax({
url: "/wp-content/themes/hoekiesikeenschool/question-storage.php",
data: { action: "get_results" },
type: "post",
dataType: "json"
}).done(function (data) {
answers = data.questionary;
console.log(answers);
// Manage answers here
});
}

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();

Categories

Resources