How to call a php function with parameters using Ajax and JQuery - javascript

Trying to delete a record by using JQuery/Ajax function so that my page will not reload everytime I delete. I have a Movie.php that serves as a model object for Movie and this is where I put the function called delete_movie to delete based on movieId parameter. I have tried to call it inside my Jquery call but it looks like it is not calling my function delete_movie(movieId).
This is my Movie.php
<?php
class Movie {
public static function delete_movie($movieId) {
$db = Database::getDB();
$query = 'DELETE FROM MOVIE
WHERE movieId = :movieId';
$statement = $db->prepare($query);
$statement->bindValue(':movieId', $movieId);
$statement->execute();
$statement->closeCursor();
}
}
?>
movielist.php
<tr class="delete_mem<?php echo $movie['movieId'];?>">
<td><?php echo $movie['title']; ?> </td>
<td><?php echo $movie['releaseYear']; ?></td>
<td><?php echo $movie['imdbId']; ?></td>
<td><?php echo $movie['description']; ?></td>
<td><button type="submit" class="btn btn-danger" id="<?php echo $movie['movieId'];?>">Delete</button></td>
</tr>
JQScript.js
$(document).ready(function() {
$('.btn-danger').click(function() {
var id = $(this).attr("id");
if (confirm("Are you sure you want to delete this?")) {
$.ajax({
type: "POST",
url: "model/Movie.php",
data: {
delete_movie : id
},
success: function() {
alert('Success deletion!');
}
});
} else {
return false;
}
});
});

When PHP is running movie.php, it's just processing the class. The PHP within the file doesn't actually say to do anything.
If you don't need classes, you could just change your movie.php to
$db = Database::getDB();
$query = 'DELETE FROM MOVIE
WHERE movieId = :movieId';
$statement = $db->prepare($query);
$statement->bindValue(':movieId', $movieId);
$statement->execute();
$statement->closeCursor();
If there's more in the file or you must use classes, then you need a controller that receives the url POST, and then calls Movie::delete_movie($id).
You appear to be following the MVC pattern, the model and view you have, and adding this controller to control the actions, would be the final part.

You cannot call PHP code from JavaScript (not easily, at least). Fortunately for you, you can do what you're trying to achieve because you're sending a POST message to Movie.php. All that you have to do now is to handle that POST message in Movie.php.
<?php
class Movie {
public static function delete_movie($movieId) {
$db = Database::getDB();
$query = 'DELETE FROM MOVIE
WHERE movieId = :movieId';
$statement = $db->prepare($query);
$statement->bindValue(':movieId', $movieId);
$statement->execute();
$statement->closeCursor();
}
}
// add this
if (isset($_POST["delete_movie"])) {
Movie.delete_movie($_POST["delete_movie"]);
}
?>
I suggest you don't forget to add authentication. Otherwise, anyone can delete any movie from your database. Try adding a session. That's outside the scope of this question, though.

Related

How to view data from DB with AJAX immediately after script counts it?

I am practising AJAX by implementing editable HTML table looking like this:
The logic is this:
User clicks on left column (containing integer);
JS script catches its value and by using AJAX adds them to database;
PHP script fetches this value, makes some calculations, adds them to database and shows result in right column (date in <td>).
Now as expected PHP script needs page refreshing to show calculation result (date in <td>). I'm trying to write JS script which will retrieve calculated data from database and immediately show in HTML table's cell.
Having troubles with it. Asking for help with this issue.
index.php:
<form id="form-wrap" action="functions.php" method="POST">
<select name="select1" required>
<?php
for ($i = 1; $i <= 20; $i++) {
echo "<option>".$i."</option>";
}
?>
</select>
<br>
<input type="text" id="name" name="name">
<input type="date" id="day" name="day">
<input type="submit" name="button_ok" id="button_ok" value="Write">
<input type="submit" name="show" id="show" value="Show table">
</form>
functions.php:
<?php
require_once 'dbconnect.php';
$loged = $_POST["name"];
$day = $_POST["day"];
class Count_Add_Class {
public function CountDays() {
global $day, $loged, $day_remind1, $days_before1;
$currenttime = time();
$days_before1 = $_POST["select1"];
// ... make some calculations with user's input ...
$this->AddDate();
}
public function AddDate() {
global $pdo, $loged, $day, $day_remind1, $days_before1;
if (isset($_POST['button_ok'])) {
// ... insert in database user's inpt and calculation result ...
}
}
}
$obj = new Count_Add_Class();
$obj -> CountDays();
function Count_days_new_data() {
global $pdo, $day, $loged, $day_remind1_updated,
$stmt = $pdo->prepare("SELECT select1 FROM tablex WHERE name=?");
$stmt->execute([$loged]);
$res = $stmt->fetchAll();
foreach ($res as $row) {
$day_remind1_updated = $row['select1'];
}
$day_remind1_updated = $day - ($days_before1_updated * 86400);
$day_remind1_updated = date('Y-m-d', $day_remind1_updated);
}
Count_days_new_data();
function Show() {
global $pdo, $loged, $faq, $day_remind1_updated;
$stmt = $pdo->prepare("SELECT * FROM tablex WHERE name=?");
$stmt->execute([$loged]);
$faq = $stmt->fetchAll();
$s1 = $_POST['editval'];
$id = $_POST['id'];
$stmt2 = $pdo->prepare("UPDATE tablex SET select1=? WHERE
id=?");
$stmt2->execute([$s1, $id]);
$stmt3 = $pdo -> prepare("UPDATE tablex SET day_remind1=?,WHERE
id=?");
$stmt3->execute([$day_remind1_updated, $id]);
require_once 'table.php';
}
Show();
?>
table.php:
<div id="day-data">
<tbody>
<?php
foreach($faq as $key=>$value) {
?>
<tr class="table_row">
<td><?php echo $value['name']; ?></td>
<td aria-label="First" contenteditable="true" onBlur="saveToDatabase(this,'select1','<?php echo $faq[$key]["id"];
?>')" onClick="showEdit(this);"><?php echo $faq[$key]["select1"]; ?>
</td>
<td><?php echo $value['day_remind1']; ?></td>
</tr>
<?php
}
?>
edit.js:
function showEdit(editableObj) {
$(editableObj).css("background","#FFF");
}
function saveToDatabase(editableObj,column,id) {
$(editableObj).css("background","#FFF url(loaderIcon.gif) no-repeat
right");
$.ajax({
url: "functions.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
show.js: (inspired by this answer)
$(".tbl tbody").on("click", "tr", function() {
var id = $(this).find("td")[0].text(); // gets the first td of the
clicked tr
var value = $(this).find("td")[1].text()
$.ajax({
url : "table.php",
dataType: "text",
success : function (data) {
$(".day-data").html(data);
},
error: function (data) {
(".tbl").html('No such file found on server');
}
});
});
When user clicks on HTML-table left column it is higligted well; when he changes it, data is addiing to database well. Now when page is refreshed new data is calculated, added to database and shown in HTML-table's right column.
I suppose problem is in show.js. Need some help in correcting this script!
Update1:
Added illustartion of my task's logic:
It is unfortunate, that you have everything in the functions.php file. It doesn't just count the values, it also renders the table. So when you call the function saveToDatabase, the request that you make to functions.php (and i understand it coorectly) already returns the table with the updated data (as argument of the success function). Try removing show.js and changing the success function content in edit.js from this:
$(editableObj).css("background","#FDFDFD");
to this
$(editableObj).css("background","#FDFDFD");
$(".day-data").replaceWith(data);

How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list

How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list
index.php
<?php
include('pdo.php');
include('item.php');
include('loadMore.php');
?>
<div id="container">
<?php foreach ($items as $item): ?>
<div class="single-item" data-id="<?= $item->id ?>">
<?= $item->show() ?>
</div>
<?php endforeach; ?>
</div>
<button id="loadMore">Загрузить ещё...</button>
<script src="/jquery-1.11.3.min.js"></script>
<script src="/script.js"></script>
item.php
<?php
class Item
{
public $id;
public $text;
function __construct($id = null, $text = null)
{
$this->id = $id;
$this->text = $text;
}
public function show()
{
return $this->text;
}
}
loadmore.php
<?php
$offset = 0;
$limit = 10;
$statement = $pdo->prepare('SELECT * FROM credit LIMIT ?, ?');
$statement->bindValue(1, $offset, PDO::PARAM_INT);
$statement->bindValue(2, $limit, PDO::PARAM_INT);
$statement->execute();
$data = $statement->fetchAll();
$items = [];
foreach ($data as $item)
{
$items[] = new Item($item['id'], $item['tel']);
}
pdo.php
<?php
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
script.js
function getMoreItems() {
var url = "/loadMore.php";
var data = {
//
};
$.ajax({
url: url,
data: data,
type: 'get',
success: function (res) {
//
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//
}
});
}
How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list
I think 2 hours and I can not understand.
Help.(
I understand your confusion, I believe you're wondering why your php code in index.php doesn't work properly after you call loadMore.php using ajax.
There's one distinction you need to understand to be capable of developing for the web. The difference between server-side and client-side code.
PHP is a server-side programming language, which means that it only executes on the server. Your server returns html, or json, or text, or anything to the browser and once the response arrives at the browser, you can forget about php code.
Javascript on the other hand is a client side programming language (at least in your case) It executes on the browser.
You basically have two options:
To send back some json and loop over it using jQuery, which is the preferable choice, but I fear it requires more work.
Send back html and append it to your page, first create a file called async.php
<?php
include('pdo.php');
include('item.php');
include('loadMore.php');
?>
<?php foreach ($items as $item): ?>
<div class="single-item" data-id="<?= $item->id ?>">
<?= $item->show() ?>
</div>
<?php endforeach; ?>
in your js add to your success callback
$.ajax({
url: url,
data: data,
type: 'get',
success: function (res) {
$('#container').append(res);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//
}
});
don't forget var url = "async.php";
First you need to attach the buttons onclick="" attribute with the ajax-method.
<button ... onclick="getMoreItems">...</button>
Second, your loadmore.php need to require_once the files it depends on:
require_once('pdo.php');
require_once('item.php');
Third, separate your logic for querying the database to a function in the pdo.php file you can call with the limits as parameters, i.e.
function getData($offset = 0, $limit = 10){
//logic
}
You should also always try to use require_once or include_once to be sure files aren't loaded several times.
Now you can call the function getData(...) from index.php before the container div to load up the initial data, remove the include to loadmore.php from index.php, and in loadmore.php write the logic to use the parameters sent from the webpage to get the next chunk of data.
The data:... in your ajax needs to pass along the "page" it wants to get, perhaps simply a counter as to how many times you have loaded more. In the loadmore.php script you then just multiply the page by the limit to get the offset.
Return the data as JSON to the ajax, parse the JSON so you can build a new div for each item, then add each div to the container-div using javascript.
Im not going in detail on all topics here, but you at least will know what tutorials to search for on google :)

How can I call a Function with a href?

I´m trying to call a function into a href, my function is on functions.php
and my href is on views/something.php
so, this is my function:
function discount($connection, $us){
$discount = $conexion->prepare("UPDATE postule SET seen = 1 WHERE id = $us");
$discount->execute();
return $discount;
}
and my link button is on an <li> (not in a form):
<?php foreach ($total_notu as $notu) : ?>
<li><a onClick="<?php discount() ?>" href="notificaciones.php"> Notificaciones <span class="badge "><?php echo "$notu[0]"; ?></span></a></li>
<?php endforeach; ?>
(Do not pay attention to the foreach)
You'll need to change this to use an ajax call or form post to call the PHP function.
Here's a really basic example which should point you in the right direction
discount.php
<?php
// Load $connection from somewhere
// Get user, it's better to get this from a cookie or session rather than GET
$user = $_GET['user']
$discount = $connection->prepare("UPDATE postule SET seen = 1 WHERE id = :user");
$discount->bindParam(':user', $user);
$result = $discount->execute();
// Throw error if something went wrong with the update, this will cause $.ajax to use the error function
if (!$result) {
http_response_code(500);
}
html, assuming $notu[0] contains the user id
<?php foreach ($total_notu as $notu) : ?>
<li><a onClick="return callDiscount('<?php echo "$notu[0]"; ?>');" href="#"> Notificaciones <span class="badge "><?php echo "$notu[0]"; ?></span></a></li>
<?php endforeach; ?>
js, requires jquery
function callDiscount(user_id)
{
// Perform ajax call to discount.php
$.ajax({
url: '/discount.php?user=' + user_id,
error: function() {
alert('An error occurred');
},
success: function(data) {
// Redirect user to notificaciones.php
document.location = '/notificaciones.php';
}
});
// Prevent link click doing anything
return false;
}

Using ajax to display new database inputs without refreshing the page

I am using ajax to post comments to a certain page, I have everything working, except for when the user posts a comment I would like it to show immediately without refreshing. The php code I have to display the comments is:
<?php
require('connect.php');
$query = "select * \n"
. " from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '$s_post_id' ORDER BY comments.id DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$c_comment_by = $row['comment_by'];
$c_comment_content = $row['comment_content'];
?>
<div class="comment_box">
<p><?php echo $c_comment_by;?></p>
<p><?php echo $c_comment_content;?></p>
</div>
<?php } ?>
</div>
</div>
<?php
}
}
and the code I have to post comments is:
<?php
$post_comment = $_POST['p_post_comment'];
$post_id = $_POST['p_post_id'];
$post_comment_by = "Undefined";
if ($post_comment){
if(require('connect.php')){
mysql_query("INSERT INTO comments VALUES (
'',
'$post_id',
'$post_comment_by',
'$post_comment'
)");
echo " <script>$('#post_form')[0].reset();</script>";
echo "success!";
mysql_close();
}else echo "Could no connect to the database!";
}
else echo "You cannot post empty comments!"
?>
JS:
function post(){
var post_comment = $('#comment').val();
$.post('comment_parser.php', {p_post_comment:post_comment,p_post_id:<?php echo $post_id;?>},
function(data)
{
$('#result').html(data);
});
}
This is what I have for the refresh so far:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.comment_box').load('blogpost.php');
}, 3000);.
});
Now what I want to do is to use ajax to refresh the comments every time a new one is added. Without refreshing the whole page, ofcourse. What am I doing wrong?
You'll need to restructure to an endpoint structure. You'll have a file called "get_comments.php" that returns the newest comments in JSON, then call some JS like this:
function load_comments(){
$.ajax({
url: "API/get_comments.php",
data: {post_id: post_id, page: 0, limit: 0}, // If you want to do pagination eventually.
dataType: 'json',
success: function(response){
$('#all_comments').html(''); // Clears all HTML
// Insert each comment
response.forEach(function(comment){
var new_comment = "<div class="comment_box"><p>"+comment.comment_by+"</p><p>"+comment.comment_content+"</p></div>";
$('#all_comments').append(new_comment);
}
})
};
}
Make sure post_id is declared globally somewhere i.e.
<head>
<script>
var post_id = "<?= $s_post_id ; ?>";
</script>
</head>
Your new PHP file would look like this:
require('connect.php');
$query = "select * from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '".$_REQUEST['post_id']."' ORDER BY comments.id DESC";
$result = mysql_query($query);
$all_comments = array() ;
while ($row = mysql_fetch_array($result))
$all_comments[] = array("comment_by" => $result[comment_by], "comment_content" => $result[comment_content]);
echo json_encode($all_comments);
Of course you'd want to follow good practices everywhere, probably using a template for both server & client side HTML creation, never write MySQL queries like you've written (or that I wrote for you). Use MySQLi, or PDO! Think about what would happen if $s_post_id was somehow equal to 5' OR '1'='1 This would just return every comment.. but what if this was done in a DELETE_COMMENT function, and someone wiped your comment table out completely?

Update CakePhp View each time a record is inserted in the db table

Am making an application that will enable remote viewing of records and reports via a browser. I have used cakePHP to make the application and its working fine,but i have one little problem,since the application does not do any inserts its just reading the data,i want when a user has opened a view and a record has been inserted on the table,it should update all open clients, instead of the user refreshing the page to get the new records.
Is there a cakePHP websocket plugin that actually works?
Our webhost doesnt allow installing programs or adding apache modules so nodejs or similar solutions wont be applicable here.
Am looking for a purely php and javascript implementation where you
just upload your application files to the webserver and everything
runs. You dont have to run, install extras or do any configuration on apache or stuff... afteruploading your files
here is a function in one of my controllers(BooksController.php) that retrieves the data to the view
public function list_books()
{
$this->Books->recursive = 0;
$this->paginate = array('order' => array('Serial_No' => 'DESC'));
$this->set('All_Books', $this->paginate());
}
and here is one of my views(list_books.ctp) that displays the data in a table paginated.
<div class="row-fluid">
<div class="span12">
<?php echo $this->Session->flash() ?>
<h4><?php echo __('All Books') ?></h4>
<hr>
<table class="table table-bordered">
<thead>
<tr> <th><?php echo __('Serial No') ?></th>
<th><?php echo __('Title') ?></th>
<th><?php echo __('Author') ?></th>
<th><?php echo __('Publisher') ?></th>
<th><?php echo __('Category') ?></th>
<th><?php echo __('Section') ?></th>
<th><?php echo __('Available') ?></th>
</tr>
</thead>
<tbody>
<?php foreach( $All_Books as $book ){ ?>
<tr>
<td><?php echo $this->Html->link(__($book['Book']['Serial_No']),'/books/view/'.$book['Book']['Serial_No']) ?></td>
<td><?php echo $book['Book']['Title'] ?></td>
<td><?php echo $book['Book']['Author'] ?></td>
<td><?php echo $book['Book']['Publisher'] ?></td>
<td><?php echo $book['Book']['Category'] ?></td>
<td><?php echo $book['Book']['Section'] ?></td>
<td><?php echo $book['Book']['Available'] ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php echo $this->Paginator->prev('« Previous', null, null, array('class' => 'disabled'));
echo $this->Paginator->numbers();
echo $this->Paginator->next('Next »', null, null, array('class' => 'disabled'));
echo $this->Paginator->counter(array(
'format' => 'Page {:page} of {:pages}, showing {:current} records out of
{:count} total, starting on record {:start}, ending on {:end}'
));
?>
</div>
</div>
What can i add on my view or controller or model, to make the view auto updating?
Can this be achieved using ajax?
You can use an AJAX poller, or (HTML5) websockets (using Pusher for instance) for push notification.
You've already mentioned it, AJAX. That's the easiest way to accomplish something like that, simply do a check in the background via AJAX, and if necessary reload the page, or update only the affected parts by again using an AJAX request.
Depending on the amount of data you could of course simply load the data directly instead of checking for updates first.
Update I've misunderstood the question, in case the inserts/udpates are made from an external source that you have no direct control over as described in the comments, the only options I could think of for checking whether updating the view is necessary, would be checking the UPDATE_TIME information schema (works on MyISAM only), using triggers for updating a custom information schema that could be checked, or counting the rows, however the latter would only cover inserts.
All methods would fetch the comparison value (update time or row count) in the controller action of the specific view, and pass that value to the view where it's then used in the AJAX call. The AJAX call invokes a controller method where the passed value is compared to the current time/count value in order to determine whether an update is necessary.
Please note that the examples are untested!
Information Schema
The easiest method would be checking the UPDATE_TIME information schema, however as mentioned this only works for MyISAM tables:
Model:
public function getUpdateTime()
{
$db = $this->getDataSource();
$result = $db->fetchAll('
SELECT
UNIX_TIMESTAMP(UPDATE_TIME) AS update_time
FROM
information_schema.tables
WHERE
TABLE_SCHEMA = ?
AND
TABLE_NAME = ?',
array
(
$db->config['database'],
$this->table
)
);
if(empty($result) || !isset($result[0][0]['update_time']))
{
return false;
}
return (int)$result[0][0]['update_time'];
}
Controller:
public function list_books()
{
$this->set('lastUpdate', $this->Books->getUpdateTime());
$this->Books->recursive = 0;
$this->paginate = array('order' => array('Serial_No' => 'DESC'));
$this->set('All_Books', $this->paginate());
}
public function checkForUpdate($time)
{
$updateNecessary = $this->Books->getUpdateTime() > (int)$time;
return new CakeResponse(array('body' => json_encode($updateNecessary)));
}
View:
<script>
jQuery(function($)
{
var lastUpdate = <?php echo $lastUpdate; ?>;
function checkForUpdate()
{
$.get('/books/checkForUpdate', {time: lastUpdate}, function(updateNecessary)
{
if(updateNecessary === true)
{
alert('update necessary');
// now reload the page or use an additional AJAX request for updating the content
}
else
{
queueUpdateCheck();
}
},
'json');
}
function queueUpdateCheck()
{
setTimeout(checkForUpdate, 5000);
}
queueUpdateCheck();
});
</script>
Using Triggers
Another option would be using triggers. You'd need an additional table that connects tables and time values using for example the table name, and two triggers, one for inserts, one for updates. These triggers could then update the custom information table.
Information Table
CREATE TABLE IF NOT EXISTS `table_stats` (
`table_name` varchar(255) NOT NULL,
`update_time` datetime NOT NULL,
PRIMARY KEY (`table_name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `table_stats` (`table_name`, `update_time`)
VALUES ('books', NOW());
Triggers
CREATE TRIGGER `update_time_after_insert` AFTER INSERT ON `books`
FOR EACH ROW
UPDATE `table_stats` SET `update_time` = NOW() WHERE `table_name` = 'books';
CREATE TRIGGER `update_time_after_update` AFTER UPDATE ON `books`
FOR EACH ROW
UPDATE `table_stats` SET `update_time` = NOW() WHERE `table_name` = 'books';
Model:
public function getUpdateTime()
{
$db = $this->getDataSource();
$result = $db->fetchAll('
SELECT
UNIX_TIMESTAMP(update_time) AS update_time
FROM
`table_stats`
WHERE
`table_name` = ?',
array
(
$this->table
)
);
if(empty($result) || !isset($result[0][0]['update_time']))
{
return false;
}
return (int)$result[0][0]['update_time'];
}
Controller and View would be the same as in the previous example.
Counting rows
Now the last option would be comparing the row count, which would of course only work for inserts. In this example the Model would stay untouched.
Controller:
public function list_books()
{
$this->set('rowCount', $this->Books->find('count'));
$this->Books->recursive = 0;
$this->paginate = array('order' => array('Serial_No' => 'DESC'));
$this->set('All_Books', $this->paginate());
}
public function checkForUpdate($rowCount)
{
$updateNecessary = $this->Books->find('count') != (int)$rowCount;
return new CakeResponse(array('body' => json_encode($updateNecessary)));
}
View:
<script>
jQuery(function($)
{
var rowCount = <?php echo $rowCount; ?>;
function checkForUpdate()
{
$.get('/books/checkForUpdate', {rowCount: rowCount}, function(updateNecessary)
{
if(updateNecessary === true)
{
alert('update necessary');
// now reload the page or use an additional AJAX request for updating the content
}
else
{
queueUpdateCheck();
}
},
'json');
}
function queueUpdateCheck()
{
setTimeout(checkForUpdate, 5000);
}
queueUpdateCheck();
});
</script>
Retrieving data together with the update check
Of course you could also submit possible data together with the update check, in order to avoid additional requests. For example:
Model
public function checkForUpdate($time)
{
$data = '';
$updateAvailable = $this->Books->getUpdateTime() > (int)$time;
if($updateAvailable)
{
$this->set('books', $this->Books->find('all'));
// render /Elements/books.ctp in ajax.ctp layout and grab the rendered content
$this->viewPath = 'Elements';
$view = $this->render('books', 'ajax');
$data = $view->body();
}
$body = compact('updateAvailable', 'data');
return new CakeResponse(array('body' => json_encode($body)));
}
View
<script>
jQuery(function($)
{
var lastUpdate = <?php echo $lastUpdate; ?>;
function checkForUpdate()
{
$.get('/books/checkForUpdate', {time: lastUpdate}, function(response)
{
if(response.updateAvailable === true)
{
// the data is already available, so directly update the content
$('#content').html(response.data);
}
queueUpdateCheck();
},
'json');
}
function queueUpdateCheck()
{
setTimeout(checkForUpdate, 5000);
}
queueUpdateCheck();
});
</script>

Categories