How do I add a javascript variable to a page after the page loads? I have a PHP ajax function that I need to return a javascript variable. I've tried echoing the variable between script tags and it's not working.
The way I do this, is to create a php document that just echos out the variable, with no markup, and not even any trailing linebreaks.
<?php echo($var); ?>
Then ajax that page, and in the success clause of the ajax call, just do;
success: function(result) { myGlobalJavascriptVariable = result; }
If you don't know the variable name at page load, you could do it this way:
Javascript:
$.ajax({url:'/releventScript.php',
data: RelevantData,
dataType:'json',
success:function(data){
window[data.varName]=data.varValue;
}
});
PHP Script
$response=array('varName'=>'Foo',
'varValue'=>'Bar');
header('Content-Type: text/json');
echo json_encode($response);
exit;
This will allow you to dynamically create variables in the global namespace.
Related
I use DHTMLX. I want to use the ajax component get the data from php, the php will create the xml. How to get this xml data into javascript.
enter code here
dhtmlxAjax.get("php/getUsername.php", function(r){
r = r.xmlDoc.responseXML; // will give you DOM object
//console.log(r.firstChild.tagName);
alert(r.firstChild.tagName("param1"));
});
thank you
Just use the php echo function to echo the php variable into a java script variable.
eg. If you have a php variable called $XMLData you would do the following
var XMLdata = <?php echo $XMLData; ?>
Then on page load your php variable becomes a javascript variable and can be used. from anywhere in javascript provided that the variable is within its scope.
I wanted to use HTML links to change a session variable in PHP. To do this, I set up an HTML "a" tag that would call a javascript function that looks like this:
function changeValue(name){
data = "key='person'&value=" + _name;
$.ajax({
url: www_root + "/funcs.php?func=set_session_var",
type: "post",
data: data,
success: function(data){
console.log(data);
}
});
}
Then, I had the funcs.php script which had the set_session_var function like this:
function set_session_var(){
session_start();
$key= trim($_GET["key"]);
$value= trim($_GET["value"]);
$_SESSION[$key] = $value;
session_write_close();
echo $key;
}
Then, the original php/html page would reload, but it would first load an external page (call it item.php) that settled all of the php session stuff. Looks like this:
session_start()
$session_id = session_id();
$sc = $_SESSION['person'];
However, the $sc variable always shows up as empty, despite the AJAX success function returning the right value. I've checked the session_id's for both scripts, and they are the same. I have also tried to set a session variable in item.php, and it persists. It's just that when I set a session variable using the funcs.php script it doesn't save.
Any and all ideas are appreciated!
You're sending quotes:
data = "key='person'&value=" + _name;
^------^
which means you're effectively doing:
$_SESSION["'person'"] = $value;
^------^-
Note that those single quotes have become PART of the session key name.
Try
data = "key=person&value=" + _name;
^----^--- no quotes
instead.
Is it possible to run a JavaScript function from PHP using an Ajax call.
For example, if I have a html page in php with an ajax call. The ajax post gets sent to a php engine:
index.php
<script>
Ajax.post('http://example.com/ajaxEngine.php', { data: "someData" });
</script>
Then in the PHP engine, can I run a JavaScript function like this:
ajaxEngine.php
<?php
$data = $_POST['data'];
?>
<script type="text/javascript">
var php_var = "<?php echo data ?>";
function doSomething(php_var) {
// do something with data
}
</script>
Lastly, If the JavaScript function needs to return a value, how would you then transfer that back to php? Could I post to the same page and then get it as a variable with PHP?
Short answer: No.
Your code in ajaxEngine.php would just output that snippet of javascript. This will be transfered back to your page, so you could insert it into a script tag or eval it, if you like it to execute. But this would then happen on the client side not on your server. The script would have the dynamic data from the php, though. So if this is everything you need, it would work that way.
Beware: That would NOT hide your script. It would be visible for any client.
Try this function
function includetext(text,onlyone)
{
var d=document.createElement('script');
if(onlyone)
{
var ds=document.getElementById('onlyonesscript');
if(ds)
removeElement(ds);
d.id='onlyonesscript';
}
d.innerHTML=text;
document.body.appendChild(d);
}
text - returing text of script from ajax.
onlyone use for just one script node, this will help you.
ajaxEngine.php
<?php
$data = $_POST['data'];
?>
var php_var = "<?php echo data ?>";
// do something with data
I have a file like "my_js_stuff.js" which is looking like this :
function my_js_function()
{
jQuery.ajax({
url: my_ajax_script.ajaxurl,
data: ({action : 'get_my_comments'}),
success: function() {
//Do stuff here
}
});
This file is included in my
<header>like this: <script type="text/javascript" src="my_js_stuff.js"></script>
I want to call the function from "my_js_stuff.js" inside my php page, and I'm thinking to call it like this:
<?php
<script type="text/javascript>
$('.some-class').on('click', my_js_function()); // this is the function from the js file.
</script>
?>
Is this the correct way to call the function from the js file ?
Thank you !
Is this the correct way to call the function from the js file ?
my_js_function() is certainly the correct way to call it.
But, to pass the function so the event can call it later, you'll want to skip the calling parenthesis:
$('.some-class').on('click', my_js_function);
With them, it'll be called immediately and its return value will instead be passed to the event binding.
Also note that the <script> shouldn't be inside a <?php ... ?> block unless it's in a string being echoed.
<?php
# ...
?>
<script>
$('.some-class').on('click', my_js_function);
</script>
<?php
# ...
?>
You could do that, but I'm not sure that's what you actually want to do. Javascript is executed on the client-side, whereas PHP is executed on the server. Your Ajax function makes a request (client-to-server) and fetches content from the server, such as dynamic content generated from a PHP file.
If what you're describing is really what you want to do, you need to echo your script snippet and enclose it in quotes.
<?php
echo '<script type="text/javascript">/*js content*/</script>';
?>
You're confusing the technologies. Your JS is for the client side (browser) and the PHP is for the server side (business logic).
You cannot call a JS function from inside PHP.
However, assuming you want to communicate JS > PHP, you need to include the JS on your page.
<script type="text/javascript?>
$('.some-class').on('click', my_js_function()); // this is the function from the js file.
</script>
and your URL needs to match the PHP endpoint:
url: my_ajax_script.ajaxurl, // This should be the path of your PHP file
Inside the php file you can get all the info as if it were a normal request:
<?php
echo $_GET['action'];
?>
This will return the $_GET['action'] var to your JS success function:
success: function(data) {
alert('Received: ' + data);
}
Hopefully you can use this information to build what you need.
The jquery code:
$('.up_IMG').click(function() {
if (notLoggedIn()) return false;
alert('Got to here');
});
The function (attempt #1): in quotes:
function notLoggedIn() {
alert('here');
logged_in = "<?php echo json_encode($logged_in); ?>";
alert('Logged in: ' + logged_in);
}
OR json_encoded (attempt #2):
function notLoggedIn() {
alert('here');
logged_in = <?php echo json_encode($logged_in); ?>;
alert('Logged in: ' + logged_in);
}
When attempt #1 fn is called, the first code block's alert displays:
The second code block does nothing.
The PHP variable does exist and has the value zero.
Any thoughts as to what's happening?
If you're calling this code with a 'click', at that point it's too late for PHP to help you asynchronously.
PHP runs when the page is loaded, not after. It's a matter of timing. PHP can never output something that doesn't exist yet, so it will always be blank.
Explanation of Solution:
The question was caused by a misunderstanding of the relationship between PHP and javascript.
Once the page has rendered (that is, inside jQuery's $(document).ready()), all PHP regular variables no longer exist. The PHP super-variables exist (such as $_SESSION, but not $logged_in.
To possible solutions:
Store logged-in value in a super-global: e.g. $_SESSION['logged-in'], or
Use AJAX inside the javascript $(document).ready() to query PHP if the user is logged in, and receive the answer in the AJAX function's success: function.
Simple explanation of AJAX and how it works