Ajax call to update values in HTML - javascript

I am trying to implement a JS that updates an otherwise static HTML table in a set interval without any sort of websockets etc. just using ajax calls. The page is regularly updated with new data on the source server and I want the HTML, once open in the users browser, to load the new values and replace them dynamically.
My solution is matching the user HTML's id-tags with it's updated pairs in the new version on the server and inserting them using the ajax load function.
function updateVals () {
for (var i = 0; i < (idList.length); i++) {
$('#' + idList[i]).load('SamebutUpdated.html #' + idList[i])
}
}
Now, my problem is that when I try to update the source HTML's values on a simulated live server (VSC) while the user's HTML is open, the user's HTML jumps back to it's original data values before reloading the new ones and I'd like for it not to do that but instead keep the previously loaded ones and then replace them yet again.
Hope this is clear and cohesive enough.
Cheers in advance!

Related

How to submit value to database with jquery?

so basically i want to make a webpage to detect how many times user clicked on it and send that value to database. I know i should use ajax but just can't figure out how to use it.
var count = 0;
$("body").click(function() {
$("#track").text("you clicked " + count + " times");
count++;
});
$.ajax({
url: "index.html",
cache: false,
success: function(html){
$("#results").append(count);
}
});
Assuming the following things. You:
have AMP Stack installed with PHP & MySQL.
have a working DataBase in MySQL (most commonly used with PHP).
are running the web server and looking at HTTP version and not file version in Chrome.
I would go by this method:
On load, I'll get the current count from DataBase using a PHP backend.
In the PHP backend, I'll write a code to query MySQL and get the current value.
Use a single file, say count.php as a file to get and set the counts.
Using GET method, the file responds with the count.
Use an AJAX code and get the count data.
Using jQuery with the AJAX's response, update the DOM with the current count.
Once you load the page and update the value, set the event listener on click.
Update the current count in the UI by adding one more.
Use the same code as you have to update the UI to increment the count.
Fire a POST request using AJAX to the count.php and send the new value.
In the count.php, write an UPDATE query to update the count.
Send a success message.
When you reload the page or look at the database, the count will be preserved.

Ajax Call to refresh web page

Update: I am using an apache server on the back-end and vanilla JS and jquery on the front-end.
Currently i have a web page that is displaying a variety of data that i am pulling from my back-end server.
How it works: I have a php script that is scraping directory names and displaying them in a dropdown. I have a refresh function set in my html for the web page that refreshes the page every 30 seconds.
The problem: I don't like the constant refresh, especially if there is nothing to update.
Is there a way to use ajax to pool my back-end server and check if new data has been entered in the directory and then update my dropdown?
Many thanks!
Use .data
window.setInterval(function() {
$.getJSON('/foo', { }, function(result) {
//Get the old data stored in the body using jquery data
var old_data = $('body').data('my_data');
//If objects are not the same, update cell
if ( ! equal_objects(result, old_data) )
update_cell();
//Store the new data
$('body').data('my_data',result);
});
}, 30000);
OBS: equal_objects is a function you should implement to compare 2 objects since JavaScript doesn't provide this functionality. See this post for details: Object comparison in JavaScript

Javascript file for multiple html pages

I am beginner in Javascript. I am currentlyworking on a Phonegap app with it. I am stuck in between as I have 4 html pages for signup process, and I have to pass all the html pages input value to single js file as in final all data must be POSTed to server URL and also I have read on many sites that they have recommended using same js file for all the pages of your site to speed up the site. So I have two problems to solve. I searched on many sites but could not find the accurate answer.
I need to pass 4 html page's input value to single js file.
I have to make single js file for both sign-in and sign-up.
My codes for JS page is:
var firstName="";
var lastName="";
var email="";
var password="";
var retypePassword="";
var gender="";
var DOB="";
var institute="";
var course="";
var branch="";
var semester="";
var teachers = [];
function signUpStarting() {
alert(firstName + " "+lastName+" "+email+" "+password+" "+retypePassword+" "+gender+" "+DOB+" "+institute+" "+course+" "+branch+" "+semester+" "+teachers.join(","));
}
function signUp1() {
firstName[0] = $("#first_name").val().trim();
firstName[1] = $("#last_name").val().trim();
email = $("#email").val().trim();
password = $("#password").val();
retypePassword = $("#retype_password").val();
alert(firstName + " "+lastName+" "+email+" "+password+" "+retypePassword);
}
function signUp2() {
gender = $('#gender').find(":selected").text();
DOB = $('#DOB').val();
alert(gender+" "+DOB);
}
function signUp3() {
institute = $('#institute').find(":selected").text();
course = $('#course').find(":selected").text();
branch = $('#branch').find(":selected").text();
semester = $('#semester').find(":selected").text();
alert(institute+" "+course+" "+branch+" "+semester);
}
function signUp4() {
$(":checkbox" ).map(function() {
if($(this).is(':checked')){
teachers.push($('label[for="' + this.id + '"]').text());
}
});
signUpStarting();
}
In html pages I am calling JS functions for each pages:
On first page:
<a onclick="signUp1()" href="register-two.html">continue</a>
On second page:
<a onclick="signUp2()" href="register-three.html">continue</a>
On third page:
<a onclick="signUp3()" href="register-four.html">continue</a>
On fourth page:
<a onclick="signUp4()">continue</a>
On each transaction from one page to next I have set alert in JS, and I am getting alert with accurate values also. But after clicking the continue button from fourth page of html, I transferred the code to main signup function. I tried to see alert in signUpStarting() function but there I am getting response of just fourth page values and other values are showing nothing as the variables are null.
I am not getting how to save variable values for always without using localStorage or cookies and POSTing all data to server.And I think this would have been easier if I would know to code for all html pages for my site to single JS file.
Please help me !
I am not getting how to save variable values for always without using localStorage or cookies and POSTing all data to server.And I think this would have been easier if I would know to code for all html pages for my site to single JS file.
This is exactly right. You cannot store data in memory between page loads in a web browser environment because all javascript variables are naturally destroyed when the browser navigates away from the page to a new page (even if they use the same javascript on both pages). Thus, you have to save it somewhere with more permanence: localStorage, cookies, or on the server via POST or GET.
What I would recommend is scrapping the four different html pages and simply using one html page that changes dynamically as the user fills in data. This way the browser will not eliminate data before you are ready to POST it to the server.

Writing variables to a second HTML file with Javascript

I've got 2 HTML files and 1 javascript file, index.html, results.html and file.js
Inside index.html I retrieve user input which is used to do some calculations inside the javascript file. The calculating starts when a button is pressed. Now I want to display the data retrieved from index.html to display on results.html so when pressing the button it should run the function and go to another page.
It all works fine to calculate and show the results on 1 page, but I don't know how to display the results on results.html.
This is how a piece of the code looks:
function berekenKoolBehoefte(){
koolBehoefte = (energieBehoefte - (eiwitBehoefte * 4) - vetBehoefte) / 4;
toonKool();
}
function toonKool(){
var uitkomstKool = document.getElementById("uitkomstKool");
uitkomstKool.innerHTML = (koolBehoefte * 4).toFixed(1) + " kcal" + " " + koolBehoefte.toFixed(1) + " gram"
}
bereken.addEventListener('click', berekenKoolBehoefte, false);
This displays all on 1 page, know function toonKool() should be display inside results.html
Your best bet in this case is to use:
server side to store the values and get the results from there
cookies - if it's small data, simply put it inside a cookie. For more info how to use cookies with plain javascript look here
attach your results to url and then parse them with JS. You can see how it's done here
iFrame - you can attach your results in an iframe and access the
data. This method is quite good, but for my taste - it's awful
I think you'd better:
1) Create form on your page aroud the button.
2) On form submit do calculations and put result to hidden field in the form (Or post all fields for calculation to server side). Then all arguments that you want to pass would be accessible on server on second page.
3) Display second page using GET or POST argument from previous.
Cookies is something that you may forgot to clear and it's much harder to manage them.
Calculation in iframe is much worse then using ajax. You may use ajax for partial load the second page, then all javascript variables would remain.

Create a textfile from the input of an html-form with the browser (client-side)

I have an html site with a form in it and I want the user to be able to create a text/xml file depending on the input. But I wan't to avoid setting up a webserver only for this task.
Is there a good way, to do that, e.g. with Javascript? I think you can't create files with Javascript, but maybe create a data url and pass the text, so the user can save it to file?
Or is there another way to achieve this simple task without a webserver?
Solved it, somehow. I create a data url data:text/xml;charset=utf-8, followed by the XML.
function createXML() {
var XML = 'data:text/xml;charset=utf-8,<MainNode>';
var elements = document.getElementsByTagName('input'),i;
for (i in elements) {
if (elements[i].checked == true) {
XML += elements[i].value;
}
}
XML += '</MainNode>';
window.open(XML);
}
So the url looks like data:text/xml;charset=utf-8,<MainNode><SubNode>...</SubNode>...</MainNode>
Unfortunately this doesn't work for me on Chromium(Chrome) and on Firefox. It just displays the XML instead of showing a save dialog. But I think that's because of my settings and at least you can save it as a XML-file manually.
I haven't tried this but it should work.
After getting form data, system will call page A.
page A will have javascript that gets query strings and builds the page accordingly.
After finishing page build, user can save current page with following statement in javascript
document.execCommand('SaveAs',true,'file.html');

Categories