Pass Javascript variables to PHP functions?
Hello
How can I do something like this:
<script type="text/javascript">
var one="hi ";
var three="there";
<?php echo ConcatTwoStrings(?>one<?php,?>two<?php);?>;
</script>
That should produce "Hi there". Yes, I know there is concat Javascript functions; Thats not the point as I was simply showing a easy example.
How can I do the above?
Thank you
Related Article: pass javascript var to php?
is a PHP discussion thread by dyingatmidnight that has 2 replies and was last updated 1 year ago.
riahc3
1,311 posts since May 2008
Reputation Points: 60
Solved Threads: 13
Skill Endorsements: 11
PHP is server Side script and Javascript client-side.So You can't do this.But you can use AJAX to call a PHP function from Javascript.
Great :) How do I do this?
I currently have this:
PHTML:
<script type="text/javascript">
$j(document).ready(function()
{
var variablecalle=$j("#listadetiendas").val();
var currentSessionID = "<?php echo session_id(); ?>";
var data='calle='+encodeURIComponent(variablecalle)+'&ses='+currentSessionID;
$j.ajax({
url: '../../updatesession.php',
type: 'POST',
data: data
}).done(function(data){
$j("#currSess").html(data);
$j("#currSess").html( $j("#currSess").text() );
var wrap = $j("#currSess");
var text = wrap.text();
wrap.replaceWith(text);
});
});
</script>
Now here is the problem: I cant access that PHP object/function in a AJAX call.
updatesession.php:
<?php
require 'C:/folder/app/Mage.php';
Mage::app();
Mage::getSingleton('core/session')->setTest($_POST['calle']);
?>
When I access the getter, it shows null. I think its because the PHP object isnt passed so how could I pass it (and later return it)?
riahc3
1,311 posts since May 2008
Reputation Points: 60
Solved Threads: 13
Skill Endorsements: 11
PHP objects are not persistent. On ajax call, the server accepts info without any hangover - i.e. info from previous server actions. Session data is available though, but that's hardly the same as the data is usually in a file (or DB). You can set objects to be persistent, but that's a pretty big consideration. PHP is build up, tear down. So, without object persistence or storing the state of dead objects in sessions, you need to create all your objects from scratch.
diafol
Keep Smiling
10,826 posts since Oct 2006
Reputation Points: 1,675
Solved Threads: 1,532
Skill Endorsements: 61