I have a JavaScript value given by Google maps and I need to save it in a MySQL database.
Actually I have the variable
<script>
...
var lugar = results[0].geometry.location;// this gives me a latitud, longitud value, like: -34.397, 150.644
...
</script>
And I need to pass that variable to the PHP variable lugar
<?
$lugar= ?????
?>
-
possible duplicate of How to pass JavaScript variables to PHP?McGarnagle– McGarnagle2012年10月08日 05:27:13 +00:00Commented Oct 8, 2012 at 5:27
-
@dbaseman Given the antique answer from the duplicate, perhaps it should be the other way around? :)Ja͢ck– Ja͢ck2012年10月17日 04:15:22 +00:00Commented Oct 17, 2012 at 4:15
4 Answers 4
You can use jQuery ajax for this, but you need to create another script that save on your database:
<script>
$.ajax({
url: "save.in.my.database.php",
type: "post",
dataType:"json",
data: {
lugar: results[0].geometry.location
},
success: function(data){
alert('saved');
},
error: function(){
alert('error');
}
});
</script>
"save.in.my.database.php" receives a $_POST['lugar'] and you can save on your database.
Comments
You will need to pass it via a form submission, cookie, or through a querystring.
1 Comment
You can POST through a form or pass it in the URL if you're doing it on page transition, then just use $_POST or $_GET to receive the variable.
If you need it done seamlessly then you might want to look at using AJAX. TIZAG AJAX Tutorial
Comments
This will convert js variable to php variable
<script>
function sud(){
javavar=document.getElementById("text").value;
document.getElementById("rslt").innerHTML="<?php
$phpvar='"+javavar+"';
echo $phpvar.$phpvar;?>";
}
function sud2(){
document.getElementById("rslt2").innerHTML="<?php
echo $phpvar;?>";
}
</script>
<body>
<div id="rslt">
</div>
<div id="rslt2">
</div>
<input type="text" id="text" />
<button onClick="sud()" >Convert</button>
<button onClick="sud2()">Once Again</button>
</body>