Ajax load content with jquery (URL trigger) - php

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.

Related

What is the proper way to execute JS?

Is it possible to use JS/JQuery from an external file? If so, what is the best practice?
What is the best practice to call a JQuery function inside a PHP or HTML page?
Here is file.php
echo "<table..";
echo "some code...";
echo "</table>":
<script type="javascript">
$('table').hide().fadeIn(700);
</script>
or:
echo '<script type="javascript">';
echo '$('#foo').toggle("slow");';
echo '</script>';
So, besides a best practice. is any of this possible? I can't seem to make it work from external file or directly.
also from external.js
$(document).ready(function(){ $('table').css({ // code here ... }); });
You can certainly echo jquery (or any html code) directly from PHP
echo '<script type="javascript">
$(\'#foo\').toggle("slow");
</script>';
Your issue in that one was the un-escaped quotes around #foo
I'm not really sure what you meant in the first part of your question, but since you have php I would use this option rather than trying to add jquery into an html file from another javascript file (if that's what you were trying to do)
Both internal and external javascript/jquery code should work.
Make sure you jquery script tag was include in you header/body
If external, make sure to include the external.js script tag after the jquery script tag
Make sure the document was ready first ( $(document).ready() ), and check again the selector either they are exist or not.
For more clean code, no need to echo every single line html code. Just close the php ( ?> ) and write the html as usual.
Please provide as much information as you can so that we know exactly what's the problem was.

Use of PHP code inside Javascript code

Since I know many consider the use of PHP code inside Javascript code bad practice, I wonder how to execute a javascript function provided that a certain PHP variable has a certain value.
This is the way I currently write the code:
<script type="text/javascript">
function execute_this() {
some code;
}
<?php
if(!empty($_SESSION['authorized'])) :
?>
execute_this();
<?php
endif;
?>
</script>
Any ideas how to avoid using PHP inside Javascript in this particular example?
If you don't want to include any PHP code inside the javascript code but want to know the value of a php variable, you have to integrate a communication between the server side (PHP) and the client (JS)
For example you could use a ajax request to call a small php snippet that provides the value in its reply. With that value you can go on in you java script code.
In my opinion you should decide if its worth the effort.
Edit:
In regard to the edited question: If it is important that the JS function is never ever called if the PHP session value isn't present I would stay with the PHP code but would do it that way:
<?php
if(!empty($_SESSION['authorized'])) :
?>
<script type="text/javascript">
function execute_this() {
some code;
}
execute_this();
</script>
<?php
endif;
?>
If you evaluate the value of the session variable in javascript, you have to make sure that nothing bad happens to your code if the provided value was manipulated.
It's a matter of code style. The time your project grows, you will find it increasingly difficult to maintain it or to extend its functionality. A better solution would be to initialize all needed variables in the beginning of the file and to externalize the main JavaScript functionality.
Example PHP:
<script type="text/javascript">
MYCONFIG = {
authorized: '<?php echo $_SESSION['authorized']; ?>',
foo: 'something else'
}
$(document).trigger('init'); // fire init event, you can call it as you like
</script>
Example JS with jQuery (note that i use the custom trigger 'init', you can call it however you like):
$(document).on('init', function() {
function execute_this() {
document.write(MYCONFIG.foo);
}
if(MYCONFIG.authorized) {
execute_this();
}
})
This should be in an external JS file and does not need any PHP tags.
You have to store the php variables somewhere in the html code and then access it.
For example:
<input type="hidden" id="hidval" value=<?php echo $_SESSION['authorized'] ?>/>
then in your js:
var somevar=document.getElementById(hidval).value;
if(somevar==what you want){
execute_this();
}
I think you have some basic design issues, and we are only seeing the tip of the iceberg and can't fully help you.
There is nothing inherently wrong with calling a php function this way, but you have several issues:
1) you cannot separate your js file & allow for caching or cdn
2) while MVC is certainly not "mandatory", it is definitely a good idea to try to separate this type of logic from your "view" - your rendered output
3) I suspect elsewhere you have a massive security hole - if you are setting certain parameters based on whether or not they are "authorized" in their session, this means you are most likely sending back info on which to base a permissions decision in your php code somewhere. Never do that from the page - all data should be "neutral" on the page itself, because you have no control over it.
Give this a read if you are not clear why I say that: http://www.codebyjeff.com/blog/2012/12/web-form-security-avoiding-common-mistakes
There are three possible ways to do it.
Use hidden field and add necessary variable value inside each fields and get those using jQuery.
User jQuery Session plugin and access php session variable.
make a ajax call to php and get response in json format and access response.

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.

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

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); ?>);

Calling a JavaScript function from PHP

I have a php script that is a bit of a mess and after a form entry, I need to get an address, and display it on a google map. The html and php is crammed into the same script so I essentially need to call the JavaScript as the PHP is happening. Is there a way to do this?
Thanks,
Alex
You can POST your from to a different frame (or iframe), so your page would not reload. The response of your PHP file which comes back to that frame can contain JavaScript code, which will be executed. Something like:
echo('<script type="text/javascript"> alert("Executed on client side"); </script>');
No, PHP executed by the server and returns the full response to the browser. JavaScript in the page is then executed by the client.
You can't call Javascript functions from PHP. You can set the Javascript to run when the page loads instead.
What you want is something like this:
<script type="text/javascript"></script>
var userAddress = "<?php echo $_POST['address']; ?>";
doSomethingWithAddress(userAddress);
</script>
If that code is on the page which you are POSTing the address to, it would take the address from the user, and write it into a javascript tag. The PHP will get executed first on the server, before building the HTML document. This new document has the variable available to the javascript.
I don't know how you would go about doing that, but this seems like a good place to start looking:
http://code.google.com/intl/en/

Categories