freepwnyrides
freepwnyrides

Reputation: 23

How do I write a javascript variable to an sql database?

I have a form that writes a name and email address defined by the user to a mysql database. The part I'm having trouble with is I have secondary part of the form that assigns values to checkboxes and then gives you the sum, which is defined as "total". I want to write this total to the same database. I'm new to coding in JS and I'm not quite sure how to pass total along once the value has been established by the user.

<form name="form1">
    <input type="checkbox" name="check[]" data-weight="5" /> 5<br />
    <input type="checkbox" name="check[]" data-weight="10" /> 10<br />
    <input type="checkbox" name="check[]" data-weight="30" /> 30<br />
    <div>Total: <span id="total">0</span></div>
</form>

<script type="text/javascript">
    (function () {
        var totalEl = document.getElementById('total');
        var total = 0;
        var checkboxes = document.form1['check[]'];

        var handleClick = function () {
            total += parseInt(this.getAttribute('data-weight'), 10) * (this.checked ? 1 : -1);
            totalEl.innerHTML = total;
        };

        var l = checkboxes.length;
        for (i = 0; i < l; ++i) {
            checkboxes[i].onclick = handleClick;
        }
    }());
</script>

Upvotes: 1

Views: 1221

Answers (2)

Sampo Sarrala
Sampo Sarrala

Reputation: 4868

First of all: Should it work if Javascript is disabled? Or is it acceptable that form is submitted but possibly wrong/no value is written to db?

If it does not matter

what you get in your db from users without Javascript enabled then you can go with AvL's suggestion.

However if you want correct values

then you should make sure that you are not relying on Javascript support. You should make sure that your form always delivers consistent values, even if it is submitted without calculations done in Javascript.

In this case you should do calculations at server side rather than client side. Of course you could do calculations at client side but thing is that you only do client side math for client side user interface (not for final data).

I don't know about your server side processing and because of that I am not suggesting any code for server side calculations and/or saving values to database. Thus my only suggestion is that you should process your check[] bit array at server side.

If you want you can describe your server/database/processing better and leave note about your changes as comment to my answer.

Update: This is basically longer explanation about what pst commented to your question.

Upvotes: 1

AvL
AvL

Reputation: 3093

You can add a hidden input element:

<input id="totalChecked" type="hidden" name="total" value="0" />

and add the following to your function:

document.getElementById('totalChecked').value = total;

check out this fiddle

Upvotes: 0

Related Questions