How to use php functions in Jquery. append?
Good afternoon, I implemented a lazy load feed that loads news as the page scrolls. Using a self-written engine on Codeigniter 3.
Everything works, the problem is that in$("#posts").append('');
you need to insert a large layout design mixed with the php functions of Codeigniter itself.
For example, the data array contains the date of the news in the unix_timestamp format.. I try to output it using the native Codeignter function:
$.each(data, function(index, data){
$("#posts").append('<?php unix_to_human( + data.created + )?>');
});
Such the output doesn't work. How can I put such a complex output in append using php tags?
P.S. The full code is given below:
<script type="text/javascript">
$(document).ready(function(){
var inProcess = false;
var num = 15;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height() && !inProcess) {
$.ajax({
url: 'http://домен/lazy/index',
method: 'GET',
data: {"num" : num},
beforeSend: function() {
inProcess = true;
}
}).done(function(data){
data = JSON.stringify(data);
data = jQuery.parseJSON(data);
if (data.length > 0) {
$.each(data, function(index, data){
$("#posts").append(''); // вывод контента тут
});
inProcess = false;
num += 15;
}
});
}
});
});
2 answers
Unfortunately, you can't call PCP functions inside a Javascript after your file has done its full work (i.e., the page has been loaded by the browser).
In your case, I see 2 options for the implementation of the plan:
- Return data from the server that has already been converted in the desired way (the recommended method, the server is needed for this);
- Duplicate the PCP functions you use in Javascript and call them.
In your example, the php code is executed, but not output to the browser. Try adding an output function.
$.each(data, function(index, data){
$("#posts").append('<?php echo unix_to_human( + data.created + )?>');
});
If that's what you need. But it is better to implement a separate php script to generate the necessary layout dynamically and already access it.