Reputation: 11746
I'm not sure what the best way to handle this is but here is what I'm trying to do. After a user deletes a photo I need to update my two divs with new stats and a new table. This is done initially by calling two functions. Can I call these PHP functions with jquery somehow or is there a better way?
Here is what my current code snippet looks like:
<?php
include('header.php');
?>
<script type="text/javascript">
$(document).ready(function() {
$('.image_result li').click(function() {
var imgInfo = $(this).attr('id').split(':');
if(confirm('Are you sure you want to delete this image?')) {
$.post('delete_image.php?image_id=' + imgInfo[0] + '&user_id=' + imgInfo[1], function(data) {
// How can I update both divs (imageStats, and imageTable) by calling my two PHP functions?
});
}
});
});
</script>
<div id="imageStats" ><?php echo get_image_stats(); ?></div>
<div id="imageTable" ><?php get_user_images(); ?></div>
Upvotes: 0
Views: 76
Reputation: 6886
What you need to do is call your PHP methods: get_image_stats()
and get_user_images()
and send their output back when the delete_image.php
script is called from the jquery ajax post method.
Assuming get_image_stats()
returns an alphanumeric string, get_user_images()
returns a complete HTML table and there are no "|" characters in either, what I would do is concatenate the output of get_image_stats()
and get_user_images()
with a “|” and echo it out delete_image.php
.
On the success of a post, I would split the data back and update the stats and images like this:
var resp = data.split("|");
$('#imageStats').html(resp[0]);
$('#imageTable').html(resp[1]);
I recommend this approach because I think it will cause the least change to your existing code structure.
Upvotes: 1
Reputation: 11552
Create a file that displays only the stuff output by the functions, for example:
ajax.php
// Include or require the file that contains your functions HERE
switch($_GET['action']) {
case 'get_stats':
echo get_image_stats();
break;
case 'get_images':
get_user_images();
break;
}
JS
$.post('delete_image.php?image_id=' + imgInfo[0] + '&user_id=' + imgInfo[1], function(data) {
$('#imageStats').load('new_php_file.php?action=get_stats');
$('#imageTable').load('new_php_file.php?action=get_images');;
});
NOTE: There are many ways of solving your specific problem. This is only one of countless implementations, but it should give you enough food for thought.
Upvotes: 1