How to pass div id value to PHP variable? - php

I am using an auto complete form to find "lat" and "lng" for a city name and it works fine. I get the correct values in div id="lat" and div id="lng" but I want to use these values in php variables as $latitude="lat" and $longitude="lng" to use them in a php script that needs $latitude and $longitude?
I have been trying many of the solutions presented here, but my knowledge is too short to make it work.
The script is:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=MY_KEY&libraries=places">
</script>
<script>
function initialize() {
var address = (document.getElementById('city-input'));
var autocomplete = new google.maps.places.Autocomplete(address);
autocomplete.setTypes(['geocode']);
google.maps.event.addListener(autocomplete, 'place_changed', function()
{
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
var address = '';
if (place.address_components) {
address = [
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
document.getElementById('lat').innerHTML = place.geometry.location.lat();
document.getElementById('lng').innerHTML = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<input id="city-input" class="controls" type="text"
placeholder="Enter a location">
<div id="lat"></div>
<div id="lng"></div>
And for the php part I am trying this with no result at all
<?php
$latitude = (isset($_GET['lat']))?$_GET['lat']:'';
$longitude = (isset($_GET['lng']))?$_GET['lng']:'';
echo $latitude;
echo $longitude;
?>
Is there any way to do what I intend to do? (get $latitude and $longitude with the values that were correctly obtained from googleapis?)
Thank you so much for any precious help :-)

I am sorry for confusing vanialla JS with jquery. But I'm trying my best to help.
You can do it using ajax
get the lat value and long value and pass it to ajax data. lets call it
latjs and lonjs
$.ajax({
type: "POST",
url: "lat_lon.php",
data: "lat="+latjs+"&lon="+lonjs,
success: function (html) {
if (html === 'true') {
at the php side, capture it this way:
$data = file_get_contents('php://input');
if($data != null) {
parse_str($data, $output);
$output_lan = $output['lat'];
$output_lon = $output['lon'];
blah blah process
}

The last 2 assignment code is wrong:
document.getElementById('lat').innerHTML = place.geometry.location.lat();
document.getElementById('long').innerHTML = place.geometry.location.lng();
The above should be
$("#lat").html(place.geometry.location.lat());
$("#long").html(place.geometry.location.lng());
the code is not 100% working, but should be in the above lines. no need to use get elementbyID and all.
Hope this helps
VInay KR

Related

Passing value correctly to PHP from AJAX Code

So I'm trying to pass a value from my AJAX code to my PHP code which connects to an API to get the weather. It works when just using PHP, but I want ajax to return the results to some div on the same page. My code looks correct when I compare it to other examples but it just doesn't work.
Code may not be written with security in mind, standard practice etc, I'm just trying to play around with API's and get the basics of AJAX.
api.php:
$city = $_POST['city'];
function getCityLat($x) {
$latUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='. $x .'APIKEY';
$latResponse = file_get_contents($latUrl);
$latArray = json_decode($latResponse, true);
$lat = $latArray['results'][0]['geometry']['location']['lat'];
echo $lat;
return $lat;
}
function getCityLng($y) {
$lngUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='. $y .'APIKEY';
$lngResponse = file_get_contents($lngUrl);
$lngArray = json_decode($lngResponse, true);
$lng = $lngArray['results'][0]['geometry']['location']['lng'];
echo $lng;
return $lng;
}
function getWeather($x, $y) {
$weatherUrl = 'https://api.darksky.net/forecast/APIKEY/' . $x . ',' . $y;
$weatherResponse = file_get_contents($weatherUrl);
$weatherArray = json_decode($weatherResponse, true);
$timeZone = $weatherArray['timezone'];
$locWeather = $weatherArray['currently']['temperature'];
$locFeelsLike = $weatherArray['currently']['apparentTemperature'];
$windSpeed = $weatherArray['currently']['windSpeed'];
$weatherSummary = $weatherArray['currently']['summary'];
$time = $weatherArray['currently']['time'];
$outputweather = '<p>Temp: '.$locWeather.'</p>';
echo $outputweather;
}
getWeather(getCityLat($city), getCityLng($city));
?>
index.php(html):
<h3 align="center">Weather</h3>
<form align="center" method="POST">
<input type="text" id="city" name="city" placeholder="Enter City">
<button class="btn btn-xs btn-success" name="city_go" id="city_go">Go</button>
</form>
<div id="weather"></div>
JQuery:
function getWeather(city) {
$.ajax({
url: "api.php",
method: "POST",
data: {city:city},
dataType: "text",
success: function(data) {
$('#weather').html(data);
}
});
}
$(document).on('click', '#city_go', function() {
var city = $('#city').val();
getWeather(city);
});
The problem is that you are submitting a form, which forces a page refresh. Everything else is working correctly, just the page is being refreshed. To fix that you need to update your click event to something like
$(document).on('click', '#city_go', function(e) {
e.preventDefault();
var city = $('#city').val();
getWeather(city);
});
the preventDefault() call will cancel the default action of the form (the page refresh) and allow the AJAX call to follow through and display the data.

submit form php without refresh page

I'm working on a PHP application i want to submit form without refresh page. Actually, i want my php code to be written on the same page as the one containing html and jquery code.
In order to submit form using jquery i've written this code
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
$.post("php-opt.php", //Required URL of the page on server
{ // Data Sending With Request To Server
selectrefuser:vname,
},
function(response,status){ // Required Callback Function
//alert("*----Received Data----*\n\nResponse : " + response+"\n\nStatus : " + status);//"response" receives - whatever written in echo of above PHP script.
});
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
//return false;
//e.preventDefault();
//$("#monbutton:hidden").trigger('click');
});
});
and my php code is :
<?php
$resclient_alt = 1;
$resclient_long = 1;
if(isset($_POST['selectrefuser'])){
$client = $_POST['selectrefuser'];
echo $client;
$client_valide = mysql_real_escape_string($client);
$dbprotect = mysql_connect("localhost", "root", "") ;
$query_alt= "SELECT altitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1_alt=mysql_query($query_alt, $dbprotect);
$row_ss_alt = mysql_fetch_row($query_resclient1_alt);
$resclient_alt = $row_ss_alt[0];
//echo $resclient_alt;
$query_gps= "SELECT longitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1=mysql_query($query_gps, $dbprotect);
$row_ss_ad = mysql_fetch_row($query_resclient1);
$resclient_long = $row_ss_ad[0];
}
?>
My form is as below
<form id="form1" name="form1" method="post" >
<label>
<select name="selectrefuser" id="selectrefuser">
<?php
$array1_refuser = array();
while (list($key,$value) = each($array_facture_client_refuser)) {
$array1_refuser[$key] = $value;
?>
<option value="0" selected="selected"></option>
<option value="<?php echo $value["client"];?>"> <?php echo $value["client"];?></option>
<?php
}
?>
</select>
</label>
<button id="btn">Send Data</button>
</form>
My code does these actions:
select client get its GPS coordinates
recuperates them in php variable
use them as jquery variable
display marquer on map
So since i do this steps for many clients i don't want my page to refresh.
When i add return false or e.preventDefault the marquer is not displayed, when i remove it the page refresh i can get my marquer but i'll lost it when selecting another client.
is there a way to do this ?
EDIT
I've tried using this code, php_query.php is my current page , but the page still refresh.
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Edit
When adding e.preventDfault , this code doesn't seem to work
$( "#monbutton" ).click(function() {
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
$('#myResults').html("je suis "+php_long);
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
});
This code recuperate this value var vname = $("#selectrefuser").val(); get result from sql query and return it to jquery .
It will refresh since you have not prvent default action of <button> in script
$("#btn").click(function(e){ //pass event
e.preventDefault(); //this will prevent from refresh
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Updated
Actually, i want my php code to be written on the same page as the one containing html and jquery code
You can detect the ajax call on php using below snippet
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special code here */
}

Displaying Javascript Content In HTML Or Php Variable

I have javascript that gets the Facebook name of a user when they login on my file indir.php. However, I cannot get that name javascript variable to transform into a php variable or a <input type="hidden" name="name" value="" />. Currently, I can get the name using:
<script>
...facebook stuff...
function login() {
FB.api('/me', function(response) {
document.getElementById('login').style.display = "block";
var mos = response.name;
document.getElementById('login').innerHTML = mos;
}
}
...
</script>
And then display the name using:
<div id="login" style ="display:none"></div>
This should let you get the name in the field
First Add an id to the input field
<input type="hidden" name="name" id="fb_name" value="" />
Then
<script>
...facebook stuff...
function login() {
FB.api('/me', function(response) {
document.getElementById('login').style.display = "block";
var mos = response.name;
document.getElementById('login').innerHTML = mos;
//Enter the value in field
var field= document.getElementById("fb_name");
field.value = mos;
}
...
</script>
I think part of the problem is that the opening brackets on the FB.api call are not closed see snippet below.
If this is this done then the javascript function will update the div with the value of response.name.
It would only need to be a php variable if you are doing something with the information server side. You could then send it using AJAX if needed.
function login(){
FB.api('/me', function(response) {
document.getElementById('login').style.display = "block";
var mos = response.name;
document.getElementById('login').innerHTML = mos;
});
});
You can send it to php in a POST-request using AJAX:
var xhr = new XMLHttpRequest();
var content = "c=" + mos;
xhr.open("POST", "serverscript.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(content);
Receive at server side using something like
<?php
if (isset($_POST['c'])) {
$data = htmlspecialchars($_POST['c'], ENT_QUOTES, 'UTF-8');
}
?>
Try this something like this:
Javascript:
<script>
var name = 'Luis';
var variablejs = 'Your javascript value: ' + name ;
</script>
PHP:
<?php
$variablephp = "<script> document.write(variablejs) </script>";
echo "variablephp = $variablephp";
?>

Trouble getting php data from database through javascript function

On my php site, I want to retrieve data every three seconds from a mysql database using javascript.
Problem: when I retrieve data using SELECT * from msgtable, then neither php nor javascript startTime seems to work.
JavaScript:
setInterval(function() {
var link = document.getElementById("chg");
link.href = "http://google.com.pk";
link.innerHTML = "<?php dynamic(); ?>";
}, 3000);
function startTime() {
var today = new Date();
var s = today.getSeconds();
s = checkTime(s);
if( s == s+3 ) { alert("faraz"); }
document.getElementById('time').innerHTML= s;
t = setTimeout( function() { startTime() }, 500 );
}
function changeURL() {
var link = document.getElementById("chg");
link.href = "http://google.com.pk";
link.innerHTML = "Google Pakistan";
}
function checkTime( i ) {
if ( i < 10 ) {
i = "0" + i;
}
return i;
}
php:
<?php
$connection = mysql_connect("localhost","root","");
$db_select = mysql_select_db("msgs",$connection);
$result = mysql_query("SELECT * FROM msgtable", $connection);
function dynamic() {
echo "faraz";
while ( $row = mysql_fetch_array( $result ) ) {
echo $row['msgBody'] ;
}
}
?>
HTML:
<body onLoad="startTime()">
<div id="chg1"> 3 Seconds to Google Pakistan </div>
Google Italia
<!-- Hafiz Faraz Mukhtar-->
<div id="time"> Time </div>
<div class="publicOut">Faraz</div>
</body>
You can't call a PHP function through JavaScript like this:
link.innerHTML = "<?php dynamic(); ?>";
You will need to make an AJAX call to run the PHP script and return the result. I would recommend using jQuery and $.ajax, which makes this very easy.
http://api.jquery.com/jQuery.ajax/
You need to use normal ajax or jquery ajax for this .Use javascript setInterval() function for setting an interval
Here is a sample jquery ajax method
function request()
{
$.ajax ({
url : "";
data : {},
dataType : "" ,
success : function(success) {} ,
error : function() {}
});
}
setInterval() Syntax
setInterval(request,3000); // in milliseconds

How to access PHP session variables from jQuery function in a .js file?

How to access PHP session variables from jQuery function in a .js file?
In this code, I want to get "value" from a session variable
$(function() {
$("#progressbar").progressbar({
value: 37
});
});
You can produce the javascript file via PHP. Nothing says a javascript file must have a .js extention. For example in your HTML:
<script src='javascript.php'></script>
Then your script file:
<?php header("Content-type: application/javascript"); ?>
$(function() {
$( "#progressbar" ).progressbar({
value: <?php echo $_SESSION['value'] ?>
});
// ... more javascript ...
If this particular method isn't an option, you could put an AJAX request in your javascript file, and have the data returned as JSON from the server side script.
I was struggling with the same problem and stumbled upon this page. Another solution I came up with would be this :
In your html, echo the session variable (mine here is $_SESSION['origin']) to any element of your choosing :
<p id="sessionOrigin"><?=$_SESSION['origin'];?></p>
In your js, using jQuery you can access it like so :
$("#sessionOrigin").text();
EDIT: or even better, put it in a hidden input
<input type="hidden" name="theOrigin" value="<?=$_SESSION['origin'];?>"></input>
If you want to maintain a clearer separation of PHP and JS (it makes syntax highlighting and checking in IDEs easier) then you can create JQuery plugins for your code and then pass the $_SESSION['param'] as a variable.
So in page.php:
<script src="my_progress_bar.js"></script>
<script>
$(function () {
var percent = <?php echo $_SESSION['percent']; ?>;
$.my_progress_bar(percent);
});
</script>
Then in my_progress_bar.js:
(function ($) {
$.my_progress_bar = function(percent) {
$("#progressbar").progressbar({
value: percent
});
};
})(jQuery);
You can pass you session variables from your php script to JQUERY using JSON such as
JS:
jQuery("#rowed2").jqGrid({
url:'yourphp.php?q=3',
datatype: "json",
colNames:['Actions'],
colModel:[{
name:'Actions',
index:'Actions',
width:155,
sortable:false
}],
rowNum:30,
rowList:[50,100,150,200,300,400,500,600],
pager: '#prowed2',
sortname: 'id',
height: 660,
viewrecords: true,
sortorder: 'desc',
gridview:true,
editurl: 'yourphp.php',
caption: 'Caption',
gridComplete: function() {
var ids = jQuery("#rowed2").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
be = "<input style='height:22px;width:50px;' `enter code here` type='button' value='Edit' onclick=\"jQuery('#rowed2').editRow('"+cl+"');\" />";
se = "<input style='height:22px;width:50px;' type='button' value='Save' onclick=\"jQuery('#rowed2').saveRow('"+cl+"');\" />";
ce = "<input style='height:22px;width:50px;' type='button' value='Cancel' onclick=\"jQuery('#rowed2').restoreRow('"+cl+"');\" />";
jQuery("#rowed2").jqGrid('setRowData', ids[i], {Actions:be+se+ce});
}
}
});
PHP
// start your session
session_start();
// get session from database or create you own
$session_username = $_SESSION['John'];
$session_email = $_SESSION['johndoe#jd.com'];
$response = new stdClass();
$response->session_username = $session_username;
$response->session_email = $session_email;
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$response->rows[$i]['id'] = $row['ID'];
$response->rows[$i]['cell'] = array("", $row['rowvariable1'], $row['rowvariable2']);
$i++;
}
echo json_encode($response);
// this response (which contains your Session variables) is sent back to your JQUERY
You cant access PHP session variables/values in JS, one is server side (PHP), the other client side (JS).
What you can do is pass or return the SESSION value to your JS, by say, an AJAX call. In your JS, make a call to a PHP script which simply outputs for return to your JS the SESSION variable's value, then use your JS to handle this returned information.
Alternatively store the value in a COOKIE, which can be accessed by either framework..though this may not be the best approach in your situation.
OR you can generate some JS in your PHP which returns/sets the variable, i.e.:
<? php
echo "<script type='text/javascript'>
alert('".json_encode($_SESSION['msg'])."');
</script>";
?>
This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.
Three javascript libraries are required, createCookie, readCookie and eraseCookie. These libraries are not mine but I began using them about 5 years ago and don't know their origin.
createCookie = function(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
readCookie = function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
eraseCookie = function (name) {
createCookie(name, "", -1);
}
To call them you need to create a small PHP function, normally as part of your support library, as follows:
<?php
function createjavaScriptCookie($sessionVarible) {
$s = "<script>";
$s = $s.'createCookie('. '"'. $sessionVarible
.'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
$s = $s."</script>";
echo $s;
}
?>
So to use all you now have to include within your index.php file is
$_SESSION["video_dir"] = "/video_dir/";
createjavaScriptCookie("video_dir");
Now in your javascript library.js you can recover the cookie with the following code:
var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';
I hope this helps.
Strangely importing directly from $_SESSION not working but have to do this to make it work :
<?php
$phpVar = $_SESSION['var'];
?>
<script>
var variableValue= '<?php echo $phpVar; ?>';
var imported = document.createElement('script');
imported.src = './your/path/to.js';
document.head.appendChild(imported);
</script>
and in to.js
$(document).ready(function(){
alert(variableValue);
// rest of js file

Categories