简体   繁体   中英

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?

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.

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

With pure javaScript,

var lat = input.lat();

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM