Use $_GET, $_SERVER variables in Javascript (jQuery / AJAX) - php

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.

Related

Pass json decode variable to php

I have a JQuery login request as follow using Json encode / decode:
$('#btn_signin').click(function(){
var parameters = $('#signin_form').serialize();
$.ajax({
url: baseurl + 'site/loginRequest',
type: 'POST',
data: parameters,
dataType: 'json',
success: function(output_str){
if(output_str.usertype == "a"){
var sess_email = output_str.email;
window.location.replace(baseurl + 'site/page_a');
}else if(output_str.usertype == "b"){
var sess_email = output_str.email;
window.location.replace(baseurl + 'site/page_b');
}else{
$('#result_msg').html(output_str);
}
}
});
});
As seen on the script with var sess_email how can I pass it to php variable?
Any advise? thanks.
I'm not sure whether I understand this right, but if you want to assign the value of a PHP variable to a Javascript variable you could do something like this:
var sess_email = <?php echo $someVar ?>;
If your looking for the other way around, passing a var from Javascript to PHP, then this is the way to go:
Send it to the server using an AJAX request (I usually JSON encode it then).
JSON decode it on the server and assign it to a PHP variable
Example:
In your case you sended the javascript variable 'parameters' to the server. Then server side you would do this in PHP:
$parameters = $_POST['parameters'];
You can't pass javascript variable to PHP variable. But some workarounds available.
What you are trying to do exactly?

Jquery set PHP $_GET array

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/

How to go from php to js to use the vars defined there?

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

Building dynamic poll with jquery, php and html

Okey, this is what I've got.
<?php
$options[1] = 'jQuery';
$options[2] = 'Ext JS';
$options[3] = 'Dojo';
$options[4] = 'Prototype';
$options[5] = 'YUI';
$options[6] = 'mootools';
That is my array, but I'd like to make it a bit more dynamic so that the array is built according to input id, so he won't have to change the php-code whenever he want's another poll. How would I import those input id's and push them into an array?
To the extent I can understand your question, you could use JSON to pass the data from the client to the server like this:
JAVASCRIPT (using jQuery):
var arr = [];
arr.push("option1");
arr.push("option2"); // and so on..
//Use AJAX to send the data across ..
$.ajax({
url: 'poll.php?jsondata=' + encodeURIComponent(JSON.stringify(arr)),
success: function(data) {
// response..
}
});
});
I think that PHP script will put those options into a database or something for using it later on.
Now, in PHP(poll.php):
<?php
$options = json_decode($_GET['jsondata']);
//...
?>

PHP + Jquery - pass value through ajax to php and check against variable

I can't get the following PHP + jQuery to work - all I want the script to do is pass the value through ajax, and get the php to grab it, check it matches and add 1 to score.
This is the code I've written:
<?php
$score = "1";
$userAnswer = $_POST['name'];
if ($_POST['name'] == "145"){
$score++;
}else{
//Do nothing
}
echo $score;
?>
<script type="text/javascript">
$(document).ready(function() {
$("#raaagh").click(function(){
var value = "145";
alert(value);
$.ajax({
url: 'processing.php', //This is the current doc
type: "POST",
data: ({name: value}),
success: function(){
location.reload();
}
});
});
});
</script>
<p id="raaagh">Ajax Away</p>
Thanks for the help, I've changed GET to POST in both instances, and no joy - there's something else wrong.
First of all: Do not go back to the dark ages... don't use the same script to generate HTML and to respond to an ajax request.
I can't make any sense of what you are trying to do... Let me change your code so it at least makes some sense and document what's going on. It seems like the problem is the fact that you are calling location.reload from your success handler.
// ajax.php - Outputs 2 if the name parameter is 145, 1 otherwise (????)
<?php
$score = "1";
$userAnswer = $_POST['name'];
if ($_POST['name'] == "145"){
$score++;
}
echo $score;
?>
// test.html
<script type="text/javascript">
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
// Why were you reloading the page? This is probably your bug
// location.reload();
// Replace the content of the clicked paragraph
// with the result from the ajax call
$("#raaagh").html(data);
}
});
});
});
</script>
<p id="raaagh">Ajax Away</p>
You use POST in your jQuery, but you try and get a GET in you php.
BTW it is good practice to check if a GET/POST variable is set before reading it.
using the isset() function.
Replace $_GET with $_POST and there you are.
Basically POST and GET are two different way to pass variables to a script. The get method in php can also be attached at the end of a url : script.php?variable=value and it is really easy to hack. While the post method can be submitted with forms or ajax calls and it is pretty safe, at least more than the get.
Also i'd suggest you to check whatever a GET or POST variable is set before calling it, so that you can prevent stupid notice errors.
Just use the following code:
if (isset($_POST['var']) and !empty($_POST['var'])) { // do something }
You can also delete the
}else{
// do nothing
}
part of the script, since the else clause it is not necessary always.
You're submitting the data with an Ajax POST, but trying to read it out of a GET. Either use type: "GET" in your Ajax call or $_POST['name'] in your PHP.
The problem is you are using jQuery to POST your value, yet you are reading it with GET.
You should be able to fix your problem by changing your $_GET['name'] to $_POST['name']

Categories