Using PHP variable and use it in Jquery/Ajax page load request - php

Let's say I have set up a PHP variable like this:
$phpurl = $_GET["url"]
where url value will be from GET variable query. The value of "url" will be some sort of html page link with some content like "myContent.html" I want to load.
How can I get this "url" value, which I have assigned to the variable "$phpurl"
and use it in the Ajax/Jquery page load request?
$('.content').load(' ** need the value of "$phpurl" to be placed here ** ');
Hope the question is clear. I am pretty new into programming. Thanks.

EDIT:
$('.content').load('<?php echo json_encode($phpurl); ?>');
will do

You'll want to take precaution to escape the value properly
<script type="text/javascript>
var url = decodeURIComponent('<?php echo rawurlencode($phpurl) ?>');
</script>
Or you could try something like https://github.com/allmarkedup/jQuery-URL-Parser
// requires no PHP at all!
var url = $.url(window.location).attr('url');
$('.content').load(url);

As a generic rule you should properly escape variables when you move them between two realms, in this case from PHP to JavaScript.
This is especially true if you don't have full control over the variable contents, such as those coming from $_GET, $_POST, etc.
This is a safe bet, using json_encode() to form a proper JavaScript value:
$('.content').load(<?php echo json_encode($phpurl); ?>);

Related

Call php value in javascript

I'm a bit of a newbie when it comes to Javascript and I am trying to find a way that I can pass a php value into a javascript/jquery function.
<script type="text/javascript">
$(document).ready(function() {
$('div#audit_admin_tabs').slideTabs({
contentAnim: 'slideH',
contentAnimTime: 600,
contentEasing: 'easeInOutExpo',
tabsAnimTime: 300,
buttonsFunction:'click',
tabSaveState:true,
autoHeight:true,
urlLinking:false
});
});
</script>
I have a value call $audit_id, the value for which is from a $_GET from the previous page. I would like to add it to the audit_admin_tabs. I have tried...
div#audit_admin_tabs<? echo $audit_id; ?>
But I realise that won't work because php is server side and javascript isn't. I have also tried echoing the whole function so I can add the php value but that didn't work either.
Thanks
div#audit_admin_tabs<?php echo $_GET['audit_id']; ?>
When you want get a get parameter you make it with $_GET['yourparam']
Greetz
You have the wrong tags. It's <?php ?> ... Not <? ?> ... As Franco has mentioned, you need to use $_GET['audit_id'] (or just use $_REQUEST['audit_id'] because that will take care of getting the value from $_GET or $_POST).
To answer your doubt about javascript being client side but PHP being server side :: Yes your understanding is correct, however in this case first PHP will do its magic so the code inside will get replaced with whatever it should be and then the resulting javascript will be served to the browser. And after that browser will execute that resulting javascript.
So, in short, it should work.

Ajax load content with jquery (URL trigger)

I'm trying to create a demo bar just like wordpress theme companies do
.So far, i was able to achieve a bit of it with
$('#window').load('index.php?action=theme&themeID=5');
Now i want to be able to create specific URLs which trigger specific code.
For example, the above mentioned code runs if i go to
http://mysite.com/theme.php?id=5
How do i do that? is there any way to do the same with php?
Easily done with PHP, you just have to echo the $_GET['id'] value inside your script:
echo "<script type='text/javascript'>$('#window').load('index.php?action=theme&themeID=".$_GET['id']."');</script>";
or
<script type='text/javascript'>
$('#window').load('index.php?action=theme&themeID=<?php echo $_GET['id'] ?>');
</script>
Reference
And yes, GET parameters are unsafe, just as POST parameters may also be manipulated. You should valid to check if the parameter being passed is valid in your PHP page beforing echoing it directly to your script.
From what I gather you are trying to dynamically change javascript based on the url of the page?
<script type='text/javascript'>
$('#window').load('index.php?action=theme&themeID=<?php echo $_GET['id']; ?>');
</script>
You might want to cast the value to an int or something though in order to secure things a bit.

how to pass a php values to javascript?

here is the code??
posting code:
$.post('get.php',{selected:"aaaa"},function(return){alert(return);});
when i check the values of "selected" value using
<?php
$r=$_POST['selected'];
echo $r;
?>
is displays the value "aaaa" correctly..
this code works fine...
<?php
$r=$_POST['selected'];
?>
var answer="<?php echo "welcome" ?>";
when we echo the value"welcome" it is stored in the variable answer.and i could print that...
but when i put like this....
<?php
$r=$_POST['selected'];
?>
var answer="<?php echo $r ?>";
an empty value is stored in answer... and nothing gets displayed....
whether specifying $r inside " " is not right... how to specify that......
Assuming that the php code you are showing, is located in get.php, there is no use of using javascript in that same file. If you want to get the returned value in a javascript variable in your page, you need to use the first php snippet and use the return value in your .post function:
javascript in original page:
$.post('get.php',{selected:"aaaa"},function(data){
var answer = data;
});
get.php
<?php
$r=$_POST['selected'];
echo $r;
?>
$_POST['selected'] is probably empty to start with. Make sure you're sending a nonempty value for selected, and that you're using POST. (The easiest way is to look in your browser's developer tools for the initial request).
Note that directly outputting user input into the page introduces a Cross-Site Scripting Vulnerability: The input "; alert("evil"); can show that. Assuming you're using UTF-8 all around, you can write:
var answer = <?php echo json_encode($_POST['selected']); ?>
Also, there are often better ways to transfer data from php to JavaScript, including XHR requests/JSON or data-* attributes.

grabbing POST values with javascript

Forgive me for asking a seemingly obvious question, but all of my searching is turning up guides on how to create POST values with JS, not how to grab (and utilize) them.
What I want to do:
step1.php -- form POSTing to step2.php
step2.php -- also a form, JS grabs one particular POST value and does some work with it, then updates this new form accordingly
for reasons not worth getting into, the process needs to be a 2 step//2 page process.
The obvious solution is just to do something like:
<script type="text/javascript">
function damn_ugly () {
var shameful = <?php echo $_POST['desiredDatum']; ?>;
do more stuff...
}
</script>
but that seems a bit dirty to me.
Is there a better way? or is that really how I'm supposed to do it?
var postData = <?php echo json_encode($_POST); ?>;
You can obviously change that to include only certain fields from $_POST by passing a custom array to json_encode.
var desiredDatum = <?php echo json_encode($_POST['desiredDatum']); ?>;
There is no nicer way to do it - and using json_encode ensures no matter what's contained in the POST variable nothing will break (at least not during the assignment).
That is how you are supposed to do it, JavaScript cannot access the POST values in another way.
Offcourse you can make it a bit more beautiful: have your php-script put the POST variables in an array, and print the array in JSON format. Now your javascript has the array.
POST values are being sent to the server. Once submitted only the server can work with those values. Your example is pretty much the only option you have to "access" POST values that have been sent to the server in the previous request.
JS has no access to POST values, it can only retrieve GET values. However, since you're using a PHP script and you're able to pass the data to JS - why not give your JS functions data in JSON format? You can use PHP's json_encode function to encode all POST values to JSON that you can use then easily in your JS code.
Try this
On second step Page 2:
Set hidden text box on page:
<input type='hidden' name='text1' id = 'text1' value='<?php echo $_POST['desiredDatum']; ?>' />
Now if you use jQuery the wirite below given code
$(document).ready(function() {
var shameful = $('#text1').val();
});
if not using jQuery Then
var shameful = document.getElementById('text1').value;
I hope this is what you are looking for.

What is the best practice to pass many server side information to JavaScript?

Let say that I have many Javascript inside pages. At this moment is pretty easy to initialize variable by simply using some Print/Echo statement to initialize JavaScript value.
Example: var x = <?php echo('This is a value');?>
I first thought that I could pass all variables value by parameter of function BUT it's impossible because we have a lot of values (we have a multilanguage website and all text are from the server (BD)).
Example : initializeValues(<?php echo('Value1,Value2,Value3,Value...');?>);//JS Method that can be external of the page
More problem come when we want to take off all JavaScript from pages to move everything on external JavaScript file. What would be the good way to initialize all those variables? If I bind the JavaScript methods by using OnLoad of the document I won't be able to use Print/Echo method to populate all values.
Any good pattern to resolve this task?
A very popular pattern is the use of the JSON format. There are libraries to produce it, and Javascript directly consumes it.
With php you can create an associative array then using json_encode you can serialize it for output on the page between some script tags.
for some examples on doing that you can look at http://www.php.net/manual/en/function.json-encode.php
Here's how I do it:
<?php
$foo = array('bar' => 'gork');
?>
<input id='foo' type='hidden' value='&lt?= json_encode($foo); ?>' />
Then client side (I'm using Prototype) :
var foo = $F('foo').jsonParse();
alert(foo.bar);
var x = <?php echo('This is a value');?>
Er, no, that would end up as:
var x = This is a value
(syntax error.) You want:
var x = <?php echo json_encode('This is a value', JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT);?>
The HEX_TAG escaping in PHP 5.3 avoids problems with the </ sequence appearing in a <script> block. The AMP and QUOT encoding is needed to ensure there are no problem " and & characters when you're putting code in an attribute value delimited by " or a non-CDATA XHTML script block. If you're only ever using a HTML script block (or XHTML CDATA script block) you can get away without them (although they do no harm either).
json_encode will also happily encode an array of values to put in a JS variable, not just a string.
More problem come when we want to take off all JavaScript from pages to move everything on external JavaScript file.
It's a good idea to put all your static code, including code that binds onto event listeners, in an external JavaScript file. However per-page data should still stay on the page, either in appropriate attributes of the document itself (eg. class names for unobtrusive scripting) or in a simple <script type="text/javascript">var data= ...;</script> block with no other code.
best practice? passing values from server to the client-side js is too volatile for a singular best practice.
let's say you use Smarty. then, my best practice is:
<script type="text/javascript">
var limit = Number("{$limit}");
var msg = "{$msg}";
{literal}
// code using the variables
{/literal}
</script>
but I can also see this as a very sensible approach:
function to_js_vars(arrray $jsvars)
{
foreach ($jsvars as $name => $info) {
printf(
"var %s = %s("%s");\n"
, $name
, $info['type']
, $info['val']
);
}
}
where $info['type'] is one of Number, Boolean, and '' (empty string) for everything else

Categories