Как я могу автоматически заполнить эти данные JavaScript <div>в форме PHP? - PullRequest
2 голосов
/ 08 октября 2011

У меня есть .js, который заполняет 2 <div> данными о долготе и широте и работает отлично. Но я хочу взять эти данные и заполнить ими форму, чтобы я мог записать ее в свою базу данных, когда они нажмут кнопку отправки. Мне все равно, если форма скрыта или видна мне просто нужно, когда страница загружается и скрипт показывает данные, которые она также автоматически помещает в форму. Любая помощь очень ценится. Спасибо.

js называется main.js, который находится ниже, и код для заполнения данные на странице:

    <section>
<ul>
               <dl>
                       <dt>Latitude:</dt>
                       <dd id="latitude">Please...</dd>
               </dl>
               <dl>
                       <dt>Longitude:</dt>
                       <dd id="longitude">Wait...</dd>
               </dl>
               <dl>
                       <dt>Accuracy:</dt>
                       <dd id="accuracy">While...</dd>
               </dl>
               <dl>
                       <dt>Timestamp:</dt><dd id="timestamp">Calculating...</dd>
               </dl>
</ul>           
</section>



    <!--Now  and this is my issue I need the <dd id="latitude"> and <dd id="longitude"> some how in
a form to get in a SQL database -->




<ul class="pageitem">
                       <li class="smallfield"><span class="name">latitude</span><input
placeholder="" id="latitude" name="latitude" type="num" />
                       </li></ul>
<ul class="pageitem">
                       <li class="smallfield"><span class="name">Longitude</span><input
placeholder="" id="longitude" name="longitude" type="num" />
                       </li></ul>

Лучшая документация, которую я нашел, это: Как мне собрать данные из div для использования в форме

Но я не могу заставить это работать. Спасибо всем заранее.

JavaScript, который я использую:

/*
 * 
 * Find more about this app by visiting
 * http://miniapps.co.uk/
 *
 * Copyright (c) 2010 Alex Gibson, http://miniapps.co.uk/
 * Released under MIT license
 * http://miniapps.co.uk/license/
 * 
 */

var geoUtilityApp = (function() {

    var updateLocation = null;

    return {

        //initializes watchPosition.
        init: function () {

            updateLocation = navigator.geolocation.watchPosition(geoUtilityApp.success, geoUtilityApp.fail, {enableHighAccuracy: true});

        },

        success: function (position) {

            var timeStamp = null,
            heading = null,
            accuracy = null,
            altAccuracy = null,
            speed = null;


            //we must check to see whether or not each piece of data has been returned in the success call.
            //if a piece of data has been returned, we then update the meter readout.

            if(!position.coords.latitude) {
                document.querySelector('#latitude').innerHTML = 'Calculating';
            }
            else {
                document.querySelector('#latitude').innerHTML = position.coords.latitude;
            }

            if(!position.coords.longitude) {
                document.querySelector('#longitude').innerHTML = 'Calculating';
            }
            else {
                document.querySelector('#longitude').innerHTML = position.coords.longitude;
            }

            if(!position.coords.accuracy) {
                document.querySelector('#accuracy').innerHTML = 'Calculating';
            }
            else {
                accuracy = Math.round(position.coords.accuracy);
                document.querySelector('#accuracy').innerHTML = accuracy + ' meters';
            }

            if(!position.timestamp) {
                document.querySelector('#timestamp').innerHTML = 'Calculating';
            }
            else {
                //convert timestamp to be more human readable.
                timeStamp = geoUtilityApp.formatTimeStamp(position.timestamp);
                document.querySelector('#timestamp').innerHTML = timeStamp;
            }

            //update 'map' button href.
            geoUtilityApp.setMapURL(position.coords.latitude, position.coords.longitude);

            //update 'Mail location info' button href.
            geoUtilityApp.updateMail(position.coords.latitude, position.coords.longitude, accuracy, position.coords.altitude, altAccuracy, speed, heading, timeStamp);

        },

        //called if watchPosition returns an error.
        fail: function(error) {

            switch(error.code) {
                case 0:
                    // unknown error alert error message
                    alert('An unknown error occured');
                    break;

                case 1:
                    // permission denied alert error message
                    alert('Permission denied by user');
                    break;

                case 2:
                    // position unavailable error message
                    alert('Position unavailable');
                    break;

                case 3:
                    // timeout error message
                    alert('The request timed out');
                    break;
            }
        },


        //function that stops watchPosition, if we wished to call it
        stop: function() {

            navigator.geolocation.clearWatch(updateLocation);
        },

        //updates the href of the 'Map' button.
        setMapURL: function(latitude, longitude) {

            var URL = 'http://maps.google.com/maps?q=' + latitude + ',' + longitude;

            document.querySelector('#map').onclick = function() {
                window.open(URL);   
            };
        },

        //updates the href of the 'Mail location info' button.
        updateMail: function(latitude, longitude, accuracy, timeStamp) {

            (!latitude) ? latitude = '?' : latitude = latitude;
            (!longitude) ? longitude = '?' : longitude = longitude;
            (!accuracy) ? accuracy = '?\n' : accuracy += ' meters\n';
            (!timeStamp) ?timeStamp = '?\n\n' : timeStamp += '\n\n';

            var subject = 'My location';
            var body = 'Latitude: ' + latitude + '\nLongitude: ' + longitude + '\nAccuracy: ' + accuracy + 'Timestamp: ' + timeStamp + 'http://maps.google.com/maps?q=' + latitude + ',' + longitude + '\n';

            document.querySelector('#maillink').href = 'mailto:?subject=' + encodeURIComponent(subject) + '&body=' + encodeURIComponent(body);
        },

        //toggles the large 'Mail location info' button.
        sendMail: function() {

            var mailLink = document.querySelector('#maillist');

            if (mailLink.style.display === 'none') {
                mailLink.style.display = 'block';
            }
            else {
                mailLink.style.display = 'none';
            }
        },

        //takes a variable that is degrees clockwise from true north and returns the relevant compass direction.


        //takes a Unix timestamp and returns a formatted, human readable timestamp.
        formatTimeStamp: function(timestamp) {

            var date = new Date(timestamp);

            var month = date.getUTCMonth() + 1,
            day = date.getUTCDate(),
            year = date.getUTCFullYear(),
            hours = date.getUTCHours() - 5,
            minutes = date.getUTCMinutes(),
            seconds = date.getUTCSeconds(),

            formattedTime =  year + '-' + month + '-' + day + ' T ' + hours + ':' + minutes + ':' + seconds;

            return formattedTime;
        },

        loaded : function() {

            //test to see if browser supports geo location api.
            if (window.navigator.geolocation) { 

                //hide the address bar if visible.
                window.scrollTo(0,0);

                //hack to enable active pseudo selectors on buttons in mobile webkit
                document.addEventListener("touchstart", function() {},false);

                //hide the mail list items button.
                document.querySelector('#maillist').style.display = 'none';

                //initialise the app.   
                geoUtilityApp.init();

                //add an event listener for when the mail button is clicked.
                document.querySelector('#mail').addEventListener('click', geoUtilityApp.sendMail, false);

            } else {  
                alert('Your browser does not support Geolocation API. Sorry!');
            }
        }
    };

}());

window.addEventListener("DOMContentLoaded", geoUtilityApp.loaded, true);

Ответы [ 2 ]

1 голос
/ 08 октября 2011

Поместите эту форму в свой HTML-код, где вы хотите:

<form action="your_form_destination.php" method="post">
 <input type="hidden" id="long" name="long" />
 <input type="hidden" id="lat" name="lat" />
<input type="submit" value="Save values" />
</form>

А в свой код добавьте:

       //......
        if(!position.coords.latitude) {
            document.querySelector('#latitude').innerHTML = 'Calculating';
        }
        else {
            document.querySelector('#latitude').innerHTML = position.coords.latitude;
            document.getElementById("lat").value =  position.coords.latitude;
        }

        if(!position.coords.longitude) {
            document.querySelector('#longitude').innerHTML = 'Calculating';
        }
        else {
            document.querySelector('#longitude').innerHTML = position.coords.longitude;
            document.getElementById("long").value =  position.coords.longitude;
        }
      //......

Это должно решить вашу проблему, икогда вы нажмете кнопку, информация будет опубликована в вашем php-скрипте.

Дайте мне знать, если это поможет!

1 голос
/ 08 октября 2011

Назовите входные данные вашей формы, затем выберите их с помощью JS, например:

 <form action='#' method='post'>
 <input type='hidden' id='hidden1' name='hidden1' value=''/>
 <input type='text' id='text1' name='text1' value='text'/>
 </form>

 <script>
      //Add this code into whatever javascript you want to populate the form
      var thisElem = document.getElementById("hidden1");
      thisElem.value = yourOtherJavascriptValue;
 </script>

Если вы не хотите, чтобы пользователь видел эту информацию, просто используйте несколько скрытых элементов, в противном случае используйте тексты

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...