简体   繁体   中英

Inserting values from JavaScript directly into MySQL database

I'm using this JS function to grab visitor geolocation and show it on the page. This works great.

        function onGeoSuccess(location) {
        console.log(location);
        var strLocation = '<b>Latitude:</b> ' + location.coords.latitude + '<br />' +
                        '<b>Longitude:</b> ' + location.coords.longitude + '<br />' +
                        '<b>City:</b> ' + location.address.city + '<br />' +
                        '<b>Country:</b> ' + location.address.country + '<br />' +
                        '<b>Country Code:</b> ' + location.address.countryCode + '<br />' +
                        '<b>Region:</b> ' + location.address.region + '<br />' +
                        '<b>Accuracy:</b> ' + location.coords.accuracy + '<br />' +
                        '<br />'
        document.getElementById('geofound').innerHTML = strLocation;
    }
//The callback function executed when the location could not be fetched.
function onGeoError(error) {
    console.log(error);
}

window.onload = function () {
    //geolocator.locateByIP(onGeoSuccess, onGeoError, 2, 'map-canvas');
    var html5Options = { enableHighAccuracy: true, timeout: 6000, maximumAge: 0 };
    geolocator.locate(onGeoSuccess, onGeoError, true, html5Options, 'geo-details');
};

Now I would like to save this information into a MySQL database upon each call. Something like:

var strLocation = '$addtodb = "mysql_query('INSERT INTO gpsdb (lat, lon, city, country, code, region, accuracy) values (location.coords.latitude, location.coords.longitude, ...))"'

but I don't think this is the correct way to do so. What would be the correct way to enter info into a database directly from JS? I do not need to echo the info as it is doing now in JS, I would rather pull that from the DB once it is entered there. The JS would be used only to insert into DB.

you would need to use an ajax call http://api.jquery.com/jquery.ajax/ to your server-side language to then insert the information into the database

eg

post to database

function insertIntoDatabase(location){
 $.ajax({
   url: 'serversideurl',
   type : "POST",       
   data: location,       
   success: function(response) {
    // after success from server show the location on screen?
    document.getElementById('geofound').innerHTML = response.location;
    }
 });

}

then inside the server you can parse the object, or have this done by the client before it is sent as data. and run the mysql_query

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