jeudi 19 février 2015

How to use AJAX to create/update radio buttons?


I currently have a setup where I use a PHP script to create a list of radio buttons by loading the required information from my database. This script is in the HTML structure rather than a separate file, so it requires a page refresh to update the list.


I'd like to figure out how to delete and reload the list upon pressing a button, the ID of which is 'btnDelete' (the actual deletion of items in the database is a separate point that I won't go into here). The current code that I have will delete the list of radio buttons, but when the next line is added, nothing happens (including list deletion).


PHP (delCom.php)



<?php
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic WHERE username = '".$_SESSION['username']."'");
$result = mysqli_query($conn, $query);
while ($row = $result->fetch_assoc())
{
echo "<br><input name='comicList' id='".$row['comicID']."' type='radio' value='".$row['comicID']."'>".$row['comicName']." </option>";
}
?>


JavaScript



function delComic()
{
var ajaxRequest;

try
{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try
{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
$("#loadList").remove();
document.getElementById("divComics").innerHTML=xmlhttp.responseText;
}
}
ajaxRequest.open("GET", "delCom.php?t=", true);
ajaxRequest.send(null);

}


HTML



<div id="divComics">
<p><u>Uploaded Comics</u></p>
<!-- find comics in database -->
<div id="loadList">
<?php
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic WHERE username = '".$_SESSION['username']."' ORDER BY comicName ASC");
$result = mysqli_query($conn, $query);
while ($row = $result->fetch_assoc())
{
echo "<br><input name='comicList' id='".$row['comicID']."' type='radio' value='".$row['comicID']."'>".$row['comicName']." </option>";
}
?>
</div>
<br>
<br>
<input type="button" onclick="delComic()" value="Delete Comic" name="deleteButton" id="btnDelete"/>
</div>


The code creates buttons correctly when run in the HTML, but not when in a separate php file.


Thanks in advance.


EDIT: Updated to fix a few misnamed things. Also, the 'loadList' div needs to be recreated after deletion in the PHP, which I'm not sure how to do. This needs doing because I cannot find a way to delete the list of buttons by themselves.





Aucun commentaire:

Enregistrer un commentaire