I have 2 functions in php which I'm using to display page content on a website.
Both of these functions work from inside the page independently and so the $_POST variables from the ajax call I have proven to myself are all present.
There are 2 pages involved plus the button, I won't bother with the button below.
pages/pages.php (where the problem statement is and which is called by ajax from the button)
<?php
include('../config/connection.php');
$page=$_POST['page'];
$lang=$_POST['lang'];
function pageDivs($dbc, $id, $lang){
$q="SELECT * FROM content WHERE page='$id' AND status=1";
$r = mysqli_query($dbc, $q);
while ($data=mysqli_fetch_assoc($r)){
?>
<div class="content" >
<?php
if ($lang =='FR'){
echo $data['contentfr'];
}else{
echo $data['contenten'];
}
?>
</div>
<?php
}
}
function blog($dbc,$lang){
?>
<div class="bgImage homeImg"><img src="images/bgs/1566337061.jpg"></div>
<div class="gradient"></div>
<div class="col-md-12">
<?php
$q = "SELECT * FROM blog WHERE status = 1 ORDER BY id DESC";
$r = mysqli_query($dbc,$q);
$i=0;
while ($data=mysqli_fetch_assoc($r)){
$i++;
?>
<div id="post<?php echo $i; ?>" class="post snap">
<div class="postBox">
<article id="article<?php echo $i; ?>" class="article col-md-7">
<h3><?php echo $data['titleen'] ?></h3>
<?php echo $data['contenten']; ?>
</article>
<div id="pictureFrameLand<?php echo $i; ?>" class="pictureFrameLand col-md-4">
<img src="<?php
$q2 = "SELECT * FROM tbl_images WHERE image_id=$data[artimage]";
$r2 = mysqli_query($dbc, $q2);
$src= mysqli_fetch_assoc($r2);
echo $src['urlFront']
?>">
</div>
<div class="gradientLand col-md-4"></div>
</div>
</div>
<div class="spacer snap"></div>
<?php
}
?>
</div>
<?php
}
if ($page !== 'home'){
pageDivs($dbc, $page, $lang);
} else{
blog($dbc, $lang);
include('../js/home.php');
}
?>
js/myJS.php(ajax calls from here, button.on(click, function(){}) )
<script type="text/javascript">
// JavaScript Document
$(document).ready(function() {
// Create vars for Pages
var page = 'home';
var lang = '<?php echo $_GET['
lang ']; ?>';
var dataTosend = 'page=' + page + '&lang=' + lang;
//Ajax Home Page on load
$.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
//Ajax 1st 2 buttons
$('#home').click(function() {
page = 'home';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').addClass('inactive').removeClass('active');
$('#home').removeClass('inactive').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(),
$.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
$('#bio').click(function() {
page = 'bio';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').addClass('inactive').removeClass('active');
$('#bio').removeClass('inactive').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
//Ajax Work Dropdown
$('#work').click(function() {
page = 'work';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#work').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
$('.install').click(function() {
page = 'install';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#install').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
$('.write').click(function() {
page = 'write';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#write').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
$('.video').click(function() {
page = 'video';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#video').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
$('.photo').click(function() {
page = 'photo';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#photo').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
//Ajax Workshops dropdown
$('#works').click(function() {
page = 'works';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#works').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
$('.child').click(function() {
page = 'child';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#child').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
$('.adols').click(function() {
page = 'adols';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#adols').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
$('.adult').click(function() {
page = 'adult';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#adult').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
//Ajax Last button
$('#contact').click(function() {
page = 'contact';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#contact').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
//Collapse Dropdowns with other buttons
$('.bbutt').click(function() {
$('#collapseOne1').removeClass('show');
$('#collapseTwo1').removeClass('show');
});
$('#work').click(function() {
$('#collapseTwo1').removeClass('show');
});
$('#works').click(function() {
$('#collapseOne1').removeClass('show');
});
//debug
$('#console-debug').hide();
$('#btn-debug').on("click", function() {
$('#console-debug').toggle();
});
// Hide NavBar after 5s and show on rollover
//$('#navCol').hide("slide", { direction: "left" }, 1000);
//$('#navCol').show("slide", { direction: "right" }, 1000);
});
</script>
I know there's a lot of code there and you only really need 2 of the button ajax calls to see the method but it's worth pointing out that there are that many potential calls from buttons; so I included the whole file.
The Culprit Statement is at the end of pages.php:
<?php
}
if ($page !== 'home'){
pageDivs($dbc, $page, $lang);
} else{
blog($dbc, $lang);
include('../js/home.php');
}
?>
Now, what's strange is that only home works like this, so !=='home' is skipped and blog runs, proving that both $dbc and $lang are available. no button changes from this page.
But if I do this:
pageDivs($dbc, $page, $lang);
/*
if ($page !== 'home'){
} else{
blog($dbc, $lang);
include('../js/home.php');
}
*/
Then pageDivs() runs, proving that infact $page is set and available...
Edit
I should also point out that I started the If statement as just != and then later moved to !== and had no effect.
Edit2:
For Rasclatt, here is the button html output. I had to keep the href or my css breaks, but I can remove it and rewrite my css if it's gonna need to be buttons:
<div id="navCol" class="col-sm-1">
<!--nav in here-->
<ul id="mainNav" class="nav navbar">
<!--beginning of main list-->
<li class="nav navbar navbar-text">
<a id="home" href="#home" data-acton="#home" data-page="home" class="bbutt do-action active"> Home </a>
</li>
<li class="nav navbar navbar-text">
<a id="bio" href="#bio" data-acton="#bio" data-page="bio" class="bbutt do-action inactive"> Biography </a>
</li>
<li>
<div id="accordion1" class="accordion" role="tablist">
<div id="header-card" class="card accordion">
<div class="card-header accordion accordion-header work" role="tab" id="headingOne1">
<h5 class="mb-0"> <a id="work" class="do-action" data-page="work" data-toggle="collapse" data-acton="#work" href="#collapseOne1" role="button" aria-expanded="true" aria-controls="collapseOne1"> Work </a> </h5>
</div>
<div id="collapseOne1" class="collapse accordion" role="tabpanel" aria-labelledby="headingOne1" data-parent="#accordion1">
<div class='card-body accordion accordion-item inactive'>
<a id="install" data-page="install" class="do-action install" href="#install" data-acton="#install" class="subs first">
Installations
</a>
</div>
<div class='card-body accordion accordion-item inactive'>
<a id="write" data-page="write" class="do-action write" href="#write" data-acton="#write" class="subs">
Writing
</a>
</div>
<div class='card-body accordion accordion-item inactive'>
<a id="video" data-page="video" class="do-action video" href="#video" data-acton="#video" class="subs">
Video
</a>
</div>
<div class='card-body accordion accordion-item inactive'>
<a id="photo" data-page="photo" class="do-action photo" href="#photo" data-acton="#photo" class="subs last">
Photography
</a>
</div>
</div>
</div>
</div>
</li>
<li>
<div id="accordion2" class="accordion" role="tablist">
<div id="header-card" class="card accordion">
<div class="card-header accordion accordion-header2 works" role="tab" id="headingTwo1">
<h6 class="mb-0"> <a id="works" class="do-action" data-toggle="collapse" href="#collapseTwo1" data-acton="#workshops" data-page="works" role="button" aria-expanded="true" aria-controls="collapseTwo1">Workshops</a> </h6>
</div>
<div id="collapseTwo1" class="collapse accordion" role="tabpanel" aria-labelledby="headingTwo1" data-parent="#accordion2">
<div class='card-body accordion accordion-item inactive'>
<a id="child" data-page="child" class="do-action child" href="#child" data-acton="#child" class="subs first">
Children
</a>
</div>
<div class='card-body accordion accordion-item inactive'>
<a id="adols" data-page="adols" class="do-action adols" href="#adols" data-acton="#adols" class="subs">
Adolescents
</a>
</div>
<div class='card-body accordion accordion-item inactive'>
<a id="adult" data-page="adult" class="do-action adult" href="#adult" data-acton="#adult" class="subs last">
Adults
</a>
</div>
</div>
</div>
</div>
</li>
<li class="nav navbar navbar-text">
<a id="contact" href="#contact" data-acton="#contact" data-page="contact" class="bbutt do-action inactive"> Contact </a>
</li>
</ul>
</div>
when you load the page for the first time it goes on home which is fine, but when you click on other button (bio,work,etc.) it fetch the content of both because every time you include the js/home.php it executes the ajax function below along with the $('#other').click . due to which you end up making 2 ajax call
//Ajax Home Page on load
$.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
before including the page i suggest you to add extra flag variable just to skip ajax call to home
}
if ($page !== 'home'){
pageDivs($dbc, $page, $lang);
} else{
blog($dbc, $lang);
$donotloadhome = true;
include('../js/home.php');
}
and in the script add a varible too.
var skipflag = '<?php echo ($donotloadhome)?'call':''; ?>';
if(skipflag != 'call')
{
//Ajax Home Page on load
$.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
}
Couple things here; you have a PHP syntax anomaly in your javascript on this line:
var lang = '<?php echo $_GET['
lang ']; ?>';
try bringing it up on one line and remove spaces in the key name:
var lang = '<?php echo $_GET['lang']; ?>';
Secondly, you should not be repeating your JavaScript sections over and over. You can reduce it to one ajax function and then use other DOM elements to indicate your intentions to that function, for example:
<script>
// Wrap your stuff in one function and inject what you need that changes
function doAjaxCall(btn, page, lang)
{
// Set the query string
var dataTosend = 'page=' + page + '&lang=' + lang;
// If is obj do the button stuff
if(btn !== false) {
$('.active').addClass('inactive').removeClass('active');
btn.removeClass('inactive').addClass('active');
}
// Run the ajax and all that jazz
$('.content').fadeOut(500, function() {
$('.content').remove();
$.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
}
// Set document ready
$(function(){
// Just send the language once, make sure to try and remove any possible
// user hackery...
var lang = '<?php echo htmlspecialchars($_GET["lang"], ENT_QUOTES) ?>';
// Run the default ajax on page load
doAjaxCall(false, 'home', lang);
// Just listen for one element on click now
$(this).on('click', '.do-action', function(){
// If the element that is being clicked is the same one that is going
// to have the .active done to it, then just use $(this) only
doAjaxCall($($(this).data('acton')), $(this).data('page'), lang);
});
});
//Collapse Dropdowns with other buttons
$('.bbutt').click(function() {
$('#collapseOne1').removeClass('show');
$('#collapseTwo1').removeClass('show');
});
$('#work').click(function() {
$('#collapseTwo1').removeClass('show');
});
$('#works').click(function() {
$('#collapseOne1').removeClass('show');
});
//debug
$('#console-debug').hide();
$('#btn-debug').on("click", function() {
$('#console-debug').toggle();
});
</script>
The trigger html would be something like this:
<!-- Add the "do-action" class to everything that you want to fire the ajax -->
<!-- Then you can put the page destination in the data attribute -->
<!-- Using $(this) probably would work in the js but, use the acton data attribute to send the intended object to act on -->
<button id="home" class="do-action" data-acton="#home" data-page="home">Home<button>
<button id="install" class="do-action" data-acton="#install" data-page="install">Install<button>
Anyway, by making only one function, you reduce the chances you will make a copy/paste error and will clean up your JS greatly.
Finally, since you are mixing all kinds of html/functions/business/view login together, you may want to wrap your PHP functions with a check for exists:
if(!function_exists('pageDivs')) {
function pageDivs($dbc, $id, $lang)
{
$r = mysqli_query($dbc, "SELECT * FROM content WHERE page='$id' AND status = 1");
while ($data = mysqli_fetch_assoc($r)): ?>
<div class="content" >
<?php echo ($lang =='FR')? $data['contentfr'] : $data['contenten'] ?>
</div>
<?php endwhile;
}
}
if(!function_exists('blog')) {
function blog($dbc, $lang)
{ ?>
<div class="bgImage homeImg">
<img src="images/bgs/1566337061.jpg">
</div>
<div class="gradient"></div>
<div class="col-md-12">
<?php
$r = mysqli_query($dbc, "SELECT * FROM blog WHERE status = 1 ORDER BY id DESC");
$i=0;
while($data = mysqli_fetch_assoc($r)):
$i++; ?>
<div id="post<?php echo $i; ?>" class="post snap">
<div class="postBox">
<article id="article<?php echo $i; ?>" class="article col-md-7">
<h3><?php echo $data['titleen'] ?></h3>
<?php echo $data['contenten']; ?>
</article>
<div id="pictureFrameLand<?php echo $i; ?>" class="pictureFrameLand col-md-4">
<img src="<?php
$q2 = "SELECT * FROM tbl_images WHERE image_id = ".$data['artimage'];
$r2 = mysqli_query($dbc, $q2);
$src= mysqli_fetch_assoc($r2);
echo $src['urlFront']
?>" />
</div>
<div class="gradientLand col-md-4"></div>
</div>
</div>
<div class="spacer snap"></div>
<?php endwhile ?>
</div>
<?php
}
}
I successfully fetch the data from the database. The problem is that, I want to display the results using Ajax request. The results/Output which displayed twice, I mean the *first output which displayed through Ajax (#the bottom of index.php), and the Second output displayed through PHP ECHO (**#**the bottom of the page). What can I do to get a single output through Ajax without adding another file and without refreshing the page?
index.php
<head>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript" src="javas.js"></script>
</head>
<body>
<div id="table_content"></div>
<?php
include ("db.php");
error_reporting(~E_NOTICE);
function ShowForm($AnswerCommentId) {
echo '<form id="myForm">';
echo '<input id="user" name="user" />';
echo '<textarea id="text" name="text"></textarea>';
echo sprintf('<input id="ParentId" name="ParentId" type="hidden" value="%s"/>', ($AnswerCommentId));
echo '<button type="button" OnClick=SendComment()>Comment</button>';
echo '</form>';
}
$query="SELECT * FROM `comm` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId'])) $AnswerId = $_REQUEST['AnswerId'];
else $AnswerId = 0;
$i=0;
while ($mytablerow = mysqli_fetch_row($result)){ $mytable[$i] = $mytablerow; $i++; }
function tree($treeArray, $level, $pid = 0) {
global $AnswerId;
foreach($treeArray as $item){
if ($item[1] == $pid){
echo sprintf('<div class="CommentWithReplyDiv" style="margin-left:%spx;">',$level*60);
echo sprintf('<p>%s</p>', $item[2]);
echo sprintf('<div>%s</div>', $item[3]);
if ($level<=2) echo sprintf('Reply', $item[0]);
if ($AnswerId == $item[0]) echo sprintf('<div id="InnerDiv">%s</div>', ShowForm($AnswerId));
echo '</div><br/>';
tree($treeArray, $level+1, $item[0]); // Recursion
}
}
}
tree($mytable,0,0);
?>
Comment
<div id="MainAnswerForm" style="display:none;width:40%; margin:0 auto;"><?php ShowForm(0); ?></div>
<div id="AfterMainAnswerForm"></div>
<script>
$(document).ready(function(){
$("#Link").click(function () {
$("#InnerDiv").remove();
$("#MainAnswerForm").slideToggle("normal");
return false;
});
});
</script>
</body>
Page.php
<?php
include ("db.php");
$user = $_POST['user'];
$text = $_POST['text'];
$ParentId = $_POST['ParentId'];
$action = $_POST['action'];
if ($action=="add") $query= mysqli_query($conn,"INSERT into `comm` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())");
?>
Javas.js
function show_messages(){
$.ajax({
url: "index.php",
cache: false,
success: function(html){
$("#table_content").html(html);
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "index.php",
data: "AnswerId="+id,
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "page.php",
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
show_messages();
}
});
return false;
}
OK I think its more simple than you think
while you're using .html() it should change all the content of your div but while you're using <div id="table_content"></div> then the <?php ?> your code will show both - one appended to the div and under it the one which echoed by php ... so instead of using
<div id="table_content"></div>
<?php ?>
just wrap the <?php ?> inside the div
<div id="table_content">
<?php ?>
</div>
Alternative way: by using jquery wrapAll() but while Id must be unique you'll need to .remove() the #table_content element first then wrap all your code inside a new #table_content div .. see the example below
$(document).ready(function(){
$('#table_content').remove();
$('.CommentWithReplyDiv').wrapAll('<div id="table_content"></div>');
});
#table_content{
margin : 50px;
background : red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table_content"></div>
<div class="CommentWithReplyDiv">1</div>
<div class="CommentWithReplyDiv">2</div>
<div class="CommentWithReplyDiv">3</div>
<div class="CommentWithReplyDiv">4</div>
My project is a kind of blog, with posts and comments area. I'm trying to make it async with jquery ajax. My problem is that when a new comment gets inserted asynchronously it appears in the div twice, and all the other comments disappear. If i refresh the page it looks fine.
VIEW:
<section id="comments_section_<?php echo $p1['post_id'];?>"> //THIS IS THE OUTPUT WHERE NEW COMMENTS WILL BE APPENDED
<?php
$data['comments'] = $this->model_mutamba->getComments($p1['post_id']);
if($data['comments'] != ""){ ?>
<div class="comments_container" id="comments_container_<?php echo $p1['post_id'];?>">
<?php foreach ($data['comments'] as $c){
$user_img3 = $this->model_mutamba->getUserPicId($c->aluno_id);
?>
<div>
<img style="height:32px;" src="<?php echo site_url();?>img/users/portfolio/<?php echo $user_img3;?>" alt="" class="align-left" />
<p>
<?php echo $this->model_mutamba->addSmilies($c->comment);?>
<br>
<span class="comments_date">
<?php
$c_date = explode('-', substr($c->comment_date,0,-8));
$date_num_word = monthNumToWords($c_date[1]);
echo substr($c->comment_date, 11,-3)." ".$c_date[2]." de ". $date_num_word . " ". $c_date[0];?>
</span>
</p>
</div>
<?php } ?>
</div>
<?php } ?>
</section>
JS:
function comment(post_id,input){
var comment = $(input).val();
var output = '#comments_section_'+post_id;
if(comment != ""){
$.ajax({
type:"POST",
url:base_url+"mutamba/insertNewComment",
data: {comment: comment, post_id:post_id},
cache:false,
success:function(response){
$(output).html(response);
$(output).append(response);
}
});
}
}
CONTROLLER:
function insertNewComment(){
if($this->session->userdata('is_logged_in')){
$email= $this->session->userdata('email');
$comment= $this->FilterData($this->input->post('comment'));
$post_id= $this->FilterData($this->input->post('post_id'));
$this->load->model('model_mutamba');
if($this->model_mutamba->insertNewComment($email,$comment,$post_id)){
$this->load->model('model_user');
$count = $this->model_mutamba->countPostComments($post_id);
?>
<script>
var count = '<?php echo $count;?>';
var comments_count = '<?php echo "#comments_count_".$post_id;?>';
var content = "";
if(count == 1){
content = '<span class="comments_count">'+count+'</span> Comentário';
}else{
content = '<span class="comments_count">'+count+'</span> Comentários';
}
$(comments_count).html(content);
</script>
<?php
$this->load->model('model_user');
$user_img = $this->model_user->getUserPic($email);
echo '
<div>
<img style="height:32px;" src="'.site_url().'img/users/portfolio/'.$user_img.'" alt="" class="align-left" />
<p>
'.$this->model_mutamba->addSmilies($comment).'
<br>
<span class="comments_date">';
$date = date(date('Y-m-d H:i:s'));
$c_date = explode('-', substr($date,0,-8));
$date_num_word = monthNumToWords($date[1]);
echo substr($date, 11,-3)." ".$c_date[2]." de ". $date_num_word . " ". $c_date[0].'
</span>
</p>
</div>';
}
}else{
redirect("inicio");
}
}
Will appreciate any help,
Thanks in advance
This is happening because in your AJAX success callback, you are adding response to the output TWICE - once with .html() and then again with .append().
.html(response) removes the previous HTML in your webpage, thats why you dont see other comments and it adds response to it.
With .append(response), it is adding response to the bottom of the div, that is the reason you are seeing the response twice!
Remove $(output).html(response) from the success callback and it will work fine.
So, your function needs to look like this:
function comment(post_id,input){
var comment = $(input).val();
var output = '#comments_section_'+post_id;
if(comment != ""){
$.ajax({
type:"POST",
url:base_url+"mutamba/insertNewComment",
data: {comment: comment, post_id:post_id},
cache:false,
success:function(response){
$(output).append(response);
}
});
}
}
function comment(post_id,input){
var comment = $(input).val();
var output = '#comments_section_'+post_id;
if(comment != ""){
$.ajax({
type:"POST",
url:base_url+"mutamba/insertNewComment",
data: {comment: comment, post_id:post_id},
cache:false,
success:function(response){
//$(output).html(response); //Comment this line or the line below it.
$(output).append(response);
}
});
}
}
<div id="appenddiv">
<h1>append</h1>
</div>
<script type="text/javacript">
$("#appenddiv").append('<b>hello world</b>');
</script>
Before I ask this question, I have already referred to the example of this question. However, it seems doesn't work. Without using ajax, I can get my post deleted but after implement ajax, the deleteAtc.php seems to be not working.
My delete page code (delete.php)
<h4>Select an Article to Delete:</h4>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span> Delete<br />
<script type="text/javascript">
$(function(){
$('#link').click(function(){
var id = <?php echo $article['article_id']; ?>;
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id"+id+,
sucess: function() {
$('#sucess').html(data);
}
})
return false;
});
});
</script>
<div id="success"></div><br />
<?php } ?>
While my deleteAtc.php code:
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
echo "Article deleted";
}
}
?>
What I'm trying to do here is to delete the record without redirect to deleteAtc.php, it will remove out the record and replace Article Deleted
May I know where did I go wrong in ajax side?
Please refer below for updated question
Based on the answer below, here is my updated code:
delete.php
<h4>Select an Article to Delete:</h4>
<div id="message"></div>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span>
Delete<br />
<?php } ?>
script
<script type="text/javascript">
$(function(){
$('.link').click(function(){
var elem = $(this);
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+elem.attr('data-artid'),
dataType:"json",
success: function(data) {
if(data.success){
elem.hide();
$('#message').html(data.message);
}
}
});
return false;
});
});
</script>
deleteAtc.php
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
//Also try to handle false conditions or failure
echo json_encode(array('success'=>TRUE,'message'=>"Article deleted"));
}
}
?>
Somehow, if I delete two record at a time, only the first record echo the result, the second result deleted doesn't echo out the result.
Am wondering, possible to add jquery animation to .show the success message and .hide the record deleted?
First of all IDs are not meant to be duplicated, use class selector instead. Also you could make use of custom data attributes to store the id of the article.
Try
<h4>Select an Article to Delete:</h4>
<div id="message"></div>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span>
Delete<br />
<?php } ?>
Script
<script type="text/javascript">
$(function(){
$('.link').click(function(){
var elem = $(this);
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+elem.attr('data-artid'),
dataType:"json",
success: function(data) {
if(data.success){
elem.hide();
$('#message').html(data.message);
}
}
});
return false;
});
});
</script>
And in server side
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
//Also try to handle false conditions or failure
echo json_encode(array('success'=>TRUE,'message'=>"Article deleted"));
}
}
?>
The above script won't work you have to change like below. You are repeating the same identifier function again and again. Keep the jquery script out of foreach loop. You have to add the class property with the article id.
<h4>Select an Article to Delete:</h4>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span> <a href="#" id="link" class='<?php echo $article['article_id']; ?>' >Delete</a><br />
<div id="success"></div><br />
<?php } ?>
<script type="text/javascript">
$(function(){
$('#link').click(function(){
var id = $(this).prop('class');
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+id,
sucess: function() {
$('#sucess').html(data);
}
})
return false;
});
});
</script>
You create several links with id="link". ID must be unique.
You have to write
id="link<? echo $article['article_id']; ?>"
as well as
$('#link<? echo $article["article_id"]; ?>').click(function() {...})
<script language="javascript">
$(document).ready(function() {
$(".delbutton").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this record? There is NO undo!"))
{
$.ajax({
type: "GET",
url: "products/delete_record.php",
data: info,
cache: false,
success: function(){
setTimeout(function() {
location.reload('');
}, 1000);
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
//location.reload();
});
});
</script>
I'm trying import images to HTML using PHP, but NivoSlider not loaded that.
I looked for the cause of the problem.
I am printing a alert message of response and the right.
Here is the HTML and AJAX query:
<div id="workcontent" class="pcontent" style="display:none;">
<div class="slider-wrapper theme-default">
<div id="slider" class="nivoSlider">
</div>
</div>
<script>
$(document).ready(function() {
var wl = $('#worklist div');
wl.on('click', function(){
var name = $(this).attr('id');
console.log(name);
$.ajax({
url: 'read.php',
type: 'POST',
data: { data : name }
}).done(function (response) {
$('#slider').prepend(response);
alert(response);
});
});
});
</script>
<div id="back"></div>
<div id="backcontainer">
<div id="back">
Back
</div>
</div><!--End backcontainer-->
</div><!--End content-->
And here is the other jQuery:
<script>
$(document).ready(function() {
$('#slider').nivoSlider(function(){alert('OK');});
});
</script>
This alert don't show! ):
Finally, here is the PHP code:
<?php
if (isset($_POST["data"])){
if ($_POST["data"] == "") {
echo "data ures";
} else {
$data = $_POST["data"];
$fname = "content/".$data."/*.*";
$files = glob($fname);
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
echo '<img src="'.$num.'" data-thumb="'.$num.'">';
}
}
} else {
echo "nem jott data";
}
?>
Sorry for my bad english
NivoSlider doesn't take a function as an argument.
Also .nivoSlider() is probably called before the AJAX call returns it's response.
A better solution would be:
$(document).ready(function() {
$.ajax({
url: 'read.php',
type: 'POST',
data: { data : name }
}).done(function (response) {
$('#slider').prepend(response).nivoSlider( {} );
});
});
Now you can be fairly sure #slider contains the images from the response body so NivoSlider can act on them.