perseoclub perseoclub - 3 months ago 25
Ajax Question

Best practices ajax php jquery

I've a (many) doubts about this topic.

I use a file javascript separated from html/php.. and when I call php codes with ajax, in success I use typical function like this:

$('...').on('method', function () {.....});

When I want a variable I must pass it in hidden div, ecc. ecc.

I recently realized that I can directly write the code jquery in php-file, so I can also pass variables or use php-code between js.

$('...').<?php echo ( $a>1 ? "method1" : "method2" ); ?>({.....});
var x = <?php echo $b; ?>;

Where is the swindle? or is correct?



This is correct. You can actually use *.PHP files for just about anything. You can even us them for CSS! The trick here is that HTML doesn't really care about file extensions, what it DOES care about, is the response header. so I can do something like this to load up a style sheet..

<link rel="stylesheet" type="text/css" href="mystyle.php">

Then, as long as mystyle.php sends this header

header("Content-type: text/css; charset: UTF-8");

The browser will take the output as a CSS file. here is a more in-depth example.


You can use *.PHP to output just about any type of file. Including Javascript, PHP, HTML, CSS ect ect. Just make sure you are sending the right header at the beginning of the script! :)