views:

189

answers:

4

Hi,

There maybe some simlar questions to this but I can't see anything that really solves my problem. I would like to pass the contents of a variable in JavaScript either into a PHP variable or a html form value.

Cheers, knowing how to do both would be very helpful.

A: 

You could use ajax, get/post request to the php script so that php can save the value although I haven't worked with Google Maps API. This answer should help you on DevShed

alexy13
+1  A: 

To save a Javascript variable into a html form element, I would go using DOM:

  //your target html form element must have a unique ID
  var input_element = document.getElementById('unique_id');
  input_element.value = google_maps_api_variable;

That's it!

clinisbut
A: 

You could use hidden fields in your form.

<input type="hidden" id="testField" />

Populate the value of your hidden field with the value of your variable, and it should be there when you submit it:

var variableWithData = 42; //get this from somewhere...
document.getElementById('testField').value = variableWithData;
Zeus
+1  A: 

Littering your document with IDs can cause problems down the line. You should use IDs only when you really need to.

Why not do it with the DOM Level 0 forms collection?

<form name="myForm">
    <input name="myInput" type="hidden" />
</form>

<script type="text/javascript">
    var foo = 42;
    document.forms["myForm"].elements["myInput"].value = foo;
</script>
Christopher Parker
What kind of problems can arise? I always refer my elements by its ID
clinisbut
Slapping IDs on everything can make it more likely that you'll eventually have duplicate IDs on a page (think includes, Ajax, etc.). While it's true that labels require IDs on their corresponding input elements to function properly, that really should be a fringe case. In my opinion, there's no reason to put an ID on a hidden form field when you can access it just as well with the forms collection.
Christopher Parker