mac
mac

Reputation: 162

How to link up js variable with html form and send to PHP file

I have asked already similar question but I couldn't find good solution. I have got a variable in js called 'lat', which are numbers(lattitude). I would like to connect this variable with form, which I have on my site, and send it with other information inserting by users, to php file when clicking submit button in the end of the form.

<form action="address.php" method="post" class = "form1">

<--some input fields-->



<textarea id = "jj" name="comentary" cols="32" rows="12" wrap="virtual"></textarea></p>
<p class ="p2"><input type ="submit"  id = "ff" value="Send"></p>

</form>

My js script is in head tag, where in function I obtain "lat" from user choice on map.

var lat =  input.lat(); 

I have tried with lots of scripts to solve it, including Ajax etc. but none of them was worked. Can anyone help with this issue?

Upvotes: 0

Views: 376

Answers (4)

Chris Brickhouse
Chris Brickhouse

Reputation: 648

Add this hidden field inside your form tag:

<input type="hidden" id="lat" name="lat" value="">

Then $('#lat').val(lat); for jQuery or document.getElementById('lat').value = lat; if you're just using JavaScript.

Then when the form is submitted you will have the value of the "lat" field as form variable.

Upvotes: 0

Sam van Lieshout
Sam van Lieshout

Reputation: 11

Is the value static? You could add a hidden element to the form containing the value of lat. For instance in jQuery:

var latElement = $("<input />").attr("type", "hidden");
latElement.val(lat);
$(".form1").prepend(latElement);

Upvotes: 1

Suman Bogati
Suman Bogati

Reputation: 6351

With pure javaScript,

var lat = input.lat();

document.getElementById("latValue").value = lat;

Upvotes: 0

Bic
Bic

Reputation: 3134

Add a hidden input to your form to store the lat variable value:

<form action="address.php" method="post" class = "form1">
    <input type='hidden' id='latValue'>
    <--some input fields-->



    <textarea id = "jj" name="comentary" cols="32" rows="12" wrap="virtual"></textarea>    </p>
    <p class ="p2"><input type ="submit"  id = "ff" value="Send"></p>

</form>

JavaScript

var lat = input.lat();

$("#latValue").val(lat);

Because it is an input on the form, it will automatically get sent up with the form post.

Upvotes: 3

Related Questions