简体   繁体   中英

Can I use php and jQuery in the same file with .php extension

I am new at programming websites and have spent the last month learning jQuery and PHP. I built a website using jQuery, but now realise that i need to use php as well but mainly for the purpose of authentication. I don't want to try to redo the jQuery code in php.

I know that most people recommend separating server-side and browser-side scripts and HTML, but can I use both jQuery and php in the same file for separate purposes with out any conflicts or issues aising? The file extension will be .php and I expect the structure to be along the lines of:

<?php
//php code for authentication 
?>

<html>
<head>
//header code

<sctipt>
//jquery code to control layout including hiding divs and changing the information 
//shown based on conditional statements

</script>
</head>

//other html

Sorry if this is a dumb question, but I would like to know the best way forward before I get too far. I appreciate your help.

Thank you all for your quick responses, much appreciated.

The purpose of the php is so that only people who are logged in can see the page. My current understanding is that authentication can only be done by using cookies (still have to learn about sessions) and that these require a php script. Is there a better method so I don't have to mix the two languages on the one page? or is my method easier and equally valid - even though it's bad practice?

yes .. you can.. just need to make sure , you have all your jquery(javascript) codes inside the <script> tag.... (though it is a bad pratice but you can )...

<?php
 $test="test";
?>

<script>
   var data= '<?php echo $test ?>';
   alert(data);
</script>

Yes. This is possible. You'd write it just like you gave an example. Just test it out ;-)

The answer is yes, you can. PHP is a method of dynamically deciding what mark-up (HTML) to send to the browser, so PHP and HTML are generally intrinsically linked. Furthermore JavaScript is generally intrinsically linked in HTML. Note that this all happens independently of what file extension it came from - your web server sends the result of the script you write, not any file of a given extension.

The principle being that it doesn't matter how the mark-up is generated, once it gets to the browser, it will be executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM