Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery function only working once?

Tags:

html

jquery

php

I have this function that is suppose to change the html of a span. It works the first time but anyclick after that it doesn't change anything. I know the query is working because the database is updating. Here's the code.

$('#availabilityicon').click(function() {
    $.ajax({
            type: "GET",
            url: "includes/changeavailability.php",
            success: function(msg) {
                    if(msg === "available") {
                            var vailspan = $('span#avail').html('<a id="availabilityicon" href="#"><img align="center" width="16px" height="16px" src="images/available.png" /></a>');
                    }
                    else if(msg === "unavailable") {
                            var availspan = $('span#avail').html('<a id="availabilityicon" href="#"><img align="center" width="16px" height="16px" src="images/unavailable.png" /></a>');
                    }
            }
    });
});

here is the php code

<?php
session_start();
$user = $_SESSION['username'];
include("dbcon.php");
$result = mysql_query("SELECT availability FROM user WHERE username='$user' ORDER BY id DESC") or die(mysql_error());
$row = mysql_fetch_assoc($result);
$availability = $row['availability'];
if($availability == 'yes') { 
$query = mysql_query("UPDATE user SET availability='no' WHERE username='$user'") or die(mysql_error());
echo "unavailable"; 
}
elseif($availability == 'no' or $availability == "") { 
$query = mysql_query("UPDATE user SET availability='yes' WHERE username='$user'") or die(mysql_error()); 
echo "available"; 
}
mysql_close($con);
?>
like image 406
vacarsu Avatar asked Jun 30 '26 11:06

vacarsu


2 Answers

There's a spelling mistake in your javascript, you've put vailspan where you probably meant to put availspan after the if(msg === "available") { line.

If it's not that, try changing the click event to a live one:

$('#availabilityicon').live('click', function() {

just in case your javascript is overwriting that the #availabilityicon icon element and failing to re-attach the event to the new one

like image 59
Clive Avatar answered Jul 02 '26 23:07

Clive


The "availabiltyicon" you click is being replaced with another with the same name. You can try using .live() or you can read up on event delegation.

like image 26
Bill Criswell Avatar answered Jul 03 '26 01:07

Bill Criswell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!