Code breaks with PHP "if" statement, otherwise both functions work independently - php

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
}
}

Related

Ajax not loading posts on live server but working on localhost

I'm trying to load posts of users from my database to the website but the ajax part isn't loading for some reason. It was working on localhost but not working on the live server. Is there some problem in the ajax code or the code written in the index page?
Here in the index page the posts_area div part isn't loading
index.php
<?php
include("includes/header.php");
if(isset($_POST['post'])){
$post = new Post($con, $userLoggedIn);
$post->submitPost($_POST['post_text'], 'none');
}
?>
<div class="main_column column">
<form class="post_form" action="index.php" method="POST">
<textarea name="post_text" id="post_text" placeholder="Got something to say?"></textarea>
<input type="submit" name="post" id="post_button" value="Post">
<hr>
</form>
<div class="posts_area"></div>
<img id="loading" src="assets/images/icons/loading.gif">
</div>
<div class="user_details column">
<h4>Popular</h4>
<div class="trends">
<?php
$query = mysqli_query($con, "SELECT * FROM trends ORDER BY hits DESC LIMIT 9");
foreach ($query as $row) {
$word = $row['title'];
$word_dot = strlen($word) >= 14 ? "..." : "";
$trimmed_word = str_split($word, 14);
$trimmed_word = $trimmed_word[0];
echo "<div style'padding: 1px'>";
echo $trimmed_word . $word_dot;
echo "<br></div><br>";
}
?>
</div>
</div>
<script>
var userLoggedIn = '<?php echo $userLoggedIn; ?>';
$(document).ready(function() {
$('#loading').show();
//Original ajax request for loading first posts
$.ajax({
url: "https://bestconnect.000webhostapp.com/includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=1&userLoggedIn=" + userLoggedIn,
cache:false,
success: function(data) {
$('#loading').hide();
$('.posts_area').html(data);
}
});
$(window).scroll(function() {
var height = $('.posts_area').height(); //Div containing posts
var scroll_top = $(this).scrollTop();
var page = $('.posts_area').find('.nextPage').val();
var noMorePosts = $('.posts_area').find('.noMorePosts').val();
if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') {
$('#loading').show();
var ajaxReq = $.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=" + page + "&userLoggedIn=" + userLoggedIn,
cache:false,
success: function(response) {
$('.posts_area').find('.nextPage').remove(); //Removes current .nextpage
$('.posts_area').find('.noMorePosts').remove(); //Removes current .nextpage
$('#loading').hide();
$('.posts_area').append(response);
}
});
} //End if
return false;
}); //End (window).scroll(function())
});
</script>
</div>
ajax_load_posts.php
<?php
include("../../config/config.php");
include("../classes/User.php");
include("../classes/Post.php");
$limit = 10; //Number of posts to be loaded per call
if (isset($_GET['posts'])) {
$posts = new Post($con, $_REQUEST['userLoggedIn']);
$posts->loadPostsFriends($_REQUEST, $limit);
}
?>
<?php
header("Access-Control-Allow-Origin: *");
include("../../config/config.php");
include("../classes/User.php");
include("../classes/Post.php");
$limit = 10; //Number of posts to be loaded per call
if (isset($_GET['userLoggedIn']))
{
$posts = new Post($con, $_REQUEST['userLoggedIn']);
$posts->loadPostsFriends($_REQUEST, $limit);
}
?>

how to built ajax tabs in wordpress?

I try to display the departments in my website as tabs, when click one tab it will display the data related to this department according to department_id.
I try this code Execute php function only when clicked (wordpress) but I need the tabs number to be dynamic.
<div class="tabs">
<ul>
<?php
$arr1=array(2,3,5,10,22,25,27,28,29,30);
$arr2=array("dep1","dep2","dep3","dep4",
"dep5","dep6","dep7","dep8","dep9","dep10");
for($i=0;$i<10;$i++){?>
<li><a href="#tab" id="<?php echo $arr1[$i]; ?>"><?php echo
$arr2[$i];?>
</a></li>
<?php } ?>
</ul>
</div>
<div id="tab" class="section">
</div>
functions.php:
<?php
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id=$_GET[id];
/** Here I print data according to $dept_id **/
die();
}
?>
script.js:
jQuery(document).ready(function() {
jQuery('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = jQuery(this).attr('id');
console.log(tab_id);
jQuery.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'tabsfunction', id: tab_id}),
success: function(data){
jQuery('#tab').html(data);
},
error: function(data)
{
alert("Error!");
return false;
} });}); });
it dose not work, it displays data only for one tab.
console.log(tab_id) ----> it display the id for the first tab clicked
and did not change when click another tab.
You need to echo the output from the tabsfunction and also add the die() at end of the function like below :
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id=$_GET[id];
/** Here display data according to $dept_id **/
echo 'output';
die();
}
Hope it helps.
can you please correct your tab list code.
<div class="tabs">
<ul>
<?php
$arr1 = array(2,3,5,10,22,25,27,28,29,30);
$arr2 = array("dep1","dep2","dep3","dep4","dep5","dep6","dep7","dep8","dep9","dep10");
for($i=0;$i<10;$i++)
{
?>
<li><?php echo $arr2[$i];?></li>
<?php
}
?>
</ul>
</div>
<?php for($i=0;$i<10;$i++)
{
?>
<div id="tab<?php echo $arr1[$i]; ?>" class="section">
</div>
<?php
}
?>
Also return proper response on ajax request.
<?php
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id = $_GET[id];
echo $dept_id; // this just dispay requsted id as tab content here you can add your logic for dynamic content based on id
die();
}
?>
And your script js look like this
jQuery(document).ready(function() {
jQuery('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = jQuery(this).attr('id');
console.log(tab_id);
jQuery.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'tabsfunction', id: tab_id}),
success: function(data){
jQuery('#tab'+tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
} });}); });

HTML not working on bootstrap popover when ajax content

I am using bootstrap 3.3 & trying to show ajax content on popover. Here is my jquery code
$('.action_col span').popover({
html: true,
trigger: 'manual',
placement: 'left',
content: function () {
var div_id = 'tmp-id-' + $.now();
var tour_id = $.trim($(this).data('tour_id'));
$.ajax({
type: 'post',
url: site_url + 'controller/tour_details',
dataType: 'html',
data: {
t: tour_id
}
}).done(function (response) {
$('#' + div_id).html(response);
});
return '<div id="' + div_id + '">Loading...</div>';
}
});
tour_details method
echo 'working';
This works fine but when I send any HTML it doesn't work anymore. Like
echo '<div class="popover"> <div class="arrow"></div> <h3 class="popover-title">test</h3> <div class="popover-content"> <p>fgds</p> </div> </div>';
This is not working. Whats wrong here?
My HTML view file
<span data-container="body" data-toggle="popover" data-tour_id="88">[Tour # 48844]</span>

increase php variable in jquery

I have a problem and I do not know if the method I am using is correct.
I want to decrease the variable $ pag -1 if a record is deleted.
I do this because I have a pagination and affects which records are deleted, I must decrease that variable I use in the pagination.
In this code I decreases though it has not eliminated any registration.
How can I do to make me decrease the variable only if a record is deleted?
her code:
<?php $pag=20; ?>
<script type="text/javascript">
$('.delete').live("click",function()
{
var ID = $(this).attr("id");
var dataString = 'id='+ ID;
jConfirm('DELETE?',
function(r) {
if(r==true)
$.ajax({
type: "POST",
url: "delete.php",
data: dataString,
cache: false,
beforeSend: function(){
$("#stbody"+ID).animate({'backgroundColor':'#F2F2F2'},300);},
success: function(html){
$("#body"+ID).fadeOut(300,function(){$("#body"+ID).remove();});
//div update
setTimeout(function() {
$("#apDiv101").load('disminuye.php');
}, 100);
}
});
});
return false;
});
</script>
<!--html delete-->
<a class="delete" href="#" id="<?php echo $id;?>" title="DELETE"></a>
<!--DIV update-->
<div id="apDiv101"><?php
include('disminuye.php');
?></div>
file disminuye.php
<?php
$pag = $pag-1;
echo $pag;
?>

Deleting a list item <li> with jquery?

I'm trying to delete a li item using jquery, but its not working. Here's my code:
the html file:
<li>
<img class="avatar" src="images/$picture" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>$username</strong> $auto
<div class="date">$rel</div>
$reply_info
<div class="date"></div>
<a class ="delbutton" href="#" id = $id> Delete </a>
</div>
<div class="clear"></div>
</li>
The jquery file:
$(function () {
$(".delbutton").click(function () {
var del_id = element.attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function () {}
});
$(this).parents(".record").animate({
backgroundColor: "#fbc7c7"
}, "fast")
.animate({
opacity: "hide"
}, "slow");
}
return false;
});
});
the delete.php file:
<?php
include("includes/connect.php");
if($_POST['id'])
{
$id=$_POST['id'];
$sql = "delete from {$prefix}notes where id='$id'";
mysql_query( $sql);
}
?>
There is no element in your HTML with a class of record. I would try something like this:
<li class="record">
<!-- a bunch of other stuff -->
<a class="delbutton" href="#">Delete</a>
</li>
then in the JS:
$(function ()
{
$(".delbutton").click(function ()
{
if (confirm("..."))
{
$.ajax({ /* ... */});
$(this).closest(".record").fadeOut();
}
return false;
});
});
If your div look like this:
<ul>
<li>One | <a href='#' class='delete'>Delete</a></li>
<li>Two | <a href='#' class='delete'>Delete</a></li>
<li>Three | <a href='#' class='delete'>Delete</a></li>
<li>Four | <a href='#' class='delete'>Delete</a></li>
</ul>
jQuery:
jQuery(document).ready(function(){
jQuery('.delete').live('click', function(event) {
$(this).parent().fadeOut()
});
});​
Check: http://jsfiddle.net/9ekyP/
EDIT:
You can remove your li after getting response in success function something like this:
jQuery(document).ready(function(){
jQuery('.delbutton').live('click', function(event) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
$(this).parent().parent().fadeOut();
}
});
});
});​
There are several issues with your code...
element.attr("id") references undeclared element but this should probably be $(this).attr("id")
The <li> block has no class ".record" either
EDIT: You only fade your <li> but do not actually remove it from the DOM (don't know if this was deliberate though)
The <a>'s ID is not quoted (and not escaped either... as are the other strings you insert in PHP (EDIT) and the ID you use in your delete script - this is very dangerous as it allows cross-site scripting / XSS and SQL injection as TokIk already pointed out)
PHP:
echo '<li class="record">
<img class="avatar" src="images/'.htmlentities($picture).'" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>'.htmlentities($username).'</strong> '.htmlentities($auto).'
<div class="date">'.htmlentities($rel).'</div>'.htmlentities($reply_info).'<div class="date"></div> <a class="delbutton" href="#" id="'.htmlentities($id).'"> Delete </a>
</div>
<div class="clear"></div>
</li>';
JavaScript:
$(document).ready(function() {
$(".delbutton").click(function(){
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
alert('success');
},
error: function(){
alert('error');
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
EDIT: Delete script (note the additional error check that $_POST['id'] exists and the pseudo-function for quoting the ID):
<?php
include("includes/connect.php");
if( isset($_POST['id']) ) {
$id = quote($_POST['id']);
$sql = "delete from {$prefix}notes where id='$id'";
mysql_query( $sql);
}
?>
I am assuming that '.records' is the container.
You can pass through your ID value to make <li> unique, result being:
<li id='record_12'>
//CONTENT
</li>
<li id='record_13'>
//CONTENT
</li>
And change your SUCCESS script to the following:
$(".delbutton").click(function(){
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
//Getting the unique LI and fading it out
$('#record_' + del_id).fadeOut();
}
});
Your code works fine well.I was trying to code a form that has multiple textbox, then after each textbox threre will be link called add which POST call the other php called addnew.php.
In addnew.php data will we added to database(postgres). But I am geting problem while getting the post variable itself.
this is my code for form (I will chage for multiple textbox once it works fine)
script:
<script type='text/javascript'>
$(window).load(function() {
jQuery(document).ready(function() {
jQuery('.add').live('click', function(event) {
var da = $('form#myform').serialize();
alert(da);
$.ajax({
type: "POST",
url: "addnew.php",
data:da,
success: function(data) {
if (data === "ok") {
$(this).parent().fadeOut();
$('#results').html(data);
}
else {
alert(data);
}
}
});
});
});
});
Form
<form name='myform' id='myform'>
<input name='da' type='text' id='da' value='none'>
<a href='#' class='add'>Add</a>
</form>
addnew.php code here
<? php
if( isset($_POST['da']) )
{
echo (da);
}
?>

Categories