This is my code:
In A Function:
var daaa=document.getElementById('da').value= year+ "-" +month+ "-" +day;
document.form1.bookingsession.focus();
var coords = {
"lat": daaa
};
$.get('bs.php', coords, function () {
alert('data sent');
});
and my php code is:
<?php
$output = isset($_GET['lat']) ? $_GET['lat'] : 0;
print("$output");
?>
And when i print $output i get the value as 0, but actually have to get the value which is on tha variable daaa. Let me know where i made mistake....
Thank you in advance
Try to change
var daaa=document.getElementById('da').value= year+ "-" +month+ "-" +day;
to
var daaa=document.getElementById('da').value + "-" + year+ "-" +month+ "-" +day;
Anyway in such cases yours "number one" action should be check if variable is really set on client side. You can do it through alert(daaa) or console.log(daaa);
change this
var coords = {
"lat": daaa
};
to
var coords = {
lat: daaa
};
you misplaced the double quotes.
http://api.jquery.com/jQuery.get/
example from jquery
//$.get("test.php", { name: "John", time: "2pm" } );
First of all do the action #coramba mentioned,
then modify your javascript code like this:
$.get('bs.php', coords, function (dataThatPhpPrints) {
alert(dataThatPhpPrints);
});
..you will see that it actually returns the value that you have sent to PHP script and PHP scripts returns the print of that.
In order to assure yourself that your scripts prints something modify PHP code to like below:
<?php
$output = isset($_GET['lat']) ? $_GET['lat'] : 0;
print("$output - is response from the PHP!!!");
?>
Now when you run yor javascript, you will get an alert message like
ActualValueOfLATYouSentToPHP - is response from the PHP!!!
Bear in mind, if you want to test your PHP whether it works or not, you cant just simply open it in browser and wait for some magic to happen, as it uses $_GET to get some value meaning you need to provide it as a QueryString with the key being 'lat' :
yourhost/bs.php?lat=someTestValue
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; ?>);
Greetings Stackoverflow
How do I set the php $_GET[] array from Jquery? I have a string looking simmilar to this: $sample_string = "Hi there, this text contains space and the character: &";. I also have a variable containing the name of the destination: $saveAs = "SomeVariable";. In PHP it would look following: $_GET["$SomeVariable"] = $sample_string;.
How do I do this in Jquery?
Thanks in advance, Rasmus
If you're using jQuery, you'll have to set up an AJAX request on the client side that sends a GET request to the server. You can then pull the data you supplied in the request from the $_GET[] array on the server side.
$(function() {
var data = {
sample_string: "hi",
saveAs: "something"
};
$.get('/path/to/script.php', data, function(response) {
alert(response); // should alert "some response"
});
});
And in script.php:
<?php
$sample = $_GET['sample_string']; // == "hi"
$saveAs = $_GET['saveAs']; // == "something"
// do work
echo "some response";
?>
Can't tell if you're looking to grab a GET param from javascript or set a GET param from jQuery. If it's the former, I like to use this code (stolen a while back from I can't remember where):
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
Then you can call
var cake = urlParams['cake'];
To get the $_GET param specified by http://someurl.com?cake=delicious
If you want to send a $_GET parameter, you can use either jQuery's $.get() or $.ajax() functions. The $.get function is more straightforward and there's documentation on it here http://api.jquery.com/jQuery.get/
For $.ajax you would do something like this:
var trickystring = "Hi there, this text contains space and the character: &";
$.ajax({
url:'path/to/your/php/script.php',
data: {
'getParam1':trickystring,
'getParam2':'pie!'
},
type:'GET'
});
Now in PHP you should be able to get these by:
$trickystring = $_GET['getParam1'];
$pie = $_GET['getParam2'];
Hope these examples GET what you're looking for. (Get it?)
if $sample_string is what you want in jquery, you can do
var sample_str = '<?php echo $sample_string; ?>'; and then use the js variable sample_str wherever you want.
Now, if you want to do set $_GET in jquery, an ajax function would be way to go.
$.ajax({
url:'path/to/your/php_script.php',
data: {
'param1': 'pqr',
'param2': 'abc'
},
type:'GET'
});
Do you mean that would look like $_GET[$saveAs] = $sample_string y think.
$_GET is a variable for sending information from a page to another by URL. Its nosense to do it in jQuery that is not server side. If you want to dynamically set the $_GET variable to send it to another page you must include it in the URL like:
/index.php?'+javascriptVariable_name+'='+javascriptVariable_value+';
$_GET is just a URL parameter. So you can access get like /index.php?id=1:
echo $_GET['id'];
Look at this article, it shows all the ways to load stuff with ajax:
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-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..
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.
Here is what I want to do:
I have some json like this
var foo = {
format:"json",
type:"test",
id:"26443"
};
and I awant to put that in a url like this
'http://example.com/a:3:{s:6:"format";s:4:"json";s:4:"type";s:4:"test";s:2:"id";s:5:"26443";}'
which I will then put into ajax call but everything I have tried results in error 501 BAD URI could someone tell me how to do this
I've tried this
EDIT:
after looking again and alerting the results of this function it IS build the results correcty they just arrn't being used propler either by ajax or the browser
function js_array_to_php_array(a) {
var a_php = "";
var total = 3;
for (var key in a){
total;
a_php = a_php + "s:" + String(key).length + ":\"" + String(key) + "\";s:" + String(a[key]).length + ":\"" + String(a[key]) + "\";";
}
a_php = "a:" + total +":{" + a_php + "}";
return a_php;
}
when I use http fox it get this back
http://example.com/a:3:%7Bs:6:%22format%22;s:4:%22json%22;s:4:%22type%22;s:4:%test%22;s:2:%22id%22;s:5:%2226443%22;}
which i find odd because it ecodes everything but the last curly bracket
Why not just use a "normal" query string?
http://example.com/?type=test&id=26443
$type = $_GET['type'];
$id = $_GET['id'];
Unless I am missing something?
There is a jQuery function for this already! Use it and love it.
http://api.jquery.com/jQuery.param/
so as it turns out there is nothing wrong with the function js_array_to_php_array it did exactly as I needed it to the problem was that I needed to use JSONP instead of JSON when running my ajax call as I was going cross domain which also explains why the code worked in the url but not when I ran ajax
thank you all for your help
http://example.com/a:3:{s:6:"format";s:4:"json";s:4:"type";s:5:"test";s:2:"id";s:5:"26443";}
501 is right — that's not a valid URL. URLs definitely can't have quotes in them, or (for most part) curly brackets.
If you really have to submit a PHP literal structure in a URL without doing it as normal set of query parameters, you would have to URL-encode the invalid characters, which you can do like:
url= 'http://example.com/'+encodeURI(js_array_to_php_array(foo));
resulting in:
http://example.com/a:3:%7Bs:6:%22format%22;s:4:%22json%22;s:4:%22type%22;s:5:%22test%22;s:2:%22id%22;s:5:%2226443%22;%7D
incidentally this:
String(key)
is superfluous: object keys are always strings in JS, even if you put them in as numbers;
"\"" + String(a[key]) + "\""
is going to go wrong if the value can contain a quote or backslash, and
total;
there should surely be an increment here?
On the PHP end, you could use urlencode(json_encode($obj)) to convert an object to a string that can be used in a URL.
After I posted this, I realized you're trying to convert a JavaScript variable to a URL string after I saw var foo = {. Duh.