How to use AJAX to create/update radio buttons? - javascript

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 and to add the new line suggested. The loadList now empties but doesn't delete itself, as it should. The current problem is that the PHP file won't output the buttons again.

<?php
$username = $_GET['username'];
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic WHERE username = '$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>";
}
?>
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
document.getElementById('loadList').innerHTML="";
document.getElementById("divComics").innerHTML=xmlhttp.responseText;
}
}
ajaxRequest.open("GET", "delCom.php?username=MY_EXACT_NAME_I_KNOW_WORKS_HERE", true);
ajaxRequest.send(null);

There is no element with an id=comicList and you cannot remove it $("#comicList").remove(); in Javascript because it does not exist. Javascript is probably stopping execution at that point, and thereby not displaying your results from PHP.

Related

My php generated form disappears from the HTML page after a second

I am developing a survey form for recreational activities. The user is required to input a location which is then searched in a MYSQL database to ensure that the name entered matches the standard names for locations. The results are to be displayed in a select form to allow the user to choose the specific location.
The query appears to be working correctly. I have verified the return string via an alert window. However, the form appears for a brief second then disappears. I have tried writing the innerHTML string to both a tag and directly to the form. Other posts on this topic that I have found indicated that a form tag is not closed properly. This does not appear to be my problem.
When I run the php script from a test page using hard coded locations, and no other elements on the page, it works just fine.
My js script:
<script> function getLoc(){
var dataRequest;
try {
// Opera 8.0+, Firefox, Safari
dataRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
dataRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
dataRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser needs to be updated to run this
application!");
return false;
}
}
}
dataRequest.onreadystatechange = function() {
if(dataRequest.readyState == 4) {
if (dataRequest.status==200 ||
window.location.href.indexOf("http")==-1){
document.getElementById("locDropDown").innerHTML =
dataRequest.responseText;
}
else{
alert("An error has occured making the request");
}
}
}
var queryString = "";
queryString =
encodeURIComponent(document.getElementById('locStr').value.toUpperCase());
dataRequest.open("POST", "retrieveLoc.php", true);
dataRequest.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
dataRequest.send("searchValue=" + queryString);
}
</script>
<div>
<form id="floc">
<strong>Where Did You Go:</strong> <input type="text" id = "locStr"
placeholder="location">
<input type="submit" value="Search" onclick="getLoc()">
</form>
</div>
<!-- <div id="dataDiv"> -->
<form id="locDropDown">
</form>
<!-- </div> -->
The relevant portion of my php script:
<?php
$queryStr = htmlspecialchars($_POST['searchValue']);
$queryStr .= "%";
// Check sql
$locSql = "SELECT location FROM `location_lkup` \n"
. "WHERE location LIKE '" .$queryStr. "' \n"
. "ORDER BY `location_lkup`.`location` ASC";
$locRslt = $conn->query($locSql);
//Build Result String
/* $display_string = "<form id = 'locDropDown'>"; */
$display_string .= "<select name = 'locChoices'>";
// If returned records >0 insert a new row in the select form for each loc
returned
if ($locRslt -> num_rows > 0) {
$rowcounter = 1;
while($row = $locRslt -> fetch_array(MYSQLI_ASSOC)) {
$display_string .= "<option value = " . $rowcounter . ">" . $row['location']
. "</option>";
$rowcounter++;
}
}
else {
$display_string .= "<option value = '1'> NO DATA </option>" ;
}
$display_string .= "</select>";
$display_string .= "<input type = 'button' value= 'Select' onclick=
'getSelectedloc()'>";
/* $display_string .= "</form>"; */
echo $display_string;
?>
Any suggestions would be greatly appreciated. Thanks.

Why my JS Alert box is not displaying?

I have the following code.
if(isset($_POST['save'])){
$descript = $_POST{'descript'};
$type = $_POST{'type'};
$c_max = $_POST{'c_max'};
$status = $_POST{'status'};
$queryInsert = "INSERT INTO `item_master` (`Item`, `Descript`, `Type`, `C_max`, `Exist`, `Status`) VALUES ('$item', '$descript', '$type', '$c_max', '0', '$status');";
try{
$resultInsert = mysqli_query($conn, $queryInsert);
if($resultInsert)
{
if(mysqli_affected_rows($conn) > 0)
{
echo '<script type="text/javascript">alert("Item Inserted");</script>';
header ("Location: Insertion.php");
}else{
echo '<script type="text/javascript">alert("The item could not be inserted ");</script>';
}
}
} catch (Exception $ex){
echo 'Error Delete '.$ex->getMessage();
}
}
My code works fine my query actually can insert new data in my DB but as the title said my "confirmation" alert is not displaying and I don't understand why. Before my if(isser($_POST['save'])) a JS function runs and ask me if I really want to insert a new data. So obviously I have the pop alerts activated in my browser. So... Im I doing somthing wrong?
Thanks for your comments!
you can use window.location(or other related options like:window.location.href).
if(mysqli_affected_rows($conn) > 0)
{
echo '<script type="text/javascript">alert("Item Inserted");window.location="Insertion.php";</script>';
}else{
echo '<script type="text/javascript">alert("The item could not be inserted ");</script>';
}

Send sql query parameters to function

TABLE wp_thesis TABLE wp_courses
Thesis_ID Thesis_Title Course_ID Thesis_ID Course
1 thesis1 1 1 course1
2 thesis2 2 1 course2
3 2 course1
4 2 course2
5 2 course3
I have a select that calls the showText function onchange.
$query = "SELECT * FROM wp_thesis";
$result = mysqli_query($conn,$query);?>
<select name="ThesisTitle" onchange="showText(x,y)" required="">
<option disabled='disabled' selected='selected' value=''></option>"; <?php
foreach ($result as $row)
{
echo "<option value= {$row[Thesis_ID]}>{$row[Thesis_Title]}</option>";
}
echo"</select><br />";?>
First thought was to send the value of the select (onchange="showText(this.value)") and then have an sql query inside showText function in order to get the two values i wanted. I read that you can't execute sql queries inside functions because Javascript is client-side, so I thought to do the sql query on php and then send the values to showText function. The query I want is this:
$query = "SELECT Course FROM wp_courses WHERE Thesis_ID={$row[Thesis_ID]} ";
$courses = mysqli_query($conn,$query);
$coursesNo = mysqli_num_rows($courses);
Tha values I want to send are $courses and $coursesNo. Is it possiple to get the value of select in the same php file, without using a button or anything like that?
Get X and Y co-ordinate before rendering option and provide it as data attribute.
<select name="ThesisTitle" onchange="showText(this)" required="">
<option disabled='disabled' selected='selected' value=''></option>"; <?php
foreach ($result as $row)
{
echo "<option data-x={$row[Thesis_X]} data-y={$row[Thesis_Y]} value= {$row[Thesis_ID]}>{$row[Thesis_Title]}</option>";
}
echo"</select><br />";?>
Just after that go to showText(this) function with this as parameter and get the attribute with
function showText(obj){
var x_val = $(obj).attr("data-x");
var y_val = $(obj).attr("data-y");
}
Hope this helps to you.
I finally found what I needed. I am posting the code.
<script language="javascript" type="text/javascript">
//Browser Support Code
function showCourses(str){
var ajaxRequest; // The variable that makes Ajax possible!
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("Problem with your browser!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('courses'); // where it should be displayed
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value and pass it to server script.
var queryString = "?thesis_id=" + str ;
ajaxRequest.open("GET", "http://localhost/wordpress/get_thesis/" + queryString, true);
ajaxRequest.send(null);
}
From the select:
<select name="ThesisTitle" id="link_block" onchange="showCourses(this.value)" required="">
<option disabled='disabled' selected='selected' value=''></option>";<?php
foreach ($result as $row)
{
echo "<option value= {$row[Thesis_ID]}>{$row[Thesis_Title]}</option>";
}
echo"</select><br />";?>
I am sending the Thesis_ID to http://localhost/wordpress/get_thesis/ which is a php file that does the query I needed.

onclick javascript on anchor tag html

i am trying to change the select query on click or on change of the button,
the table name field names in the table general are equal to the fragment after page = (About, ContactInformation)
i'm not getting any error nor getting any result
index page code
<script>
function selectQuery(str) {
if (str == "") {
document.getElementById("editor").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("editor").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","queries.php?page="+str,true);
xmlhttp.send();
}
}
</script>
<ul>
<li><i class="fa fa-file-text"></i> About us</li>
<li><i class="fa fa-list-alt"></i> Contact us</li>
</ul>
queries.php page
<?php
$page = intval($_GET['page']);
$result = mysql_query("SELECT general.'".$page."' ".
"FROM general") or trigger_error(mysql_error());
echo $result;
?>
i tried to echo $page in the queries.php file directly but also it is not showing, seems its not even getting here,
so can anyone help pls
You aren't fetching those results. You need to use mysql_fetch_* functions to get those rows. Now the next part is whether you would like to get a JSON response or just output an HTML markup that can be used directly.
Here's what the fetching would look like:
<?php
$page = $_GET['page'];
$data = array();
$result = mysql_query("SELECT general.".$page." FROM general") or trigger_error(mysql_error());
while($row = mysql_fetch_assoc($result)) {
// fetch the results
$data[] = $row;
}
echo json_encode($data);
?>
Obligatory Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Here's a version with mysqli:
<?php
$default_columns = array('About', 'ContactInformation', 'Others', 'Home');
if(isset($_GET['page']) && in_array($_GET['page'], $default_columns)) {
$return_value = array();
$page = $_GET['page'];
$db = new mysqli('localhost', 'username', 'password', 'database');
$sql = "SELECT $page FROM general";
$query = $db->query($sql);
while($row = $query_fetch_assoc()) {
$return_value[] = $row[$page];
}
echo implode(' ', $return_value);
}
?>

jQuery XMLHttpRequest calling External PHP form not submiting

I recently had a friend who specializes in ladder logic and not web programming, come to me requesting help with a project from her employer. While I use more traditional coding languages, I am far from an expert in jquery and php myself. The problem that we are having is that a php page with a jquery / html form inserted into a parent page via XMLHttpRequest, is not executing its "post" action from the parent page. The thing that makes this problem more difficult is that when page is run by itself outside of the parent page (loaded directly into the browser), it executes its "post" action fine. I have done many hours of searching and trial and error at this point but am stumped and now come to you for help. Below are the relevant bits of code. Any help you could provide would be greatly appreciated as nothing we've tried seems to work when it comes to executing the submit of the form when it is inserted via XMLHttpRequest.
Javascript Code From Parent Page inserting external form:
function showUser(str)
{
if (str=="")
{
document.getElementById("insertUserHere").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp.status==200)
{
document.getElementById("insertUserHere").innerHTML=xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","ajax-userForm.php?q="+str,true);
xmlhttp2.send();
}
Code of External PHP page Inserted By xhmlhttprequest (ajax-userForm.php):
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
// JQUERY: Plugin "autoSubmit"
(function($) {
$.fn.autoSubmit = function(options) {
return $.each(this, function() {
// VARIABLES: Input-specific
var input = $(this);
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
var method = form.attr('method');
var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
// ONBLUR: Dynamic value send through Ajax
input.bind('blur', function(event) {
// Get latest value
var value = input.val();
if (input.attr('type') == "checkbox")
{
if (input.attr('checked') )
{
value = 1;
}
else
{
value = 0;
}
}
// AJAX: Send values
$.ajax({
url: action,
type: method,
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
cache: false,
timeout: 10000,
success: function(data) {
// Alert if update failed
if (data) {
alert(data);
}
// Load output into a P
else {
$('#notice').text('Updated');
$('#notice').fadeOut().fadeIn();
}
}
});
// Prevent normal submission of form
return false;
})
});
}
})(jQuery);
// JQUERY: Run .autoSubmit() on all INPUT fields within form
$(function(){
$('#ajax-userForm INPUT').autoSubmit();
});
</script>
<!-- STYLE -->
<style type="text/css">
INPUT { margin-right: 1em }
</style>
</head>
<body>
<!-- CONTENT -->
<?php
$q = intval($_GET['q']);
/*
* DATABASE CONNECTION
*/
// DATABASE: Connection variables
$db_host = "localhost";
$db_name = "DBNAME";
$db_username = "root";
$db_password = "DBPWD";
// DATABASE: Try to connect
if (!$db_connect = mysql_connect($db_host, $db_username, $db_password))
die('Unable to connect to MySQL from ajax-form.');
if (!$db_select = mysql_select_db($db_name, $db_connect))
die('Unable to select database');
/*
* DATABASE QUERY
*/
// DATABASE: Get current row
//$result = mysql_query("SELECT * FROM user");
$result = mysql_query("SELECT * FROM user where Project_ID = '".$q."' ");
$row = mysql_fetch_assoc($result);
?>
<form id="ajax-userForm" class="autosubmit" method="post" action="ajax-updateUser.php">
<fieldset>
<legend>Update user information</legend>
<label>First Name:</label>
<input name="FirstName" value="<?php echo $row['FirstName'] ?>" />
<label>Last Name:</label>
<input name="LastName" value="<?php echo $row['LastName'] ?>" />
<label>Hometown</label>
<input name="Hometown" value="<?php echo $row['Hometown'] ?>" />
<label>Married</label>
<input type = "checkbox" id = "chkMarried" name="Married" <?php echo $row['Married'] == 1 ? 'checked':'unchecked' ?>/>
<label>Employed</label>
<input type = "checkbox" id = "chkEmployed" name="Employed" <?php echo $row['Employed'] == 1 ? 'checked':'unchecked' ?> />
<input id="where" type="hidden" name="Project_ID" value="<?php echo $row['Project_ID'] ?>" />
</fieldset>
</form>
<p id="notice"></p>
</body>
</html>
Code for Page (ajax-updateUser.php) Called by "post" Action in Code Above (ajax-userForm.php):
/*
* DATABASE CONNECTION
*/
// DATABASE: Connection variables
$db_host = "localhost";
$db_name = "DBNAME";
$db_username = "root";
$db_password = "DBPWD";
// DATABASE: Try to connect
if (!$db_connect = mysql_connect($db_host, $db_username, $db_password))
die('Unable to connect to MySQL from ajax-update.');
if (!$db_select = mysql_select_db($db_name, $db_connect))
die('Unable to select database');
$message = "Connection Successful";
//echo "<script type='text/javascript'>alert('$message');</script>";
// DATABASE: Clean data before use
function clean($value)
{
return mysql_real_escape_string($value);
}
/*
* FORM PARSING
*/
// FORM: Variables were posted
if (count($_POST) > 0)
{
$message = count($_POST);
//echo "<script type='text/javascript'>alert('$message');</script>";
// Prepare form variables for database
foreach($_POST as $column => $value)
${$column} = clean($value);
// Perform MySQL UPDATE
$result = mysql_query("UPDATE user SET ".$col."='".$val."'
WHERE ".$w_col."='".$w_val."'")
or die ('Unable to update row.');
}
else
{
$message = "Nothing in Post";
echo "<script type='text/javascript'>alert('$message');</script>";
}
?>
Couple things:
Missing a close quote on your
DBPWD
Your check for status 200 uses:
xmlhttp // whereas the rest is xmlhttp2
My theory, without more context -
You're not using a var keyword when declaring:
xmlhttp2=new XMLHttpRequest();
Which means that the request is attached to the window like this: window.xmlhttp2 = ... - could you be accidentally modifying the same identifiers elsewhere on the "parent" page? That would explain a shared state error and why it works only in isolation (you would have no other code implicitly modding window.xmlhttp2)
You could also be doing bad things with:
xmlhttp2.open("GET","ajax-userForm.php?q="+str,true);
Since I don't know what this path means.
Another one could be, do you have CORS headers set for the request from the external domain?
Cheers,
Andrew

Categories