Using javascript to capture values - javascript

I have a multi-page form which uses php and javascript to capture and store the various values.
The form is working well apart from one issue which has left me stumped. At the third stage of the form there is an optional extras section which works as it should when something is selected, but if nothing is selected the previous value is not carried forward to the next stage.
I'm guesing it's because I'm using a click function - so if nothing is selected it falls over. How do I get around this?
$('.radio2').click(function() {
var servicecost = <?php echo json_encode($_POST['sum']); ?>;
var sum2 = parseInt(servicecost);
$('.radio2:checked').each(function() {
sum2 += parseFloat($(this).closest('div').find('.values').text());
});
$('#sum2').html(sum2);
$("input[name=sum3]").val(sum2);
});
The servicecost is the value of the selected options on the previous page.

Passing values extracted by script between pages can be acheived in a few ways.
Use HTML5 Local/Session Storage - however your pages should belong to the same domain.This requires a HTML5 enabled browser.
Use cookies (same domain policy again) and will not work if cookies are disabled.
Send the data through URL encoding.
POST the data to server and then send it back from server.

You are correct. As you have written the logic to print servicecost in click event, you will not be able to print the service cost from previous page. My suggestion would be,
You set the div sum2 when you arrive to the current form.
Note: Make sum2 as global so that you don't need to use POST..
May be,
$(document).ready( function () {
var servicecost = <?php echo json_encode($_POST['sum']); ?>;
var sum2 = parseInt(servicecost);
$('#sum2').html(sum2);
$("input[name=sum3]").val(sum2);
});

I got around this by hiding the Next button until an option is selected. I added a new option (No optional extras) with a value of 0 for users that don't require any and this got around the click function issue.

Related

Saving the output of the output of a random array?

So this function works fine, however everytime i refresh the page the WINNER (person1 to 4) changes, i want to save the output and have it FIXED so that it wont change everytime i refresh..
Basicly: There is a timer on my website and when it hits 0 , it should automaticly pick someone from the list as the winner... but the winner should appear on the website for everyone and stay there
function randomNavn(){
document.getElementById("utskrift").innerHTML = "";
for (i = 0; i < 1; i++){
randName.push(nname.splice(Math.floor(Math.random() * nname.length), 1));
}
document.getElementById("utskrift").innerHTML = randName.join(", ");
}
var nname = ["Person1", "Person2", "Person3", "Person4"],
randName = [];
You need server-side code to do this -- and most likely a database. You can't do what you want from JavaScript. Each person's browser will run that javascript and get their own answer, bit it is only on their browser. Someone else will get a different answer, etc. That's not what you want to happen I assume.
To save data more permanently to be used in a web page, you have a few options:
Create a web service that accepts POST or PUT requests and saves the data on a server. This will allow you to share data between users.
Use a cookie. This will only save a value for each user's session. It won't share data between users.
You could use localStorage:
$window.localStorage.setItem('initData', {data: 'here'}
after some nights spent i've managed to found the perfect solution.
1) I've eliminated the javascript function for the array and instead craeted a php file where a winner or more is choosed.
2) From that php file we write the winners into a text file.
3) From that text file we read it through ajax and list it when countdown is over.
If anyone is ever in need, its good solution.
Thanks for everytning

Boostrap modal form with 2 submit buttons and save in database

I am trying to make a form on a modal. I have a form with 2 buttons: accept and reject.
If the user clicks on accept there is an update in that database, if the user clicks on reject there is another update.
I need to retain a certain value from database before, so I am making a select.
The problem is that I don't know how to make an insert in database using javascript (I know it is possible with jquery/ajax but how to call
it in the button?).
Here is my code:
Here is the Javascript function to insert in database that doesn't work
<script type="text/javascript">
function clicked1() {
//update candidate_jobs SET is_hired='1' WHERE candidate_id=$userId and applied_to=$row["job_id"];
var connection = new ActiveXObject("ADODB.Connection"),
recordSet = new ActiveXObject("ADODB.Recordset"),
connectionString = '';
connection.Open(connectionString);
recordSet.Open(
"update candidate_jobs SET is_hired='1' WHERE candidate_id=".$userId." and applied_to=".$row["job_id"]."";,
connection);
recordSet.close;
connection.close;
alert('You accepted the offer');
}
function clicked2() {
//idem clicked1 but change the is_hired value to be inserted in the database
alert('You rejected the offer');
}
</script>
Can it be done using Jquery and Ajax? How?
What it wrong with the code?
Thank you very much!
The concatenated sql string is prone to sql injection attacks (although obviously anyone viewing the page source can do whatever they like to the database anyway) - parameterization is the solution here and we need to use an IDENTITY or GUID.
Here is a list of possible issues:
1) The code will only ever run in IE browsers
2) You may need to download and install the COM components - ADO
3) You may need to run IE as an Administrator
4) You may need to open all sorts of security loopholes in IE (ActiveX controls, safe for scripting etc)
If you enable script debugging on the browser you'll get more info on the actual issue.
hope it helps you.

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.

Adding extra variables to a URL

Using JavaScript I managed to add a variable to a page and used $_GET on the new page to use the variable to perform queries. This first implementation worked fine as I was only using one variable. However I need to use two variables now and I'm running into some problems while doing it. If I combine both variables in the first page like shown below, the values are mixed up where my db value goes to my table id.
window.location.assign("test.php?db=&tbl=" + yourDB);
I tried putting both IDs only in my new page and using reload as my DB value would already have been passed. Using
window.location.reload("test.php?db=&tbl=" + yourTbl);
But this doesnt work either.
How can I get the url to have both my DB and table in the correct format? Like
test.php?db=test&tbl=customer
EDIT
yourDB variable is passed from a select form option from a different page which in turn opens the new page where the yourTbl variable exists.I can't therefore call yourDb
window.location = 'test.php?db=' + yourDB + '&tbl=' + yourTbl ;
'OP is asking: yourDB since this variable stores the values of select options from a different page.Any ideas'
My answer is 'Get value from selection menu list in the another page, and save this value into local storage or session storage.'
Something like this,
// save your db
window.sessionStorage.setItem("db", yourDB)
// get your db
var obj = window.sessionStorage.getItem("db");

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.

Categories