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 don't know the specifications of PHP and an ID DIV. Here's my question :
Can I put in the same time an ID DIV named #modal and an ID PHP RETURN ?
while ( $contents_print = mysqli_fetch_array( $req_print ) ) {
echo'
<div class="row print">
<div class="col s12 m4">
<div class="card">
<div class="card-image">
<img data-tags="print" class="activator" src="../00_sources/images/upload/pic_min/' . $contents_print[ 'pic_min' ] . '" alt="' . $contents_print[ 'pic_min' ] . '">
<i class="material-icons">add</i>
</div>
<div class="card-content">
<span class="card-title">'.$contents_print['nom_projet'].'</span>
<p>'.$contents_print['detail_projet'].'</p>
</div>
</div>
</div>
</div>';
}
This is my jquery ajax code :
$(document).ready(function(){
$('.materialboxed').materialbox();
});
$( document ).ready( function () {
$.ajax( {
url: 'core/libs/contents-services.php?action=getFilterContent&id=3',
type: "get",
dataType: "html",
success: function ( reponse ) {
$( '#modal' ).html( reponse );
}
} );
// the "href" attribute of the modal trigger must specify the modal ID that wants to be triggered
$( '.modal' ).modal();
} );
In my ajax code : the line url: 'core/libs/contents-services.php?action=getFilterContent&id=3', I have to use the id from the php/mysql request
I would like to make a link like this :
url: 'core/libs/contents-services.php?action=getFilterContent&id='.$_GET['id'].',
I hope I'am clear
Thanks for your help
http://portfolio.rabahbook.fr to see my working's site
As I understand you get an Id from response and trying to assign it to ajax href. If this is your case, you can do something as below(please note the url_id variable.):
var url_id =3;
$( document ).ready( function () {
$.ajax( {
url: 'core/libs/contents-services.php?action=getFilterContent&id='+url_id,
type: "get",
dataType: "html",
success: function ( reponse ) {
$( '#modal' ).html( reponse );
url_id = response.url_id;/// get url id from response and assign it to
//your href
}
});
// the "href" attribute of the modal trigger must specify the modal ID
//that wants to be triggered
$( '.modal' ).modal();
} );
</script>
$('.post .modal-action').click(function(e){
e.preventDefault();
var id_projet= $(this).data('id_projet');
var $hidennDiv = $('#' +id_projet);
// do your ajax and whatever you want to do with the hidden div
$.ajax( {
url: 'core/libs/contents-services.php?action=getFilterContent&id='+id_projet,
type: "get",
dataType: "html",
success: function ( reponse ) {
$( '#modal' ).html( reponse );
id_projet = reponse.id_projet;
}
} );
$( '.modal' ).modal();
});
This works for me
Thanks all to taking time to anwser to me !
I am trying to change the value of a span after using jQuery.ajax.
JavaScript
$(document).on('click', '.kssico', function(event) {
var for_uid = $(this).parents("li").attr('data'),
for_name = $(this).parents("li").attr('unme'),
dataString = "for_uid=" + for_uid + "&for_name=" + for_name;
$.ajax({
type: "POST",
url: "include/ajax.php",
data: dataString,
success: function (html) {
if(html=="300") {
$('#myModal .modal-body p').html("Error Please Try Again.");
$('#myModal').modal('show');
}
else {
$(this).parents("li span.mi-val").html(html);
$('#myModal .modal-body p').html("The Requested Action Has Been Notified To Your Friend.");
$('#myModal').modal('show');
}
}
});
});
HTML
<li class="mispan main-span" >
<div class="thumbnail">
<h3 class="miheader">Dewashree Singh</h3>
<a >
<div class="miprofile-pic-cnt" ></div>
</a>
<div class="caption">
<p>
<a href="#" class="btn kssico miclickks">
<img src="/lisps.png"><span class="mi-val">0</span>
</a>
<a href="#" class="btn bdico miclickbd">
<img src="/besd.png"><span class="mi-val">1</span>
</a>
</p>
</div>
</div>
</li>
When I click on a.miclickks it should complete the Ajax call and return a value too be placed inside the span on the button anchor. However, nothing is being changed!
jsFiddle
I don't know what your whole code looks like, but you should be able to modify this to do what you are trying to:
$('#id').on('click', function() {
var that = this;
$.ajax({
url: 'wherever.php',
success: function(html) {
$(that).find("li span.mi-val").html(html);
}
});
It looks like you have two problems. The first is that as #Barmar posted above, mi-val is a child of micclickks, not a parent. The second is that your ajax complete function is asynchronous, so $(this) isn't what you expect it will be. Both of these are solvable though.
Your code is a bit messy and your html is missing the proper attributes, but this is I think roughly what you want:
$('.kssico').on('click', function(event) {
var for_uid = $(this).parents("li").attr('data'); //the li element in your html doesn't have a data attribute
var for_name = $(this).parents("li").attr('unme'); //the li element in your html doesn't have a 'unme' attribute
var dataString = "for_uid=" + for_uid + "&for_name=" + for_name;
$.ajax({
type: "POST",
context: this,
url: "include/ajax.php",
data: dataString,
success: function (html) {
if(html=="300")
{
$('#myModal .modal-body p').html("Error Please Try Again.");
$('#myModal').modal('show');
}
else
{
$(this).parents("li span.mi-val").html(html);
$('#myModal .modal-body p').html("The Requested Action Has Been Notified To Your Friend.");
$('#myModal').modal('show');
}
}
});
});
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);
}
?>