I have the following javascript function
function success_callback(p)
{
lat = p.coords.latitude.toFixed(2);
lon = p.coords.longitude.toFixed(2);
}
Now I want to transfer both the variable to PHP using Jquery AJAX, I am pretty new to Jquery, I am not able to figure out how to do it. I want to transfer the variables to the same PHP file where this JS code resides. Is that possible ?
Yes it is. You could post the variables using the data string. Have a look at the Manual.
$.ajax({
type: "POST",
data: "lat="+lat+"&lon="+lon,
success: function(){
//callback code
alert("Done!");
}
});
using ajax call, you can send values to another php file, in case of same file needs to use condition needs to be checked.but best is to pass parameters to another file for pressing.
Where you wanted to use/why you wants those on same page?
You could use jQuery.get(). The syntax is easy
function success_callback(p) {
lat = p.coords.latitude.toFixed(2);
lon = p.coords.longitude.toFixed(2);
var coords = {
lat: lat,
long: lon
};
$.get('mypage.php', coords, function () {
alert('data sent');
});
}
And in your PHP script, you use the $_GET
$lat = isset($_GET['lat']) ? $_GET['lat'] : 0;
$long = isset($_GET['lat']) ? $_GET['long'] : 0;
javascript:
$.get('index.php?lat='+ lat + '&long=' + lon)
php:
$lat = isset($_GET['lat']) ? $_GET['lat'] : 0;
$lon = isset($_GET['lat']) ? $_GET['long'] : 0;
If your current page is named index.php.
Keep in mind the current page is going to process again unless you specifically program your php not to. You asked to send it to the current page, though, so that is what this does.
Related
I've just started learning Jquery and I'm trying to post and retrieve some data with Ajax. The data that i wanna extrapolate is some simple text (no json), more specifically numbers. So I wrote this:
$.ajax({
url : 'finproj.php',
type : 'POST',
data : 'p=' + devidproj,
success : function(resultaat) {
var lengtebalxkx = Math.floor(100*resultaat/<?php echo $number; ?>);
$(".ongelezendonatiesproj").animate({opacity:1}, 300).show();
if(lengtebalxkx > 120)
{
$(".ongelezendonatiesproj").width(120);
}
else
{
if(lengtebalxkx < 1)
{
$(".ongelezendonatiesproj").width(2);
}
else {
$(".ongelezendonatiesproj").width(lengtebalxkx - 10);
}
}
},
});
devidproj is a number, as is $number. I tried adding dataType : 'text',
But that didn't work.
The php-file which I'm trying to retrieve the data from, is:
<?php include('config.php');
$pid = $_REQUEST['p'];
$nieuwgeld = mysql_query('SELECT bedrag, aantal, projectid FROM donaties WHERE projectid="'.$pid.'"');
while($nieuwebed = mysql_fetch_assoc($nieuwgeld)) {
$plusbedrag = $nieuwebed['bedrag'] * $nieuwebed['aantal'];
$nieuwebedragen = $nieuwebedragen + $plusbedrag;
}
if($nieuwebedragen<>0) {echo $nieuwebedragen;} ?>
The php-file works fine.
I think I missed a comma or something in the Jquery-script but I can't seem to see what's wrong with it :s I've tried debugging it with alert() but that didn't work.
use
data : {p:devidproj},
insted of
data : 'p=' + devidproj,
Use the following data on your ajax request:
data : {p: devidproj}
Note that there should be no quotes on p.
You should also parse the result on your Ajax request as integer thru parseInt() function since that's suppose to be a number. JS will parse it as string by default if not added.
var lengtebalxkx = Math.floor(100*parseInt(resultaat)/<?php echo $number; ?>);
So, heres a super simple jQuery / AJAX comment system step one. Step two is the PHP to insert the data into the DB. I need the $_GET['variable'] for the page / a $_SERVER['variable'] to store into the DB. How can I get these in the jquery. I can't just say $spot = $_GET['spot'] or $url = $_SERVER['FILE_SCRIPTNAME'] in the PHP. It won't pick it up. I has to be sent through the jQuery / AJAX. How can I do this?
$(document).ready(function() {
$('#submit_comment').click(function() {
var comment = $('#place_comment').val();
// Somewhere here set the $_GET['variable'];
$.ajax({
type: 'POST',
url: 'http://localhost/app/comment/comment.func.php',
data: 'comment='+comment,
success: function(data) {
$('#replies').html(data);
}
});
});
});
If I understand what you are trying to do correctly, you can try something like this to use server-side PHP variables in your client-side javascript.
var comment = $('#place_comment').val();
var myVariable = '<?php echo $_GET['variable'] ?>';
You can't do this like this : javascript is client-side and PHP $SERVER array is server-side.
Disclaimer
I have searched for duplicates, but I can't seem to find them. I am surprised because this seems to be a big issue. I most likely am missing something big though.
Problem/Question
I am having the userid passed into through the url via php, myOtherScript.php?userid=1. How can I get that variable to be passed via ajax so that I may query the database with that userid, echo it out and return it to the page?
This is in global.js file
jQuery
$.ajax({
url: "myScript.php",
data: "userid=" - This is what I need: $_GET['userid'] - ,
success: function( data ) {
$('#myDiv').html( data );
}
});
Solution
WIth the help of bstakes and this answer, I was able to figure it out with this function: (top answer)
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
Thanks for the answers guys!
$.ajax({
url: "myScript.php",
data: "userid=<?php echo intval($_GET['userid']); ?>",
success: function( data ) {
$('#myDiv').html( data );
}
});
You could also try using the search attribute of the window.location object.
If the url is http://www.mysite.com/display.php?userid=7 window.location.search will return "?userid=7". You will obviously need to remove the leading "?", but be aware that if there are additional GET paramaters, separated with ampersand '&', those will be included as well.
So, with a bit of additional Javascript, you can split on the '&', which gets you an array of "key=val", then you can spilt on the equal sign and create an object with {key : val}. Then you could use that object to access the query string params.
var qs = window.location.search.substring(1),
pieces = qs.split('&'),
i,
qsObj {},
tmp;
for ( var i in pieces ) {
tmp = pieces[i].split('=');
qsObj[tmp[0]] = tmp[1];
}
See https://developer.mozilla.org/En/Window.location for additional information on the window.location.
If you want to keep the JS seperate, put it in a function that accepts the user id...
function do_something(user_id) {
$.ajax({
url: "myScript.php",
data: "userid=" + user_id,
success: function( data ) {
$('#myDiv').html( data );
}
});
}
Then just call do_something($_GET['user_id']);
You might have to move the script inline on the PHP file then you echo out the $_GET['userid'] in the data area of your ajax call.
just found this: how to get GET and POST variables with JQuery?
I have decided i'd like to do an ambitious mood change depending on the time of day. I need to get the time and compare it against the sunset and sunrise of any given day.
So far I have found some javascript here that works well. Can anyone tell me how I might give the lat and long to the PHP function date_sunset? I have the IP in a PHP variable using $_SERVER['REMOTE_ADDR'] but that's all I have. I can't really do much else as I have never used the function and never tried to combine PHP and JS. Any ideas?
-- Update --
I have been trying to use the jQuery $.ajax function. Here is my code;
<script language="JavaScript">
var lat = geoip_latitude();
var long = geoip_longitude();
$(document).ready(function(){
//var url = 'http://www.ransomedesign.co.uk/web/?lat=' + lat + '&long='+ long;
// $.get(url);
$.ajax({
type: "GET",
data: { lat:lat, long:long},
url: "http:www.ransomedesign.co.uk/web/",
success: function() { alert("you win"); }
})
});
</script>
There are two different approaches in there. (1st one is commented out). This does populate my $_SERVER php code, but only on the 2nd request of a page for my site. I really need this to process on the first visit before anything loads. After this the value will be stored in a session and php will do the rest.
Can anyone see whats wrong with this code or why it wont work straight away? My php if after this, is that correct?
Many thanks...
Given that snippet there, you'd have two variables, geoip_latitude, and geoip_longitude. Take those variables, put them into an AJAX call to your server, which would then do the calculations:
html:
<div id="sunset"></div>
<script>
$('#sunset').load('/path/to/script.php?lat=' + geoip_latitude + '&lon=' & geoip_longitude);
</script>
php:
<?php
$lat = $_GET['lat'];
$lon = $_GET['lon'];
echo date_sunset(time(), SUNFUNCS_RET_STRING, $lat, $long);
This assumes you've got jquery loaded/available and the server's on PHP v5. I'm also using the server's time, which could be on a different day than the client entirely. Probably won't work out of the box, but should get you started.
I'd use AJAX for this. You use GeoIP JavaScript, so first get lat and long:
var lat = geoip_latitude () ;
var long = geoip_longitude () ;
then send it to server script, for example mood.php:
var xhr = new XMLHttpRequest () ;
xhr . onreadystatechange = function ()
{
if ( xhr . readyState == 4 && xhr . status == 200 )
{
// do something with server response
}
}
xhr . open ( "POST", "mood.php", true ) ;
xhr . setRequestHeader ( "Content-type", "application/x-www-form-urlencoded" ) ;
xhr . send ( "lat=" + lat + "&long=" + long ) ;
and mood.php might looks like:
<?php
$lat = $_POST [ "lat" ] ;
$long = $_POST [ "long" ] ;
echo "something depending on lat and long" ;
?>
edit.
If server sends response, you can read it by calling xhr . responseText:
xhr . onreadystatechange = function ()
{
if ( xhr . readyState == 4 && xhr . status == 200 )
{
alert ( "Server response: " + xhr . responseText ) ;
}
}
If server sends XML content, then you can call xhr . responseXML - it tiggers native XML parser.
https://developer.mozilla.org/en/AJAX/Getting_Started
This question had no answer as such, I ended up getting a PHP module and .dat file installed on my hosting for me. The AJAX did work, but only after a page from my site had been visited - which was no use sadly. Thanks for the help everyone..
Is it possible in the line that begins with $sql = to use the variables that were defined earlier in javascript?
var southWestLat = map.getBounds().getSouthWest().lat();
var southWestLng = map.getBounds().getSouthWest().lng();
var northEastLat = map.getBounds().getNorthEast().lat();
var northEastLng = map.getBounds().getNorthEast().lng();
var coordinatesMap =
<?php
global $wpdb;
$sql = "SELECT user_id, lat, lng FROM coordinates WHERE lat>southWestLat and lat<northEastLat and lng>southWestLng and lng<northEastLng";
$rows = $wpdb->get_results($sql, OBJECT_K);
...
?>;
Since javascript is a client side language if is not possible to directly use them. You can however use AJAX to transfer values of those JS variables to the server. Execute your sql statement and return back the results in some JSON object for example.
HTH :)
Oki so say we have the following in JS
var myvar1 = "HELLO WORLD 1";
var myvar2 = "HELLO WORLD 2";
Now we want to send myvar to the server via AJAX. Here is how.
$.ajax({
type: "POST",
url: "some.php",
data: ({'action' : 'action1' , 'myvar1' : myvar1 , 'myvar2' : myvar2 }),
success: function(msg){
alert( "Data Saved: " + msg );
}
});
The url must be some script that will handle the ajax request. What will be echoed by that script will end up in the msg variable of the success callback.
AJAX Handler
To do this you will need to send an extra parameter with each AJAX request. If you look at the above example I added the action parameter. This will allow us to identify which action should be executed by the AJAX Hander.
ajaxhandler.php
switch($_POST["action"]) {
case "action1":
action1($_POST["myvar1"]);
break;
case "action2":
action2($_POST["myvar2"]);
break;
}
function action1($myvar1){
do your action logic here
}
function action2($myvar2){
do your action logic here
}
PHP runs on the server while JavaScript runs in the client's browser.
So you need to use AJAX to do this - have a look at jQuery's AJAX functions.
no, it's absolutely different things. javascript executes on client side, php code executes on server side. your objective is possible only if you pass your js values to php script via HTTP request