PHP inside JavaScript - php

I have one line of JavaScript that I'd appreciate help with.
req.open("GET", 'update.php?id=<?php $id ?>', true);
Where $id = 12345, I am trying to get the contents of update.php?id=12345.
Using PHP inside this JavaScript doesn't seem to be working for me.
Any suggestions?

First, make sure that you are actually inside a PHP file, or have your server configured to process whatever file extension you are using with PHP.
Then, you can echo data directly into the JavaScript. For best compatibility and to avoid potential XSS vulnerabilities, always JSON-encode the data.
req.open('GET', 'update.php?id=' + <?php echo json_encode($id); ?>, true);
Personally, I prefer to have a block of variables that are assigned over from PHP. this keeps your JavaScript cleaner.
<?php
$options = new stdClass();
$options->id = 12345;
$options->dinnerSelection = 'pizza';
echo 'var options = ', json_encode($options), ';'
?>
// Then later on in your JS...
req.open('GET', 'update.php?id=' + options.id, true);

You have some way to do this.
First one make your javascript file in .php file(be carrefull you need to include it and not to link it in the begin of file.
Second one, in php, you can wrote
<?php
echo '
<script type="text/javascript">
id="'.$id.'";
</script>';
?>
with this, you define a global variable in javascript who take the good value.
Then you just have to wrote after this :
req.open("GET", 'update.php?id='+id, true);
if you have to change the id after requied the page, you just have to change the id javascript value

I believe it would be a very poor design decision to use PHP to format your javascript in this way. You should provide more info about what you're trying to do because I can almost guarantee you that there is a better way to do this.
If you are trying to, for instance, do a javascript call to a URL (clearly), then apply that data to an attribute in the HTML document:
<div id="someExample">
Item 12345
</div>
And then use unobtrusive javascript to access that item when clicked, cancelling the link's default action if necessary. The benefits of this approach are many- you can write reusable code, and you don't have extra PHP parsing to do in a javascript that is going to be extremely hard to understand later.
Adding JS hardcoded data via PHP to a javascript object is a very poor design decision. If you need more help on this let me know, but try researching it more first!

Related

How to secure the php code?

I created now a Javascript Code that get the php variable into javascript code, my issue that the php variable is important and I don't want any can see this variable is there is any way to do that by the way I tried to use obfuscator but it doesn't work because of the PHP code inside the Javascript code, let's say this is my Code,
<?php
$var = "this is impotant";
?>
<script type="text/javascript">
var javaScriptVar = "<?php echo $var; ?>";
</script>
So, is there any way to use PHP variables in Javascript code or hide the result of the PHP code?
Nobody sees the PHP code. But if you expose values into Javascript, they are not secret anymore. There is no way to deal with this. You cannot use the value in Javascript and NOT reveal it.
If you want to keep process data secret on the server, and available for the next request of that user, use a session.
People will only see the value of the variable. They wont know what it is or how important it is supposed to be. Nobody will see the variable name because the PHP code is executed BEFORE the page is sent to the client. Therefore there is no need to obfuscate the value, and you cant anyway since you need the value.
An example. if I use this PHP code in my file
<p>Hello Mr <?php echo $MY_SUPER_SECRET_VARIABLE ?></p>
the only thing people will be able to see in the source when the page loads is
<p>Hello Mr Bond</p>
The same rule applies if it is placed in Javascript
First you need to understand that Javascript is executed on the client side, every piece of code and variable are in some way accessible by someone with some programming background.
Although you can obfuscate the source code and encrypt the variable to make it harder to read, there is no 100% protection when things happen on client side.
who wants to get the value, will get it. but you can
dynamically inject them via ajax
encode (base64 etc.) the value
obfuscate the code
PHP files will be interpreted into static (like html or xml format) file, means that all variables will be replaced with certain values.What users see is static, no php code displayed but just interpreted text.

Equivalent of PHP's dirname(__FILE__) in JavaScript?

as I already mentioned in the title, I'm looking for a JS-function for getting the same result like I get with this PHP code:
dirname(dirname(__FILE__))
Thanks in advance!
I don't think it is possible because php dirname operates on apache server on local machine. It has access to the filesystem. But javascript operates on browser layer which can't operate with filesystem. I think so you should use ajax and proccess result how you need it. I think so its best solution for you.
I needed a solution to write code like this:
$("#div").load(ROOT_URL + "my/path/to/script.php");
Solution: a PHP script generates one JS-file of all needed JS-files and adds the ROOT_URL to the top of the generated file:
$js = 'ROOT_URL = "' . ROOT_URL . '"; ' . $js;
file_put_contents("file.js", $js);
Now I'm able to use the ROOT_URL (set in a PHP config-file) in JS-code as well. I hope I could help.
You can have PHP output the script. Yes, that's right, you probably can't make php process js files (unless you are in full control of the server). But it doesn't matter. Just make sure that the MIME type is correct, both in the headers PHP returns and the script tag. That way, you can have PHP insert the any values you want in the script, including it's own path.
In script.php:
header("Content-type: text/javascript");
echo 'var myvar = '.$something;
//where $something can be $_SERVER['REQUEST_URI'], __FILE__ or whatever you need.
//You could even use information from session variables, or query the database.
//In fact, this way you can have GET parameters in your javascript.
//Make sure you are not creating a vulnerability with the exposed information.
//Then put the rest of the script as usual. You could even include it*.
*: include
In HTML:
<script type="text/javascript" src="script.php"></script>
Yes, I know I'm repeating the MIME type, do it this way to maximize browser compatibility.
There's no analogue of __FILE__ in browser Javascript; the code does not have direct access to the URL from which it was loaded. But with certain assumptions you can figure it out, as in the answer here.
Once you have the URL of the script (I assume in a variable called scriptURL below) you can set about finding the grandparent URL. This can get tricky with URLs, so it's probably safest to let the URL-savvy bits of Javascript parse the URL for you and get just the pathname component before you start with the string-munging:
var a = document.createElement('a')
a.href = scriptURL
var scriptPath = a.pathname
Then it's unfortunately down to string manipulation; here's one somewhat clunky solution:
var components = scriptPath.split(/\//)
while (components.length > 0 && !components[components.length-1])
components.length -= 1;
var twoDirsUp = components.slice(0,components.length-2).join('/')
And then you can convert the result back into a full URL using the anchor element trick in reverse:
a.pathname = twoDirsUp;
var grandParentUrl = a.href
Why not load what you want from absolute URL?
If you have inse your block of codes: /my/script/to/load.js browser will load the correct file if you are in yoursite.com or whatever like yoursite.com/a/b/c/d/e/f
A little off topic, but if you just want to get the similar of dirname($_SERVER['REQUEST_URI']) for javascript, you can do
window.location.href.substr(0, window.location.href.length - window.location.href.split('/').pop().length)
I use something like that to free from the paths in javascript
var __DIR__ = window.location.pathname.match('(.*\/).*')[1] + 'NameOfThisFolder';
first
window.location.pathname.match('(.*\/).*')[1]
return the current path without the file name or other stuff.
rootFolder/folder1/folder2/
then I add the name of this folder ('NameOfThisFolder').
In this way, I can make for instance ajax request in current page from a page that was called in turn from an ajax request without worry about the path

how to access PHP variables from within JavaScript?

I want to access PHP(server side file variables) with JavaScript(Client side script) without using MySQL. e.g. i have $name=Tom; How do i access this $name variable in JavaScript? Please show code example as i am new to programming. Thank you.
You could do something like
<script>
php_variable = <?= json_encode($php_variable) ?>;
</script>
which should even let you do arrays and possibly objects. It requires PHP 5.2 or later, though. If you're stuck without json_encode, you could wrap quotes around a call to addslashes, but that won't let you do arrays and such.
If your intent is to set the value within some form, you can do like
<input type="text" name="stuff" value="<?= htmlentities($stuff) ?>">
and of course, you could access that element's value within your script if necessary.
Two key points to take away here:
Since PHP is generating the page, it can output stuff as it pleases -- even right in the middle of a <script> element. You can use this to transfer variables from server to client, but not vice versa. (Transferring client variables...well...that's effectively going to require XHR or a form submit.)
But always* escape stuff going from PHP to anywhere -- particularly if it's going into HTML, JS, or directly into SQL. Unless you have your server set all retarded (enabling magic quotes, for example), PHP will get the data raw, and it could have special chars that will cause one or all of those to break.
* Ok, not quite always. If you have a PHP variable that contains some HTML or JS you want to output as HTML/JS, then don't escape it. But you should be aware of what "XSS" means, and don't blindly output data supplied by a user.
Since javascript is client side and php is server side, you would need to use ajax(javascript) to access server side session variables(php). I would recommend researching jquery's ajax framework.
you can do this simple things.
function reset1()
{
//document.frmadd.intFaqCategoryTypeID.value='1';
document.frmadd.reset();
document.frmadd.intChatRoomCategoryId.value='<?php echo $intChatRoomCategoryId ; ?>';
document.frmadd.intEventId.value='<?php echo $intEventId ; ?>';
document.frmadd.intGroupId.value='<?php echo $intGroupId ; ?>';
document.frmadd.intMemberID.value='<?php echo $intAddedByMemberId ; ?>';
return false;
}

jqGrid serializegriddata parsing in PHP

I am extremely new to PHP and, although I am quite familiar to javascript, I am learning how to use the massive jqGrid plugin right now. I am trying to understand how jqGrid serializes the grid data and how PHP parses this data. Currently, I am not even connecting to MySQL, but I am simply trying to echo the serialized jqGrid data as "fake" results. I have the following code for js in the head of my PHP file:
<script type='text/javascript'>
$(function(){
$('#list').jgGrid({
url:'grid.php',
mtype:'POST',
colNames:['json'],
colModel:[{name:'j',index:'j',searchoptions:{sopt:['eq']},search:true}],
pager:'#pager',
rowNum:10,
viewrecords:true,
gridview:true,
serializeGridData:function(postData){
return postData;
}
})
});
</script>
I then send this information to my 'grid.php' file, which has the following code:
<?php
$jason = $_POST['postData'];
$page = $jason->{'page'};
echo '<rows>';
echo '<page>1</page>';
echo '<total>1</total>';
echo '<records>1</records';
echo '<row id="1">';
echo '<cell>'.$page.'</cell>';
echo '</row>';
echo '</rows>';
?>
When I remove the serializegriddata option from the JS, everything works fine (I also add in the default $_POST['page'], $_POST['rows'], $_POST['sidx'], $_POST['sord'] back into the PHP). The problem comes in when I add the serializegriddata.
I am looking for any examples of how to use the postData on the client side (are the any other functions I need to add to the serializegriddata or can I just return the postData) and how to properly parse this in PHP (how to $_POST the data and then how to parse and use this data). I know this is probably an extremely simple solution, but everything I find just talks about the client and says nothing about the server side. Thanks in advance.
Okay, I am a little slow, but I partially answered my own question. All of the jqGrid documentation read as if your entire postData was parsed as a JSON string if you set multipleSearch:true. I thought that I had to parse every variable into a postData JSON variable, then pass this to PHP. Although the solution took a little work to properly implement, the thing that I was missing was the fact that with multipleSearch:true, this adds just a 'filter' variable to the AJAX call. This filter variable is parsed as follows:
$filters = $_POST['filters'];
$json = json_decode($filters,true);
and the result of $filters is:
{"groupOp":"AND","rules":[{"field":"Customer","op":"eq","data":"eosp"}]}
This is as opposed to the multipleSearch:false option of:
$sField = $_POST['sField'];
$sValue = $_POST['sValue'];
$sOper = $_Post['sOper'];
Once I got this, I was able to loop through all instances of my search parameters and create my $where variable. One thing that almost became a big problem for me was the old example I was able to find about properly constructing a (link below) is that you can only have WHERE is a mysql_query only 1 time.
http://blog.brzezinka.eu/webmaster-tips/jquery/how-to-enable-the-search-functionality-in-jqgrid
I hope this might help someone in the future (it drove me crazy for almost 2 days straight).

How can I generate Dynamic Javascript?

I render a page using YUI. and depending on the user I need to change how it is rendered. This change is not something that can be parametrized, it is drastic and different for each user.
Please tell me how can I generate Javascript dynamically?
I personally use a PHP file to pass a JavaScript object made up of some basic session and internal settings, nothing mission-critical as passing information to the client isn't overly secure, but I believe it might follow the same principles as what you are looking for.
Similarly, I use this to display certain elements once the client is logged in, although all the authorization is still done on the server-side. If my session handler gives the PHP file the ok, it outputs a JavaScript object using a PHP heredoc string, otherwise, it doesn't output anything. You can use attributes of this object to compare against, or you could output only the JavaScript for how a certain page should be rendered, based on settings in your PHP file.
HTML:
<script src="common/javascript/php_feeder.php" type="text/javascript"></script>
PHP:
//my session handler authorisation check has been removed
//although you could place your own up here.
//assuming session was authorised
//set content type header
header("content-type: application/x-javascript");
$js_object = <<<EOT
var my_object = {
my_attr: '{$my_attr}',
my_attr2: '{$my_arrt2}',
etc: '{$etc}'
}
EOT;
print($js_object);
You can probably create two separate Java script files, and include the required file, depending upon the user type.
Pseudocode
If user_type is One
<Script src='one.js' type='javascript'></script>
else
<Script src='other.js' type='javascript'></script>
End If
JavaScript has an eval function, so I think (I haven't tried it) that you can generate JavaScript by writing it into a string variable (and then calling eval on that string variable).
A little bit of elaboration here would most certainly help in getting you a more descript and helpful answer. That in mind, though, you could easily just use functions declared inside an if statement to provide distinctly varied experiences for different users.
A very basic example:
<script>
function do_something(userType)
{
if (userType == 'A')
{
// everything you need to do for userType A
}
if (userType == 'B')
{
// everything you need to do for userType B
}
}
</script>

Categories