0

Is there any way to do it without doing this: send javaScript variable to php variable

OR can I do that, and "cover up" my url to the original one, without refreshing the page(still keep the php variables)?

Community
  • 1
  • 1
Rhyder
  • 101
  • 2
  • 14
  • 6
    PHP runs on the server. Javascript runs on the client. PHP has **ONE** opportunity to directly inject data into javascript, and that's when the page is generated on the server. After that, your only option is to use AJAX to fetch updated data in the background. – Marc B Aug 13 '13 at 18:12
  • So can I do it with an Ajax form that refreshes the page on success and sets the php variable, without changing the url? – Rhyder Aug 13 '13 at 18:18
  • ajax runs in the background. it's a bog-standard full-blown HTTP request. it's nothing magical - it just happens to run in the background without interfering with the user experience, unlike a non-ajax normal form submission/link clicking would. – Marc B Aug 13 '13 at 18:19
  • Use ajax to request a json serialized object/array and than use the ajax response handler to decode the json object and fire some sort of event within js. – JSON Aug 13 '13 at 20:26

5 Answers5

0

I believe you are incorrect - you actually DO get the 'javascript' variable to PHP - using the jQuery code snippet below by @MikeD (jQuery is a javascript library containing many and many functions that you can then use in your code - making things little easier to do) above you can pass the javascript variable to PHP page.

On the php page you can assign this variable (originating on client side - browser) to PHP variable using something as simple as this:

$variable = $_REQUEST['javascriptVariable'];

TomasH
  • 148
  • 1
  • 7
0

A nice and easy way to do this is like this:

PHP

<div id="something" data-info="<?php echo $info ?>"></div>

Jquery

var info = $("#something").data("info");

EXPLANATION

Put the variable as a data attribute in some div using PHP, and then grab the data attribute from the DOM using JQuery.

bzupnick
  • 2,646
  • 4
  • 25
  • 34
0

You would want to wrap a lot of security around this code before putting it anywhere you care about, but it illustrates the principles without putting too much mud in the water:

<head>
<script>
function loadDiv(url)
{ 
        $('#YourDivID').load(url);
}
</script>
<body>
<?php
$thisID = 1; //set here for demonstrative purposes.  In the code this was stolen from, a MS SQL database provides the data
$thisGroup = "MyGroup";
$thisMembers = "TheMembers";
$thisName = "Just a example";
echo "<button onclick=loadDiv('http://siteonyourdomain.com/yourpage.php?ID=$thisID&group=$thisGroup&members=$thisMembers');>$thisName</button>";    
//note this only works for sites on the same domain.  You cannot load google.com into a div from yoursite.tv
//yourpage.php would have some code like this
// if(isset($_GET['thisID'])) {$myID = $_GET['thisID']} else {$myID = NULL}
?>
<div id="YourDivID">
Before
</div>

<?php 
//I tested this code before posting, then replaced the domain and page name for security's sake
Lumberjack
  • 488
  • 4
  • 13
0

There's two points that you can use PHP to create javascript vars, the first being when the "page" is created on the server, the second point is during the operation of the javascript application (once the page is loaded). The second point will require some sort of client side request (ajax, websocket, etc).

The best way to do it (in my experience) is using PHP's json extension which allows you to encode a PHP object/array into a json serialized string that can be unserialized/decoded within the browser into equivalent javascript types.

To do this during page generation can be done similarly as follows:

echo "jsvar = eval('('+".json_encode($phpvar)."+')')";

Note that the eval occurs on client side within browser and is common in every major js library.

Requesting an object during the normal operation of your javascript app will vary depending on how the data is requested, but each way will involve an asynchronous javascript request, a PHP script to handle the request (on the server side), and then a javascript side handler/callback that is called when data is received within javascript as a response to the request.

I typically use PHP to echo a json_encode()'ed string as plain text, then code the javascript side response callback to decode the response and fire an event. For a basic example:

PHP side:

<?php echo json_encode($responce_object); // DONE ?>

javascript side:

on_responce(responce) 
{    
    var res_obj = eval('('+responce+')');
    fire_event(res_obj);
}

The example above is very simple and generic to show how it works, but not much more is required for a fully functional solution. The real magic for a specific solution will happen within the "fire_event()" method - this is where the object can be handled via jquery or whatever.

JSON
  • 1,819
  • 20
  • 27
-1

If you use $.ajax to make the submission to php you won't need to refresh the page. The code for the example on that page would look like this

var javascriptVariable = "John";

$.ajax({
    url: '/myphpfile.php',
    type: "GET",
    dataType: "json",
    data: {
        name: javascriptVariable,
    },
    success: function( data ) {
        // do success function here
    },
    error:function( xhr, ajaxOptions, thrownError ) {
        // handle errors here
    }
}, "json");
MikeD
  • 372
  • 1
  • 10
  • Yes @MikeD, but I still don't get my javascriptVariable into a php variable. – Rhyder Aug 13 '13 at 18:35
  • If you need to get the variable from javascript into PHP this way, you just need to have myphpfile.php pull it from $_GET['name']. – MikeD Aug 15 '13 at 17:48