How to clear last generated table with new one on radio select - javascript

I am working on a module with 3 radio buttons. Clicking one radio button lists data related to it and so on. I have applied ajax call on radio buttons click and return an array in the response. My problem here is for each radio button click the data keeps on adding into the list. For e.g. if I click on 'All users' radio it displays the data related to "All" but again if I click on "Unapproved Users" radio, the list adds up to the 'All users ' listing at the bottom. So how can I reset the $_POST variable each time the data is rendered so that new list appears for new radio selection, I would really appreciate the help or advice for this.
<script>
$('#selection').change
(
function()
{
var selected_value = $("input[name='users']:checked").val();
//till here the code works fine.
$.ajax
(
{
url: "approval_ajax.php",
dataType : "json",
type: "POST",
cache: false,
data: { selected_value : selected_value },
success: function(response)
{
console.log(response);
var len = response.length;
for(var i=0; i<len; i++){
var id = response[i].id;
var email = response[i].email;
var employee_id = response[i].employee_id;
var first_name = response[i].first_name;
var middle_name = response[i].middle_name;
var last_name = response[i].last_name;
var mobile = response[i].mobile;
var created_on = response[i].created_on;
var disabled = response[i].disabled;
var tr_str = "<tr>" +
"<td>" + (i+1) + "</td>" +
"<td>" + email + "</td>" +
"<td>" + employee_id + "</td>" +
"<td>" + first_name + " " + middle_name + " " + last_name + "</td>" +
"<td>" + mobile + "</td>" +
"<td>" + created_on + "</td>" +
"<td><input type='checkbox' name='check[]'" + disabled + "value= '" + id + "' class='checkbox' id='select_all' ></td>" +
"<input type='hidden' value='" + id + "' name='user_id' id='user_id' >" +
"</tr>";
$("#example").append(tr_str);
}
alert("AJAX was a success");
}
}
);
}
);
</script>
approval_ajax.php
session_start();
require("../includes/config.php");
require("../classes/Database.class.php");
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$return_arr = array();
$status='';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$value = filter_input(INPUT_POST, "selected_value");
if (isset($value))
{
$users=$value;
}else{
$users='';
}
switch ($users)
{
case "all":
$sqlQuery = "SELECT * FROM tbl_user WHERE type =3";
break;
case "approved":
$sqlQuery = "SELECT * FROM tbl_user WHERE type =3 AND status =1";
break;
case "unapproved":
$sqlQuery = "SELECT * FROM tbl_user WHERE type =3 AND status =0";
break;
}
$sq = $db->query($sqlQuery);
if ($db->affected_rows > 0) {
while ($row = mysql_fetch_array($sq)) {
$disabled = '';
if ($status == '1') {
$disabled = "disabled = 'disabled' checked='checked' ";
}
$id = $row['id'];
$email = $row['email'];
$employee_id = $row['employee_id'];
$first_name = $row['first_name'];
$middle_name = $row['middle_name'];
$last_name = $row['last_name'];
$mobile = $row['mobile'];
$created_on1 = $row['created_on'];
$created_on = date("d-m-Y", strtotime($created_on1));
$return_arr[] = array("id" => $id,
"email" => $email,
"employee_id" => $employee_id,
"first_name" => $first_name,
"middle_name" => $middle_name,
"last_name" => $last_name,
"mobile" => $mobile,
"created_on" => $created_on,
"disabled" => $disabled
);
}
}
header('Content-Type: application/json', true, 200);
echo json_encode($return_arr);
}

An append() jQuery function adds html content to requested element. In your case, you want to refresh users list on click of radio select. You need to use html() jQuery function to clear old result and add new result to requested element.
So please modify following line of your code:
$("#example").append(tr_str);
to
$("#example").html(tr_str);
Let me know if it helps.

Related

Empty Div tag issue for dynamically rendered table

I am creating dynamic table and appending it to Div tag on my .php page. On my .php page, I have dynamic buttons and if I click on any of the dynamic buttons, the dynamic table is rendered which has multiple headers and rows (for which I have written for loops with ajax requests). The issue is that, if i click on any of the dynamic buttons again, the current dynamic table data is appended to the previous dynamic table, instead I want to remove previously appended table data and render the current dynamic table data. I tried to empty the div tag but nothing seems working here. Hope I get some help, thanks in advance. Below are my .php and .js files:
.php file- I didnt post the function definition for get_Btns() as it is the basic php function to fetch data from the database:
<?php
function get_Btns() {
include "config.php";
$btns = $stmtDivision->fetchAll(PDO::FETCH_ASSOC);
foreach($btns as $btn){
echo "<input type='button' id='".$btn['divisionid']."' value='".$btn['division_name']."'
onclick=getData('".$btn['divisionid']."') >" ; echo "<br/>"; ?>
<script src="./user.js"></script>
<?php }
}
?>
<?php include "templates/header.php"; ?>
<div id="buttons_panel" style="text-align:center">
<?php echo get_Btns();?> </div>
<div id="div" class="divClass" ></div> <br/>
.js file:
function getData(value) {
document.getElementById("div");
var tableHtml = $('<table></table>');
var selectedManager = value;
var isEmpty = $('#div').empty();
// document.getElementById("div").innerHTML === "";
// document.getElementById("div").HTML === "";
// var isEmpty = $("#div").html() === "";
//$(".divclass").empty();
var teams = null;
$.ajax({
url: 'data.php',
method: 'post',
data: 'selectedManager=' + selectedManager,
async: false,
success: function(data) {
teams = JSON.parse(data);
}
});
for (var k = 0; k < teams.length; k++) {
const selectedteam = teams[k];
var selectedteamid = team[k].teamid;
var htmlth = "";
var html = "";
htmlth = "<tr>" + "<th id='thgrp' colspan='4' background-color: #013466;>" + teams[k].teamname + "</th>" +
"<th colspan='2' background-color: #62b8b6;>" + "<a href='Update.php?groupid=" + selectedteam.teamid + "' >" +
'Update Team member' + "</a>" + "</th>" + "</tr>" +
"<tr>" + "<th>" + "<img src='images/member.png'>" + "<b>" + "<div>" + 'Member' + "</div" + "</th>" +
"<th>" + "<img src='images/phone.png'>" + "<b>" + "<div >" + 'Phone' + "</div" + "</th>" +
"<th>" + "<img src='images/email.png'>" + "<b>" + "<div >" + 'Email' + "</div" + "</th>" + "</tr>";
tableHtml.append(htmlth);
var members = null;
$.ajax({
url: 'data.php',
method: 'post',
data: 'selectedteamid=' + selectedteamid,
async: false,
success: function(data) {
members = JSON.parse(data);
console.log(members);
}
});
for (var i = 0; i < members.length; i++) {
html += "<tr>" + "<td>" + members[i].name + "</td>" +
"<td>" + members[i].phone + "</td>" + "<td>" + members[i].email + "</td>";
}
tableHtml.append(html)
}
$("#div").append(tableHtml);
value = "";
}
Issue solved, I tried to empty the dynamic table that I have created instead of emptying the div tag on my html page. I did this earlier but I didn't do it properly. Thank you so much everyone for your time
This is the code:
tableHtml.attr('id', 'tableHtmlId');
$('#tableHtmlId').empty();

Javascript input field value

Need to get the value of input field inside script tag.
I need to get a value of input field that append to the html table using script tag. My code is following
function myFunction(i) {
$.ajax({
url: "<?php echo base_url(); ?>admin/itemD",
type: "POST",
dataType: "json",
data: {
"itID": i
},
success: function(data) {
//console.log(data);
if (data[0].availability == 0) {
alert('Item Not Available');
} else {
var tr = "<tr>";
var td0 = "<td>" + (i + 1) + "</td>";
var td1 = "<td>" + data[0].item_name + "</td>";
var td2 = "<td>" + data[0].price + "</td>";
var td3 = "<td><input placeholder='Advance' class='form-control col-3' /></td>"
$("#myTable").append(tr + td0 + td1 + td2 + td3);
}
},
error: function(err) {
console.log(err);
}
});
}
This is my code I used this code to show some data set which get from clicking event. But now I need to add input field to my javascript code. So I add input field to my code.
var td3 = "<td><input placeholder='Advance' id='vale' class='form-control col-3' /></td>"
But how do I get this input field value?
I tried to get the value of this input field by adding
document.getElementById('vale');
But It does not work. I go though the every problem earlier posted in stackoverflow. But no problem matching with my problem.
One way to achieve this might be to update your success handler, by binding an event handler via say, keyup(), that queries the current value of the input field when a key is pressed while the field is focused:
success: function(data) {
//console.log(data);
if (data[0].availability == 0) {
alert('Item Not Available');
} else {
var tr = "<tr>";
var td0 = "<td>" + (i + 1) + "</td>";
var td1 = "<td>" + data[0].item_name + "</td>";
var td2 = "<td>" + data[0].price + "</td>";
var td3 = "<td><input placeholder='Advance' class='form-control col-3' /></td>"
$("#myTable").append(tr + td0 + td1 + td2 + td3);
}
// Select the input field for the table, and add a keyup event listener
// to it
$('input', '#myTable').keyup(function() {
// Access the current value of the field like so
var currentFieldValue = $('input', '#myTable').val();
alert( 'Value of input is: ' + currentFieldValue );
})
}
You need to add id='vale' attributes which is not available in your input tag
After that you can get value by like this:
document.getElementById('vale').value

jQuery not pushing JSON-data

I have the following script which is supposed to pull data and display it in a HTML table:
$('#search_filter_button').click(function (e) {
e.preventDefault(); // Stop form submission
var county = $('#filter_county').val(),
kp_type = $('#filter_kp_type').val(),
getUrl = window.location,
baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
html_tr = '';
$.ajax({
type: 'GET',
url: baseUrl + "/reports/get_report.php?county=" + county + "&kp_type=" + kp_type,
dataType: "JSON",
success: function (data) {
console.log(data);
for (i = 0; i < data.length; i++) {
html_tr += '<tr>\n\
<td>' + data[i].name + '</td>\n\
<td>' + data[i].Abbrv + '</td>\n\\n\
<td>' + data[i].partner_name + '</td>\n\\n\
<td>' + data[i].facility_name + '</td>\n\\n\
<td>' + data[i].county + '</td>\n\\n\
<td>' + data[i].no_kps + '</td>\n\\n\
<td>' + data[i].activity_stamp + '</td>\n\</tr>';
}
$('#tbody_append').empty();
$('#tbody_append').append(html_tr);
}, error: function (data) {
}
});
});
My get_report.php file looks like this:
include '../database/db_connect.php';
$mysqli = mysqli_connect($host_name, $user_name, $password, $database);
$county = $_GET['county'];
$kp_type = $_GET['kp_type'];
// get the records from the database
$result = mysqli_query($mysqli, "SELECT * FROM `no_individaul_kps_contacted` where county='$county'");
$count_row = mysqli_num_rows($result);
if ($count_row >= 1) {
// display records if there are records to display
while ($user_data = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo json_encode($user_data);
}
} else {
// show an error if there is an issue with the database query
echo "Error: " . $mysqli->error;
}
// close database connection
mysqli_close($mysqli);
This pulls the information and echoes it back in JSON ENCODE format. But my JavaScript is not returning a success.
Please advise what am I doing wrong.
Collect the user data into array inside the while loop and move json_encode($data) outside the while loop:
$select = "SELECT * FROM `no_individaul_kps_contacted` where county='$county'";
$result = mysqli_query($mysqli, $select);
$data = [];
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$data[] = $row;
}
echo json_encode($data);

Assigning ViewBag property in javascript

I am trying to assign a JS variable to a ViewBag property and use that property in an Html ActionLink.
However, I'm getting a design time compile error: "Syntax error" right below the getJSON method as #ViewBag.CustomerID = data.CustomerID;
Can someone help me out with how this is done?
Here is my code:
#Html.ActionLink("Click to edit Customer", "EditCust", "Customer", new { ViewBag.CustomerID }, null);
<script type="text/javascript">
$(function ()
{
var selID = null
$("#Name").change(function ()
{
selID = $("#Name option:selected").val();
var url = '/Project/SpecificCustomer';
var param = { Id: selID };
$.getJSON(url, param, function (data)
{
#ViewBag.CustomerID = data.CustomerID;
var html = "<table border='1' cellpadding='3'>";
html += "<tr>";
html += "<td>" + "Customer ID: " + data.CustomerID + "</td>";
html += "</tr>";
html += "<tr>";
html += "<td>" + "Email: " + data.Email + "</td>";
html += "</tr>";
html += "<tr>";
var FirstName = data.FirstName;
FirstName == null ? "" : FirstName;
var LastName = data.LastName;
LastName == null ? "" : LastName;
html += "<td>" + "Name: " + FirstName + " " + LastName + "</td>";
html += "</tr>";
html += "<tr>";
var date1 = new Date(parseInt(data.CreatedDate.substr(6)));
date1 == null ? "" : date1;
html += "<td>" + "Created: " + date1 + "</td>";
html += "</tr>";
html += "<tr>";
var date2 = new Date(parseInt(data.UpdatedDate.substr(6)));
date2 == null ? "" : date2;
html += "<td>" + "Updated: " + date2 + "</td>";
html += "</tr>";
html += "</table>";
$("#divData").html('');
$("#divData").append(html);
});
});
});
</script>
This won't work. ViewBag works on server side and it will be out of scope when you get the response of an AJAX request. You should use JavaScript to update the values in your view once you get the response.
You also get the error because an assignment should be in a code block:
#{ ViewBag.CustomerID = data.CustomerID; }
However this still won't work because data is a JavaScript variable.

Passing a hiddenfield form value to a Controller

I have a jQuery getJson method which correctly returns a selected CustomerID. When that happens, a button is enabled to send the CustomerID to another Controller method which would then open up a form to modify the customer.
I check the Form collection, but there is no value associated with the ID of the Collection. It simply comes out as "CustomerID" with no value.
How can I successfully pass this value to the other Controller with the Form Collection?
I know that the script section contains the var CustomerID and the BeginForm has the hiddenfield value, but obviously, there is no "linkage" between the two. I'm wondering how I can do this...
So basically, how can I get the JS variable value inside CustomerID into the Form?
JS
#section scripts {
<script type="text/javascript">
$(function ()
{
var selID = null;
var CustomerID = null;
$("#Name").change(function ()
{
selID = $("#Name option:selected").val();
var url = '/Project/SpecificCustomer';
var param = { Id: selID };
$.getJSON(url, param, function (data)
{
var html = "<table border='1' cellpadding='3'>";
html += "<tr>";
html += "<td>" + "Customer ID: " + data.CustomerID + "</td>";
CustomerID = data.CustomerID;
html += "</tr>";
html += "<tr>";
html += "<td>" + "Email: " + data.Email + "</td>";
html += "</tr>";
html += "<tr>";
var FirstName = data.FirstName;
FirstName == null ? "" : FirstName;
var LastName = data.LastName;
LastName == null ? "" : LastName;
html += "<td>" + "Name: " + FirstName + " " + LastName + "</td>";
html += "</tr>";
html += "<tr>";
var date1 = new Date(parseInt(data.CreatedDate.substr(6)));
date1 == null ? "" : date1;
html += "<td>" + "Created: " + date1 + "</td>";
html += "</tr>";
html += "<tr>";
var date2 = new Date(parseInt(data.UpdatedDate.substr(6)));
date2 == null ? "" : date2;
html += "<td>" + "Updated: " + date2 + "</td>";
html += "</tr>";
html += "</table>";
$("#divData").html('');
$("#divData").append(html);
if (CustomerID != null)
$("#UpdateCust").prop('disabled', false);
});
});
});
</script>
}
#using (Html.BeginForm("Index", "Customer", new AjaxOptions { HttpMethod = "POST" }))
{
<fieldset>
<legend>Edit Customer</legend>
<div class="editor-field">
<input type="hidden" id="custID" name="custID" value="CustomerID" />
<input type="submit" id="UpdateCust" value='#Resources.Update' disabled="disabled" />
</div>
</fieldset>
}
Other Controller method
public ActionResult Index(FormCollection form)
{
string custID = form["custID"];
...
It's not clear, but if the form resides on the same page as the getJSON script, then you could change the last lines of your JavaScript to be:
if (CustomerID != null) {
$("#UpdateCust").prop('disabled', false);
$("#custID").val(data.CustomerID);
}

Categories

Resources