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 need help with a button for loading more data from the database. I've found examples, but too bad ones. Here is what I have so far:
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'ajax_more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('.tutorial_list').append(html);
}
});
});
});
You can follow below technique to load more data with just replacing morebox html.
blog.php
<div class="tutorial_list">
<!-- LOAD YOUR PHP BLOG DATA -->
<div class="loading"><img src="fb-load.gif"/></div>
<!-- More Button here $ID values is a last post id value. -->
<div id="show_more<?php echo $ID; ?>" class="morebox">
more
</div>
</div>
<script>
$(document).on('click', '.show_more', function() {
{
var ID = $(this).attr("id");
if (ID) {
$('.morebox').hide();
$('.loding').show();
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastpost=" + ID,
cache: false,
success: function(html) {
$('.loading').hide();
$('.tutorial_list').append(html);
$("#show_more" + ID).remove(); // removing old more button
}
});
} else {
$(".morebox").html('The End'); // no results
}
return false;
});
</script>
ajax_more.php
<!-- LOAD YOUR PHP BLOG DATA WITH lastpost ID and remember to add below code for load more -->
<!-- More Button here $ID values is a last post id value. -->
<div id="show_more<?php echo $ID; ?>" class="morebox">
more
</div>
I am new to jQuery so please don't judge me too harshly!
I'm making a page which lists videos, under each video there is a voting button. The button works in 2 stages, first you click it which expands the button, then the second click should confirm the vote using PHP/Ajax. If you click another button before submitting it should reset the first.
I put together the below to try and accomplish this, the first section is to expand the button, then the second is to submit the vote. It kind of works, but I noticed that if you click on one button, then another, then back to the first it submits the vote. Any ideas of how I can get this working? Or a better way of working?
Thanks in advance!
<script>
$(window).load(function(){
$("ul li .button").click(function() {
$("ul li .button").removeClass("active-button");
$("ul li .button").text("Vote for this");
$(this).addClass("active-button");
$(this).text("Submit vote");
stop;
});
});
$(document).on("click", "ul li .button", function () {
if ( $(this).hasClass( "active-button" ) ) {
$("ul li .active-button").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='up')
{
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
});
}
});
</script>
<ul class="videos clearfix">
<?php include('config.php');
$sql=mysql_query("SELECT * FROM messages LIMIT 4");
while($row=mysql_fetch_array($sql))
{
$msg=$row['msg'];
$mes_id=$row['mes_id'];
$up=$row['up'];
$title=$row['title'];
?>
<li>
<h2><?php echo $title; ?></h2>
<?php echo $msg; ?>
<div id="<?php echo $mes_id; ?>" name="up" class="button vote">Vote for this</div>
</li>
?php } ?>
</ul>
Dont have two seperate click handlers, combine them into one:
$(document).on("click", "ul li .button", function () {
if ( $(this).hasClass( "active-button" ) ) {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='up')
{
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
}else{
$("ul li .button").removeClass("active-button");
$("ul li .button").text("Vote for this");
$(this).addClass("active-button");
$(this).text("Submit vote");
}
});
I am trying to use the code bellow to reveal a div that contains a loading image for all divs but I cannot make it work.
For example I have 4 divs and inside those divs I have included the div that holds the image loading icon. Each div has a button with same class name.
Every time that I press the button the div that holds the loading image appears only in the first div.
P.S I want to keep this structure because I am grabbing some attributes from <a href>
My Jquery Code:
<script type="text/javascript">
$(document).ready(function() {
$(".mybutton").click(function() {
var id = $(this).attr("id");
var title = $(this).attr("title");
var dataString = 'id='+ id;
$('#myloader').fadeIn("fast");
$.ajax({
type: "POST",
url: "getvars.php",
data: dataString,
cache: false,
success: function(html) {
$('#myloader').fadeOut("fast");
}
});
});
});
</script>
And my html Code:
<!-- Div 1 -->
<div id="Master" style="width:100px; height:100px;">
<div id="myloader" style="width:50px; height:50px; display:none;">Wait...</div>
Press me
</div>
<!-- Div 2 -->
<div id="Master" style="width:100px; height:100px;">
<div id="myloader" style="width:50px; height:50px; display:none;">Wait...</div>
Press me
</div>
It is because you are using a div id and it should be unique on a HTML document, so you should replace #myloader with .myloader
and of course <div id="myloader" to <div class="myloader"
You are using same id for multiple elements. There should be only one element having an id.
Try this:
$(".mybutton").click(function()
{
var b = this;
var id = $(this).attr("id");
var title = $(this).attr("title");
var dataString = 'id='+ id;
$('#myloader').fadeIn("fast");
$.ajax({
type: "POST",
url: "getvars.php",
data: dataString,
cache: false,
success: function(html)
{
$(b).siblings('div')[0].fadeOut("fast");
}
});
});
});
ID should always be unique( that is why it is called ID..:) )..so
replace #myloader with .myloader and <div id="myloader" to <div class="myloader" ..and you can use prev() jquery function to get the div with loading...
your codes should look like this
$(document).ready(function() {
$(".mybutton").click(function()
{
var id = $(this).attr("id");
var title = $(this).attr("title");
var dataString = 'id='+ id;
$(this).prev().fadeIn("fast"); //chnages here
$.ajax({
type: "POST",
url: "getvars.php",
data: dataString,
cache: false,
success: function(html)
{
$(this).prev().fadeOut("fast"); //and here
}
});
});
});
Change <div id="myloader" to <div class="myloader" and then change JS as:
<script type="text/javascript">
$(document).ready(function() {
$(".mybutton").click(function() {
var id = $(this).attr("id");
var title = $(this).attr("title");
var dataString = 'id='+ id;
var $loader = $(this).parent().find('.myloader'); //Change this
$.ajax({
type: "POST",
url: "getvars.php",
data: dataString,
cache: false,
beforeSend: function() { //Change this
$loader.fadeIn("fast");
}
success: function(html) {
$loader.fadeOut("fast"); //Change this
}
});
});
});
</script>
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);
}
?>