I'm struggling so hard with a very silly bug. I send a form via Ajax with POST but since I also wanted a GET variable, I put it in the url.
I have something like:
var xhr = getXHR();
var id = <?php echo $id ?>;
var xhrUrl = 'request_performupdate?id='+id;
Then, in the performupdate function I have :
if($_GET)
{
$a = fopen('get.txt','w');
$test=$_GET['id'];
fwrite($a,'idlol:'.$test);
}
$id=$test;
But here, the file get.txt is well written with the correct value, but I get a notice error saying $test (the second one) doesn't exist... That's unbelievable ! Hope you will have an idea, thanks very much.
Related
i know this question is asked many times, but non of them having right solution. i am using ajax to get the response from PHP Page. After getting the response i want to use the value in PHP variable. Below code is getting result but i am confused with the usage of it.
below is my index.php
function getLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function geoSuccess(position) {
var glat = position.coords.latitude;
var glng = position.coords.longitude;
//alert("lat:" + glat + " lng:" + glng);
geocoding(glat,glng);
}
function geoError() {
alert("Geocoder failed.");
}
function geocoding(glat,glng){
$.ajax({
type:'POST',
url:'geolocation.php',
data:'latitude='+glat+'&longitude='+glng,
success:function(result){
if(result){
$("#locationg").val(result);
$("#htmllocation").html(result);
}
}
});
}
geolocation.php
<?php
session_start();
if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
//Send request and receive json data by latitude and longitude
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=false';
$json = #file_get_contents($url);
$data = json_decode($json);
$status = $data->status;
if($status=="OK"){
//Get address from json data
$location = $data->results[0]->formatted_address;
//$location = $data->results[0]->address_components;
for($j=0;$j<count($data->results[0]->address_components);$j++){
$cn=array($data->results[0]->address_components[$j]->types[0]);
if(in_array("locality", $cn))
{
$city= $data->results[0]->address_components[$j]->long_name;
}
}
}else{
echo 'No Location';
}
echo $city;
}
?>
index.php
<?php
$city='<span id="htmllocation"></span>';
?>
when i echo $city i am getting city name but in inspect elements its showing like
<span id="htmllocation">Visakhapatnam</span>
issue is that i can not use this in MYSQL because it in html format, and i just want to get only the city name nothing else.
i hope my issue is clear, please leave a comment if not clear.
The user locates example.com/index.php, it displays a webpage.
You get the user's location from JS.
You send it back to the server, and get the addresses of that location.
Then you want to access the addresses from index.php
Is that correct? If so, you can't do it. Things not work like that. Webservers uses request-response modells. When your php finishes, the server kills the process, ei. $city and everything else are destroied. After it, you get the user's location. If you want something from the server again, you must send a new request, because index.php's process is no longer available. This is impossible to get the city's name before you get it from the client, and you can't get the location from the client at the moment he first requests index.php, neither you can access an already-non-running process.
All you need to do is run your SQL query inside geolocation.php. When you get the result from Google, then fetch the data from your database. There $city doesn't contain any HTML codes, only the plain city name. Then send back some data related to that city to the user, and display it.
initially start session in PHP using
sessionstart()
method. then add this code after above code.
First set session using Jquery as below:
$.session.set("yoursessioname", "storevalue");
then try to get this session variable in PHP as below:
$city = $_SESSION['yoursessioname'];
I haven't tried it yet. I Hope it helps. :)
Use PHP in built function strip_tags to remove HTML tags from your statement to get only City in variable like below:
$city = strip_tags('<span id="htmllocation">Visakhapatnam</span>');
// Output will be Visakhapatnam only
Could you handle the name "John" in php from this getJson()? Could you assign it to a php variable?
var output = [];
$.getJSON('DisplayMap.php',{ Name: "john" }, function(data) {
for (var i in data.b) {
output.push(new google.maps.LatLng(data.b[i].Ya, data.b[i].Za));
}
});
Since it will initiate a HTTP GET request, you can get variable in PHP as below
$Name = $_GET["name"];
This code will cause a GET request to ./DisplayMap.php with a query string variable named Name set to the value of john:
http://www.site.com/DisplayMap.php?Name=john
In PHP, you would access this via $_GET['Name'] or $_REQUEST['Name'].
As for the success function and what happens there, I don't really know what your system returns and it seems unrelated to your question.
Ok, so i tried multiple of solutions but nothing seems to work for me, (or i'm just too stupid to get it).
I have such jquery code:
Jquery:
var current_id = $(this).attr("id");
var dataString = {"id" : current_id};
$.post("popup.php" , {"id" : $(this).attr("id")}, function(msg) { alert(msg);} );
I know few lines are useless here but i tried all options,
PHP:
$tmp = $_POST['id'];
if($tmp == "kontakt"){
echo '<p>UDANE PRZESŁANIE</p>';}
else{
echo '<p>NIEUDANE PRZESŁANIE</p>';
}
When i click on id=kontakt php returns error :
Notice: Undefined index: id in D:\***\popup.php on line 2
but alert sends back
<p>UDANE PRZESŁANIE</p>
Edit:
Ok, Maybe i haven't make my question clear. I don't care if php error is shown or not, I just want to know why it shows up in the first place.
It's just a PHP warning - it's basically saying that $_POST has no index called 'id'.
You can get rid of it in several ways...
A shorted version of Austin Allover's answer:
if(!isset($_POST['id')) $tmp = '';
Turn of warnings in your script or your php config file, see: http://php.net/manual/en/function.error-reporting.php (Look for E_WARNING)
You might also want try $.post("popup.php" , {"id" : "BLAHBLAHBLAH"}, function(msg) { alert(msg);} ); - just in case $(this).attr("id") doesn't contain anything...
Declare $tmp var this way:
$tmp = (isset($_POST['id'])) ? $_POST['id'] : "";
Or ...
if(isset($_POST['id'])) { $tmp = $_POST['id']; } else { $tmp = ""; }
If you don't understand what this code does...
if post id is set, then declare $tmp as the post id, else set $tmp as "". This will take away the PHP notice.
I am using the jquery plugin datatables and am trying to take advantage of the fnRender function to manipulate some data.
I have a php script that returns a JSON string from my $.post. Here is a sample response that I get from each post: {"description":"myvalue"}. I got this from the Google Chrome Developer Tools.
Here is my post function:
$.post("functions/getDescription.php", {gpn:oObj.aData[1]},
function(data) {
returnedVal = jQuery.parseJSON(data);
var test = returnedVal.description;
//alert(test);
return test;
});
Here is my php script:
$passedVal = mysql_real_escape_string(($_POST['gpn']));
$descriptionPrint = array('description' => "");
include 'db_include.php';
$getDescription = "SELECT part_number_description, description FROM unit_description
WHERE part_number_description = '$passedVal' ";
$result = mysql_query($getDescription,$db) or die(mysql_error($db));
while ($row = mysql_fetch_array($result)) {
extract($row);
$descriptionPrint = $description;
echo json_encode(array('description' => $descriptionPrint));
}
There is only one value returned from each query.
Every row alerts the right value but returns undefined.
If I replace javascript function with only a return value of a string or any generic value it works fine.
I feel like there has to be something silly I'm missing in all this. Any help is much appreciated and please let me know if you need more information (I know troubleshooting something running in a plugin like datatables can be frustrating). Thanks.
Because $.post does not return the return value of the anonymous callback function you pass to it as its third argument.
Since Ajax is asynchronous, $.post even returns before the callback function is executed.
If you want to do something when the data gets back from the server, then the callback function has to to it (or call another function to do it).
This is the same reason that the following wouldn't work:
var were_you_expecting_sunshine = $('button').click(function () {
return "sunshine";
});
All,
I have the following bit of code:
function addPoints() {
newpoints[0] = new Array(41.45998, 87.59643, icon0, 'Place', 'Content to open');
for(var i = 0; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
There is other code around this to display the marker on my map. However this value is hardcoded. I have a PHP/mySQL database that has lat/long coordinates along with some other values. Say I have like three entries that I want to create markers for. How would I pass the addPoints function the lat/long that I got from my database so I can use it in this function correctly?
I updated my code to look like the following for the addPoints:
function addPoints(num, lat, long) {
newpoints[num] = new Array(lat, long, icon0, 'Place', 'Stuff name');
alert("The newpoints length is: "+newpoints.length);
for(var i = 1; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
I call this function by doing this:
<script>
addPoints('<?php echo json_encode($num_coordinates); ?>','<?php echo json_encode($lat_coordinates); ?>', '<?php echo json_encode($long_coordinates); ?>');
</script>
It doesn't work though. When I try not to pass it to javascript and just output the lat coordinates for example. I get the following output:
{"1":"40.59479899","2":"41.4599860"}
Which are the correct coordinates in my array. No markers get created though. Any ideas on what to do next or what I'm doing wrong?
An easy and clean way to pass an array from PHP to JavaScript is to simply echo the json_encode version of the array.
$array = array(1,2,3,4,5,6);
echo 'var values = '.json_encode($array).';';
PHP executes on the server before getting sent to the the client. Therefor, if you can do things like this:
newpoints[0] = new Array(<?php echo $lattitude;?>, <?php echo $longitude;?>, icon0, 'Place', 'Content to open');
Where $lattitude and $longitude are values that you pulled out of you database with PHP.
When this page is requested by the client, your php code executes, real values get plugged in where those php tags are making it look like the example you provided, and then it gets sent to the client.
If you want to change these values using JS on the client, or fetch new ones from the server, let me know and I'll add an example of that.
EDIT:
Okay, in light of your comments, it sounds like you've got a few options. Here's one:
When the user selects a category (restaurants, bars, etc) you pass that category as a url parameter and reload either the whole page, or just the map part of it (depends on your set up but might be worth investigating). Your link would look something like this:
http://www.your-domain-here.com/maps.php?category=bars
Maps.php is ready to catch the category using the $_GET array:
$category = $_GET['category']; //'bars'
Your php then grabs the appropriate location data from the database (I'll leave that part to you) and sticks it in a variable that your JS-controlled map will be able to use:
//JS in maps.php - you could add this var to the window object
// if you have separated js files...
var locationCoords = <?php echo json_encode($arrayOfCoordinatesFromDB);?>;
When you page loads on the client machine, it now has an array of coordinates to use for the map ready to go in the locationCoords variable.
Then, depending on which coordinates you need to display on the map, you pass them as arguments to your addPoints() using standard Javascript (nothing tricky here).
That's how I'd do it. Hope that helps!
It is as simple as echoing the php values.
new Array(<?php echo $php_lat;?>, <?php echo $php_long;?>, icon0 etc...
I made a dynamic banner with this javascript array initialization. It works fine when the javascript is embedded in php.
<?php
// This is our php array with URLs obtained from the server
$urlsPHP = ["img/img01.jpg","img/img02.jpg","img/img03.jpg"];
return = "
//...Some HTML...
<script type='text/javascript'>
// Now we use this inside the javascript
var urlsJavaScript = ".stripslashes(json_encode($urlsPHP)).";
//...Some javascript style to animate the banner...
</script>
";
// if we print this:
echo stripslashes(json_encode($urlsPHP));
// We obtain:
// ["img/banner/bak01.jpg","img/banner/bak02.jpg","img/banner/bak03.jpg"]
// This is a good syntax to initialize our javascript array
// if we print this:
echo json_encode($urlsPHP);
// We obtain:
// ["img\/banner\/bak01.jpg","img\/banner\/bak02.jpg","img\/banner\/bak03.jpg"]
// This is not a good syntax to initialize our javascript URLs array
?>