Default dropdown option and displaying its default values - php

I have a dropdown select box whose values are populated from a field priority from database. Then, there are three div tags in which, display_duration and arrival and dispatch date are calculated according to the option selected shown.
I am able to perform the required functionality, the code is running smoothly but there is one more condition which is Normal should be selected as default option value and its values should be displayed in the div tags by default.
For now, I am not able to set normal as default value and thus, I am not getting its related values in div tag.
Here's my code:
Database:
CREATE TABLE `tblpriority` (
`priority_id` INT(11) NOT NULL AUTO_INCREMENT,
`priority` VARCHAR(15),
`dispatch_interval_days` INT,
`arrival_interval_days` INT,
`display_duration` VARCHAR(50),
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME,
PRIMARY KEY (`priority_id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;
Query for inserting values:
INSERT INTO `tblpriority` (`priority`,`dispatch_interval_days`,`arrival_interval_days`,`display_duration`) VALUES ('Normal',40,55,'4-6 Weeks');
INSERT INTO `tblpriority` (`priority`,`dispatch_interval_days`,`arrival_interval_days`,`display_duration`) VALUES ('High',30,45,'3-4 Weeks');
INSERT INTO `tblpriority` (`priority`,`dispatch_interval_days`,`arrival_interval_days`,`display_duration`) VALUES ('Low',45,60,'6-8 Weeks');
INSERT INTO `tblpriority` (`priority`,`dispatch_interval_days`,`arrival_interval_days`,`display_duration`) VALUES ('Very High',25,40,'3 Weeks');
index.php(main file)
<?php
use Cosmo\DAL\Order;
$priority_list_data = new Order();
$priority_list = $priority_list_data->getPriorityList();
$priority_option = '<option value=""></option>';
if ($priority_list != false) {
for ($i = 0; $i < count($priority_list); $i++) {
$priority_option .= '<option value= "' . $priority_list[$i]['priority_id'] . '" >' . $priority_list[$i]['priority'] . '</option>';
}
}
?>
<div class="item text-center">
<blockquote>
<div class="row form-group">
<div class="col-md-2 col-sm-1"></div>
<div class="col-md-8 col-sm-10">
<div class="panel panel-default">
<div class="panel-body">
<span class="pull-left">Priority:</span>
<select class="form-control" id="priority_selected">
<?php echo $priority_option; ?>
</select>
<div class="small" id="priority_duration"></div>
</div>
</div>
</div>
<div class="col-md-2 col-sm-1">
</div>
</div>
<div class="row form-group">
<div class="col-md-2 col-sm-1"></div>
<div class="col-md-4 col-sm-5">
<div class="panel panel-default">
<div class="panel-heading">Estimated Dispatch Date:</div>
<div class="panel-body" id="dispatch_date">
<h3></h3>
</div>
</div>
</div>
<div class="col-md-4 col-sm-5">
<div class="panel panel-default">
<div class="panel-heading">Estimated Date of Arrival:</div>
<div class="panel-body" id="arrival_date">
<h3></h3>
</div>
</div>
</div>
<div class="col-md-2 col-sm-1"></div>
</div>
</blockquote>
</div>
<script>
$(document).ready(function () {
$("#priority_selected").change(function () {
var id = $(this).find(":selected").val();
var dataString = 'priority_id=' + id;
$.ajax({
url: '_getprioritydata.php',
dataType: "json",
data: dataString,
cache: false,
success: function (resultData) {
if (resultData['msg'] == 'Success') {
$("#priority_duration").html(resultData.display_duration);
$("#arrival_date").html(resultData.arrival_interval_dates);
$("#dispatch_date").html(resultData.dispatch_interval_dates);
} else if (resultData['msg'] == 'Failed') {
$("#priority_duration").html('');
$("#arrival_date").html('');
$("#dispatch_date").html('');
} else {
$("#priority_duration").html('');
$("#arrival_date").html('');
$("#dispatch_date").html('');
}
}
});
})
});
</script>
Order.php(class file)
<?php
namespace Cosmo\DAL;
Class Order
{
private $db;
public function __construct(){
$config = ConfigSettings::getInstance();
$this->db = DB::getInstance($config->getDatabaseServer(), $config->getDatabaseUsername(), $config->getDatabasePassword(), $config->getDatabaseName());
}
public function getPriorityList(){
$result = $this->db->query("SELECT priority,priority_id FROM tblpriority");
$priority_data = $result->fetchAllArray();
if(count($priority_data)!= 0){
return $priority_data;
}
else{
return false;
}
}
public function getDurationandDates($priority_id)
{
$result = $this->db->query("SELECT display_duration,dispatch_interval_days,arrival_interval_days FROM tblpriority WHERE priority_id='" . $priority_id . "'");
$priorityData = $result->fetchAll();
return $priorityData;
}
}
?>
_getprioritydata.php (json file)
<?php
use Cosmo\DAL\Order;
$response = [];
if (!empty($_REQUEST["priority_id"])) {
$priority_id = $_REQUEST['priority_id'];
$addPriority = new Order();
$priorityData = $addPriority->getDurationandDates($priority_id);
$response['display_duration'] = '';
$response['dispatch_interval_dates'] = '';
$response['arrival_interval_dates'] = '';
if (!empty($priorityData)) {
$curDate = date('d F Y');
$response['msg']= 'Success';
$response['display_duration'] = $priorityData[0]->display_duration;
$response['dispatch_interval_dates'] = date('d F Y', strtotime($curDate. " +{$priorityData[0]->dispatch_interval_days} days"));
$response['arrival_interval_dates'] = date('d F Y', strtotime($curDate. " +{$priorityData[0]->arrival_interval_days} days"));
}
}
else{
$response['msg']= 'Failed';
}
header('Content-Type: application/json');
echo json_encode($response);
exit;

In order to make one of the options selected by default you should include the selected attribute for that specific option:
<option selected="selected">Some option</option>
To clarify, you only need to put the selected attribute on the default option (Replace some condition with what you use to determine the default option):
$priority_list_data = new Order();
$priority_list = $priority_list_data->getPriorityList();
$priority_option = '';
if ($priority_list != false) {
for ($i = 0; $i < count($priority_list); $i++) {
if (<some condition>) {
$is_default = 'selected="selected"';
}
$priority_option .= '<option '. $is_default .' value= "' .
$priority_list[$i]['priority_id'] . '" >' . $priority_list[$i]['priority'] . '</option>';
}
}

Related

PHP function not showing data from dropdown menu

Currently creating 2 dropdown menus, one for category and one for subcategory. My current function shows all data on the page only for subcategories but not for categories. Why is this happening?
Current Functionality: User selects a category, page refreshes and is blank. Once user selects SUBcategory it shows all products in that subcategory.
Desired Functionality: User selects a category, page refreshes and shows all products in that category. Once user selects subcategory it shows all products in that subcategory.
function populate_search_catsub()
{
global $link;
$subcatt = "";
$query = 'SELECT * FROM item';
$result = mysqli_query($link, $query);
$catt = $_GET['catt'];
if (isset($_GET['subcatt'])) {
$subcatt=$_GET['subcatt'];
}
$nbprod = mysqli_query($link, "SELECT * FROM `item` WHERE cat='$catt' AND field='$subcatt'");
if (!isset($_GET['catt']) || $_GET['catt'] == '') {
unset($_GET['catt'], $_GET['submitsearchsub']);
populate_main();
} else {
if (isset($_GET['subcatt'])) {
echo '<span>Search results for Category="'.$catt.' And Sub Category='.$subcatt.'"</span><hr>';
}
$result = mysqli_query($link,"SELECT * FROM `item` WHERE cat='$catt' AND field='$subcatt'");
if ($cat = mysqli_fetch_row($result)) {
echo '
<div class="itemlist">
<span><h3>'.$cat[1].'</h3><h6><u>View</u></h6></span>
<div class="col-lg-12" style="background-color: white;"><br>
<div class="row">
<div class="col-lg-12" style="margin-right: 2%;">
<img src="https://via.placeholder.com/160x210">
</div>
</div><br>
</div>
</div>
<hr>
';
while ($cat = mysqli_fetch_row($result))
echo '
<div class="itemlist">
<span><h3 style="display:inline;">'.$cat[1].'</h3><h6 style="display:inline; margin-left: 1%;"><u>View</u></h6></span>
<div class="col-lg-12" style="background-color: white;"><br>
<div class="row">
<div class="col-lg-2" style="margin-right: 2%;">
<img src="https://via.placeholder.com/160x210">
</div>
</div><br>
</div>
</div>
<hr>
';
} else {
if (isset($_GET['subcatt'])) {
echo "<h2 >No results found</h2>";
}
unset($_GET['catt'], $_GET['submitsearchsub']);
populate_main();
}
}
}
First of all, grab $_GET['catt'] and $_GET['subcatt']. Then, you can build a query based on these parameters. And please, use mysqli_num_rows to check if there are more than zero rows returned.
function populate_search_catsub()
{
global $link;
$catt = $_GET['catt'] ?? ''; // Requires PHP 7.0 or upper.
$subcatt = $_GET['subcatt'] ?? ''; // Requires PHP 7.0 or upper.
$query = 'SELECT * FROM `item`'; // Initial query
if (!$catt) {
unset($_GET['submitsearchsub']);
populate_main();
} else {
$query .= " WHERE `cat` = '{$catt}'";
if ($subcatt) {
echo '<span>Search results for Category="' . $catt . ' And Sub Category=' . $subcatt . '"</span><hr>';
$query .= " AND `field` = '{$subcatt}'";
}
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) { // Check if result set is not empty.
while ($cat = mysqli_fetch_row($result))
echo '
<div class="itemlist">
<span><h3 style="display:inline;">'.$cat[1].'</h3><h6 style="display:inline; margin-left: 1%;"><u>View</u></h6></span>
<div class="col-lg-12" style="background-color: white;"><br>
<div class="row">
<div class="col-lg-2" style="margin-right: 2%;">
<img src="https://via.placeholder.com/160x210">
</div>
</div><br>
</div>
</div>
<hr>
';
} else {
if ($subcatt) {
echo '<h2 >No results found</h2>';
}
unset($_GET['catt'], $_GET['submitsearchsub']);
populate_main();
}
}
}

Bootstrap 4 list group item as a form input value?

I'm redoing the whole post since I had hard time explaining the issue or question.
What this code does:
The user can create a new training session. They can name it and if they want to, they can copy the content from previously created session.
I'm using Bootstrap 4 list group items to show the previous sessions. My problem is that I can not catch the user selection to post the data to activateSaveTrainingSession.php, which includes the SQL query to insert the new data to the database.
I can pass the data from the form to the action php file from inputSessionName -input. As you can see, I've also tried using input type="hidden". It kind of works, but it only uses the $sessionId from the first row it fetches, not the user selection. And thats the problem: how do I catch which list item the user selects, so I can post the data to the activateSaveTrainingSession.php?
<div class="row">
<div class="col-lg-12">
<form class="was-validated" action="activateSaveTrainingSession.php" method="post">
<div class="custom-control">
<div class="form-group">
<label for="inputSessionName" class="float-left"><?php echo $lang['TRAINING_SESSIONNAME_HEADER'] ?></label>
<input type="text" class="form-control" id="inputSessionName" name="inputSessionName" placeholder="Example 1" minlength="3" maxLength="128" required>
<small id="inputSessionNameHelp" class="form-text text-muted">
<?php echo $lang['TRAINING_SESSIONNAME_HELPTEXT'] ?>
</small>
</div>
</div>
<h5 class = "mt-3"><?php echo $lang['TRAINING_COPYSESSION_HEADER'] ?></h5>
<div class="row mt-3">
<div class="col-lg-6 mb-3">
<div class="list-group" id="list-tab" role="tablist">
<a class="list-group-item list-group-item-action active" id="list-doNotCopy-list" data-toggle="list" href="#list-doNotCopy" role="tab" aria-controls="list-doNotCopy">Do not copy</a>
<?php
$stmt = $link->prepare('SELECT `id`, `sessionName`, `createDate` FROM `trainingSessions` WHERE `userId` = ? ORDER BY `id` DESC LIMIT 5');
$stmt->bind_param('i', $currentUserId);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($sessionId, $sessionName, $sessionNameDate);
$sessionCounter = 0;
$tabsArray = array();
if ($stmt->num_rows > 0) {
while ($stmt->fetch()) {
$sessionNameDateFixed = date("d.m.Y", strtotime($sessionNameDate));
$sessionCounter += 1;
$listId = "list-$sessionId-list";
$tabId = "list-$sessionId";
array_push($tabsArray, $sessionId)
?>
<a class="list-group-item list-group-item-action" id="<?php echo $sessionId ?>" data-toggle="list" href="#<?php echo $tabId ?>" role="tab" aria-controls="<?php echo $tabId ?>"><?php echo $sessionName ?><input type='hidden' name='copySession' value='<?php echo $sessionId ?> '/></a>
<?php
}
} else {
echo "No results.";
}
$stmt->close();
echo "Displaying last $sessionCounter records.";
?>
</div>
</div>
<div class="col-lg-6">
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade" id="list-doNotCopy" role="tabpanel" aria-labelledby="list-doNotCopy-list">Do not copy data from previous session.</div>
<?php
foreach ($tabsArray as $session) {
$tabsTextArray = array();
$stmt = $link->prepare('SELECT trainingSessions.id, workouts.workoutName, exercises.setNumber, exercises.reps, exercises.weights FROM workouts INNER JOIN exercises ON workouts.id = exercises.workoutId INNER JOIN trainingSessions on trainingSessions.id = exercises.sessionId WHERE exercises.userId = ? AND trainingSessions.id = ? ORDER BY exercises.id DESC');
$stmt->bind_param('ii', $currentUserId, $session);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($sessionId, $workoutName, $set, $reps, $weights);
if ($stmt->num_rows > 0) {
while ($stmt->fetch()) {
$tabText = "<strong>$workoutName</strong> sarja $set, $reps x $weights kg<br>";
array_push($tabsTextArray, $tabText);
}
}
$listId = "list-$sessionId-list";
$tabId = "list-$sessionId";
?>
<div class = "tab-pane fade" id="<?php echo $tabId ?>" role = "tabpanel" aria-labelledby = "<?php echo $listId ?>"><?php
foreach ($tabsTextArray as $text) {
echo "$text";
}
?>
</div>
<?php
}
$stmt->close();
?>
</div>
</div>
</div>
<button type="submit" name="buttonSaveTrainingSession" class="btn btn-success float-left">
<i class="fas fa-sd-card"></i>
<?php echo $lang['TRAINING_BTN_SAVE'] ?>
</button>
</form>
</div>
</div>
activateSaveTrainingSession.php
<?php
require_once('config/sql.php');
include_once('config/common.php');
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
header("location: login.php");
exit;
}
$currentUserId = $_SESSION["currentUserId"];
$submitButton = strip_tags(trim($_POST['buttonSaveTrainingSession']));
if (isset($submitButton)) {
$inputSessioName = filter_var(trim($_POST["inputSessionName"]), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$copySessionID = filter_var(trim($_POST["copySession"]), FILTER_SANITIZE_NUMBER_INT);
if (empty($inputSessioName) && strlen($inputSessioName) < 3 && $inputSessioName > 128) {
header("location: training.php?msg=invalidSessionName");
} else {
echo "Name: $inputSessioName <br>";
echo "ID: $copySessionID";
}
} else {
header("location: 404.php");
}
?>
I think I understand your problem.
You send in the form several fields:
<input type = 'hidden' name = 'copySession' ...>
which have the same name and not in table form! so it is normal that when receiving the request:
$_POST["copySession"]
you get only one and therefore the first.
If you want to send them all, you have to do:
<input type = 'hidden' name = 'copySession[]' ...>
and you get the request as an array.
foreach($_POST["copySession"] as $sessionId){ ... }
If you want to send only one field, you must make them disabled with javascript in real time during the selection.
For example you put in all fields copySession disabled and you add a class to them. Then you add the same class on the button as well and when the user clicks on a button, the field concerned removes the disabled.
With jQuery something like:
//Click on button
$('a.specialClass').on('click', function(){
//Disabled all copySession inputs
$('input[name="copySession"]').prop('disabled', true);
//Let the field concerned able to be send
$('input.specialClass[name="copySession"]').prop('disabled', false);
});
Good luck!

How to remove an error "Uncaught SyntaxError: Unexpected token S in JSON at position 0"?

I referenced sols of SO, but nothing solve the error.
I have a file dashboard.html with search condition and on click it calls loadtable.js and this loadtable.js file using search.php retrives rows from table,
But there is some error Uncaught SyntaxError: Unexpected token S in JSON at position 0 and also i don't want to display the server returned JSON on client side. Instead this i want to display table and put values in that. I am attaching both loadtable.js and search.php code.
File loadtable.js
$(document).ready(function(){
var delay = 1000;
// Campaign Submit Info
$('[name="search_submit"]').click(function(e){
e.preventDefault();
var lead_status = $('#filterformpost').find('#lead_status_select option:selected').val();
var campaign_status = $('#filterformpost').find('#campaign_status_select option:selected').val();
var company_name = $('#filterformpost').find('#company_name_select option:selected').val();
var tech_area = $('#filterformpost').find('#tech_area_select option:selected').val();
var firm_size = $('#filterformpost').find('#firm_size_select option:selected').val();
var firm_type = $('#filterformpost').find('#firm_type_select option:selected').val();
var country_name = $('#filterformpost').find('#country_name_select option:selected').val();
var state_name = $('#filterformpost').find('#state_name_select option:selected').val();
var start_date = $('#filterformpost').find('#start_date_search').val();
var end_date = $('#filterformpost').find('#end_date_search').val();
console.log(lead_status)
console.log(campaign_status)
console.log(company_name)
console.log(tech_area)
console.log(firm_size)
console.log(firm_type)
console.log(country_name)
console.log(state_name)
console.log(start_date)
console.log(end_date)
$.ajax({
type: "POST",
url: "http://localhost/CRM/server/search.php",
data: {
"lead_status":lead_status,
"campaign_status":campaign_status,
"company_name":company_name,
"tech_area":tech_area,
"firm_size":firm_size,
"firm_type":firm_type,
"country_name":country_name,
"state_name":state_name,
"start_date":start_date,
"end_date":end_date
},
beforeSend: function() {
$('.message_box').html(
'<img src="tenor.gif" width="40" height="40"/>'
);
},
success: function(data)
{
setTimeout(function() {
$('.message_box').html(data);
}, delay);
}
});
$.ajax({
method: "POST",
url: "./server/search.php"
}).done(function( data ) {
var result= $.parseJSON(data);
var string='<table><thead><th>#</th><th>Lead ID</th><th>Name</th><th>Company</th><th>Location</th><th>Communication</th><th>Last Contact Date</th><th>Next Contact Date</th><th>Lead Status</th><th>Details</th></thead><tbody>';
/* from result create a string of data and append to the div */
var i = 1;
$.each( result, function( key, value ) {
string += "<tr><td>"+i+"</td><td>"+value['Lead_Id']+"</td><td>"+value['FirstName']+' '+value['LastName']+"</td><td>"+value['Company']+"</td><td>"+value['State']+'\n'+value['Country']+"</td><td>"+value['Phone']+'\n'+value['Email']+"</td><td>"+value['LastContactDate']+"</td><td>"+value['NextContactDate']+"</td><td>"+value['LeadStatus']+"</td><td><a href='#'>Click Here</a></td></tr>";
i = i+1;
});
string += '</tbody></table>';
$("#filterRecords").html(string);
});
});
});
File search.php
<?php
include('connection.php');
$sqlFlag = 0;
function queryDelimiter(){
global $sqlFlag;
if ($sqlFlag == 0){
$sqlFlag = 1;
return ' WHERE ';
}else{
return ' AND ';
}
}
$selectSQL = "SELECT * FROM tbl_main_lead_info";
if(isset($_POST['lead_status']) and strlen(trim($_POST['lead_status'])) > 0){
$selectSQL .= queryDelimiter()."LeadStatus = '".$_POST['lead_status']."'";
}
if(isset($_POST['company_name']) and strlen(trim($_POST['company_name'])) > 0){
$selectSQL .= queryDelimiter()."Company = '".$_POST['company_name']."'";
}
if(isset($_POST['tech_area']) and strlen(trim($_POST['tech_area'])) > 0){
$selectSQL .= queryDelimiter()."TechArea = '".$_POST['tech_area']."'";
}
if(isset($_POST['firm_size']) and strlen(trim($_POST['firm_size'])) > 0){
$selectSQL .= queryDelimiter()."FirmSize = '".$_POST['firm_size']."'";
}
if(isset($_POST['firm_type']) and strlen(trim($_POST['firm_type'])) > 0){
$selectSQL .= queryDelimiter()."FirmType = '".$_POST['firm_type']."'";
}
if(isset($_POST['country_name']) and strlen(trim($_POST['country_name'])) > 0){
$selectSQL .= queryDelimiter()."Country = '".$_POST['country_name']."'";
}
if(isset($_POST['state_name']) and strlen(trim($_POST['state_name'])) > 0){
$selectSQL .= queryDelimiter()."State = '".$_POST['state_name']."'";
}
if(isset($_POST['start_date']) and strlen(trim($_POST['start_date'])) > 0){
$selectSQL .= queryDelimiter()."LastContactDate >='".$_POST['start_date']."'";
}
if(isset($_POST['end_date']) and strlen(trim($_POST['end_date'])) > 0){
$selectSQL .= queryDelimiter()."NextContactDate <= '".$_POST['end_date']."'";
}
$selectSQL .= " ORDER BY Lead_Id";
$result_array = array();
$result = $conn -> query ($selectSQL);
// If there are results from database push to result array
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result)) {
array_push($result_array, $row);
}
}
// send a JSON encoded array to client
echo json_encode($result_array);
$conn->close();
?>
In dashboard.html i have code as follows
<!-- View Main Lead Table with Filters -->
<section class="operation" id="view_lead_info" style="display: none;">
<!-- Filters -->
<div class="row">
<div class="col">
<label><p><b>Select Filter</b></p></label>
</div>
</div>
<form action='' method='POST' class='filterformpost' id='filterformpost'>
<div class="row">
<div class="col span-1-of-4">
<div class="row">
<div class="col span-1-of-4">
Lead Status:
</div>
<div class="col span-2-of-4">
<select id='lead_status_select'><option value=''>Select</option>
<?php
echo "<option value='All'>All</option>";
echo "<option value='Active'>Active Leads</option>";
echo "<option value='Paused'>Paused Leads</option>";
echo "<option value='Expired'>Expired Leads</option>";
echo "<option value='Unsubscribed'>Unsubscribed</option>";
?>
</select>
</div>
</div>
</div>
<div class="col span-1-of-3">
<div class="row">
<div class="col span-1-of-4">
Campaign Status:
</div>
<div class="col span-2-of-4">
<select id='campaign_status_select'><option value=''>Select</option>
<?php
echo "<option value='All'>All</option>";
echo "<option value='Active'>Active</option>";
echo "<option value='Paused'>Paused</option>";
echo "<option value='Expired'>Expired</option>";
echo "<option value='Unsubscribed'>Unsubscribed</option>";
?>
</select>
</div>
</div>
</div>
<div class="col span-1-of-3">
<div class="row">
<div class="col span-1-of-3">
Company Name:
</div>
<div class="col span-2-of-3">
<?php
include('./server/connection.php');
$sqlSelect="SELECT * FROM tbl_main_lead_info ORDER By Company ASC";
$result = $conn -> query ($sqlSelect);
echo "<select id='company_name_select'>";
echo "<option value=''>select</option>";
echo "<option value='All'>All</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='$row[Company]'> $row[Company] </option>";
}
echo "</select>";
?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col span-1-of-4">
<div class="row">
<div class="col span-1-of-4">
State:
</div>
<div class="col span-2-of-4">
<?php
include('./server/connection.php');
$sqlSelect="SELECT * FROM tbl_state_info ORDER By StateName ASC";
$result = $conn -> query ($sqlSelect);
$result = $conn -> query ($sqlSelect);
echo "<select id='state_name_select' name='StateName'>";
echo "<option value=''>select</option>";
echo "<option value='All'>All</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='$row[StateName]'> $row[StateName] </option>";
}
echo "</select>";
?>
</div>
</div>
</div>
<div class="col span-1-of-3">
<div class="row">
<div class="col span-1-of-4">
Country:
</div>
<div class="col span-2-of-4">
<?php
include('./server/connection.php');
$sqlSelect="SELECT * FROM tbl_country_info ORDER By CountryName ASC";
$result = $conn -> query ($sqlSelect);
$result = $conn -> query ($sqlSelect);
echo "<select id='country_name_select' name='CountryName'>";
echo "<option value=''>select</option>";
echo "<option value='All'>All</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='$row[CountryName]'> $row[CountryName] </option>";
}
echo "</select>";
?>
</div>
</div>
</div>
<div class="col span-1-of-3">
<div class="row">
<div class="col span-1-of-3">
Firm Type:
</div>
<div class="col span-2-of-3">
<?php
include('./server/connection.php');
$sqlSelect="SELECT * FROM tbl_firm_type_info ORDER By FirmType_Value ASC";
$result = $conn -> query ($sqlSelect);
$result = $conn -> query ($sqlSelect);
echo "<select id='firm_type_select' name='FirmType'>";
echo "<option value=''>select</option>";
echo "<option value='All'>All</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='$row[FirmType_Value]'> $row[FirmType_Value] </option>";
}
echo "</select>";
?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col span-1-of-4">
<div class="row">
<div class="col span-1-of-4">
Firm Size:
</div>
<div class="col span-2-of-4">
<?php
include('./server/connection.php');
$sqlSelect="SELECT * FROM tbl_firm_size_info ORDER By FirmSize_Id ASC";
$result = $conn -> query ($sqlSelect);
$result = $conn -> query ($sqlSelect);
echo "<select id='firm_size_select' name='FirmSize'>";
echo "<option value=''>select</option>";
echo "<option value='All'>All</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='$row[FirmSize_Value]'> $row[FirmSize_Value] </option>";
}
echo "</select>";
?>
</div>
</div>
</div>
<div class="col span-1-of-4">
<div class="row">
<div class="col span-1-of-3">
Tech Area:
</div>
<div class="col span-2-of-3">
<?php
include('./server/connection.php');
$sqlSelect="SELECT * FROM tbl_tech_area_info ORDER By TechAreaName ASC";
$result = $conn -> query ($sqlSelect);
$result = $conn -> query ($sqlSelect);
echo "<select id='tech_area_select' name='TechAreaName'>";
echo "<option value=''>select</option>";
echo "<option value='All'>All</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='$row[TechAreaName]'> $row[TechAreaName] </option>";
}
echo "</select>";
?>
</div>
</div>
</div>
<div class="col span-1-of-4">
<div class="row">
<div class="col span-1-of-4">
Start Date:
</div>
<div class="col span-3-of-4">
<?php
echo "<input type='date' id='start_date_search' name='startdate'>";
?>
</div>
</div>
</div>
<div class="col span-1-of-4">
<div class="row">
<div class="col span-1-of-4">
End Date:
</div>
<div class="col span-3-of-4">
<?php
echo "<input type='date' id='end_date_search' name='enddate'>";
?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col span-1-of-3">
<div class="row">
<div class="col span-3-of-4">
</div>
</div>
</div>
<div class="col span-1-of-3">
<div class="row">
<div class="col span-3-of-4">
<div class="row">
<div class="col span-1-of-3">
<label></label>
</div>
<div class="col span-2-of-3">
<input type="submit" name='search_submit' value="Search">
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div class="row">
<div class="col span-1-of-3">
<label></label>
</div>
<div class="col span-2-of-3">
<div class="message_box" style="margin-left: 60px;">
</div>
</div>
</div>
<div class="row">
<div class="col">
<div style="overflow-x:auto;">
<div id="filterRecords"></div>
</div>
</div>
</div>
</section>
You are returning more than just the desired json in your search.php
try removing these lines:
echo $selectSQL;
echo "<p></p>";
echo "<p></p>";
for the json output in the frontend: you have 2 ajax calls in your js file, the first one puts the json into the div with the class message_box
for the results not changing: the results come from the 2nd ajax call, which does not send your form data.
try to change your js to this:
$(document).ready(function() {
var delay = 1000;
// Campaign Submit Info
$('[name="search_submit"]').click(function(e) {
e.preventDefault();
var lead_status = $('#filterformpost').find('#lead_status_select option:selected').val();
var campaign_status = $('#filterformpost').find('#campaign_status_select option:selected').val();
var company_name = $('#filterformpost').find('#company_name_select option:selected').val();
var tech_area = $('#filterformpost').find('#tech_area_select option:selected').val();
var firm_size = $('#filterformpost').find('#firm_size_select option:selected').val();
var firm_type = $('#filterformpost').find('#firm_type_select option:selected').val();
var country_name = $('#filterformpost').find('#country_name_select option:selected').val();
var state_name = $('#filterformpost').find('#state_name_select option:selected').val();
var start_date = $('#filterformpost').find('#start_date_search').val();
var end_date = $('#filterformpost').find('#end_date_search').val();
console.log(lead_status)
console.log(campaign_status)
console.log(company_name)
console.log(tech_area)
console.log(firm_size)
console.log(firm_type)
console.log(country_name)
console.log(state_name)
console.log(start_date)
console.log(end_date)
$.ajax({
type: "POST",
// url: "https://tribalyze.com/CRM/server/login.php",
url: "search.php",
data: {
"lead_status": lead_status,
"campaign_status": campaign_status,
"company_name": company_name,
"tech_area": tech_area,
"firm_size": firm_size,
"firm_type": firm_type,
"country_name": country_name,
"state_name": state_name,
"start_date": start_date,
"end_date": end_date
},
beforeSend: function() {
$('.message_box').html(
'<img src="tenor.gif" width="40" height="40"/>'
);
},
success: function(data) {
var result = $.parseJSON(data);
var string = '<table><thead><th>#</th><th>Lead ID</th><th>Name</th><th>Company</th><th>Location</th><th>Communication</th><th>Last Contact Date</th><th>Next Contact Date</th><th>Lead Status</th><th>Details</th></thead><tbody>';
/* from result create a string of data and append to the div */
var i = 1;
$.each(result, function(key, value) {
string += "<tr><td>" + i + "</td><td>" + value['Lead_Id'] + "</td><td>" + value['FirstName'] + ' ' + value['LastName'] + "</td><td>" + value['Company'] + "</td><td>" + value['State'] + '\n' + value['Country'] + "</td><td>" + value['Phone'] + '\n' + value['Email'] + "</td><td>" + value['LastContactDate'] + "</td><td>" + value['NextContactDate'] + "</td><td>" + value['LeadStatus'] + "</td><td><a href='#'>Click Here</a></td></tr>";
i = i + 1;
});
string += '</tbody></table>';
$("#filterRecords").html(string);
$('.message_box').html('');
}
});
});
});

Can I automatically run an AJAX function when another AJAX function succeeds?

I am about to make a note system in procedural PHP and AJAX, which should allow me to both display new notes without refreshing and to load more notes without refreshing.
In my current case both works, but not together. If no notes to show from the database, then my site will display a text saying "There is no notes to display". If I then make a note, it still won't display the note, until I load it in via a click on the loading notes button.
I've tried to add in following to my success function:
if(res.indexOf("success")!=-1) {
location.reload(true);
}
Without any luck, even I could read on the internet, that it somehow worked out for other people.
Here is my ajax functions:
$(document).ready(function() {
var noteCount = 2;
$("#loadMore").click(function() {
noteCount = noteCount + 2;
$("#notes").load("load-notes.php", {
noteNewCount: noteCount
});
});
$("#noteform").on("submit", function(event) {
event.preventDefault();
noteCount = noteCount + 1;
var form_data = $(this).serialize();
$.ajax({
url: "add-notes.php",
method: "POST",
noteNewCount: noteCount,
data: form_data,
dataType: "JSON",
success: function(data) {
if(res.indexOf("success")!=-1) {
location.reload(true);
}
}
});
});
});
My add-notes.php
<?php
session_start();
require_once "../inc/core/config.php";
if ($_SERVER['REQUEST_METHOD'] != 'POST') exit;
$subject = mysqli_real_escape_string($dbconn, $_POST['subject']);
$note = mysqli_real_escape_string($dbconn, $_POST['note']);
$my_date = date("Y-m-d H:i:s");
$author = $_SESSION['u_firstname'];
$noteNewCount = $_POST['noteNewCount'];
$sql = "INSERT INTO notes(author, subject, note, created_at) VALUES ('$author', '$subject', '$note', '$my_date')";
mysqli_query($dbconn, $sql);
$sql = "SELECT * FROM notes LIMIT $noteNewCount";
$result = mysqli_query($dbconn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<div class="note">
<div class="noteHead">
<div class="row">
<div class="col-md-8">
<h3>' . $row["subject"] . '</h3>
</div>
<div class="col-md-4">
<p class="text-muted">Note created by ' . $row["author"] . '</p>
</div>
</div>
</div>
<div class="noteContent">
<div class="row">
<div class="col-12">
<p>' . $row["note"] . '</p>
</div>
</div>
</div>
<div class="noteFooter">
<div class="row">
<div class="col-12">
<p class="text-muted">Created ' . $row["created_at"] . '</p>
</div>
</div>
</div>
</div>';
}
} else {
echo "No comments yet...";
}
The note div where my notes are displayed and the form where they are created:
<form id="noteform" action="add-notes.php" method="POST" >
<div class="form-group">
<label for="usr">Titel:</label>
<input type="text" class="form-control" name="subject">
</div>
<div class="form-group">
<label for="pwd">Note:</label>
<textarea class="form-control" rows="5" name="note"></textarea>
</div>
<button class="btn btn-outline-success my-2 my-sm-0" name="submit" type="submit">Opret note</button>
</form>
<div id="notes">
<?php
$sql = "SELECT * FROM notes LIMIT 2";
$result = mysqli_query($dbconn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<div class="note">
<div class="noteHead">
<div class="row">
<div class="col-md-8">
<h3>' . $row["subject"] . '</h3>
</div>
<div class="col-md-4">
<p class="text-muted">Note created by ' . $row["author"] . '</p>
</div>
</div>
</div>
<div class="noteContent">
<div class="row">
<div class="col-12">
<p>' . $row["note"] . '</p>
</div>
</div>
</div>
<div class="noteFooter">
<div class="row">
<div class="col-12">
<p class="text-muted">Created ' . $row["created_at"] . '</p>
</div>
</div>
</div>
</div>';
}
} else {
echo "No comments yet...";
}
?>
</div>
So to sum up, I am looking for a way to display a new note made, without having to load it in via my load button. What can I do?
Instead of location.reload, you can just replace the HTML in #notes. Also, in add-notes.php you are echoing HTML but in your ajax, you are expecting dataType: json. Also, not sure what is noteNewCount being passed to AJAX.
$.ajax({
url: "add-notes.php",
method: "POST",
data: form_data,
success: function(data) {
$("#notes").html(data);
}
});

Form loaded into div w/ AJAX no longer submits

Let me start by apologizing for the information overload. I have no idea what is not working, so I included a little of everything here.
I have a page named jobs.php that shows a table of open 'jobs' on the left side. When the add job button is clicked, the form to add a new job is loaded into the div on the right side of the page using this:
//Get Next Job
$query = "SELECT * FROM jobs WHERE job_id = (SELECT MAX(job_id) FROM jobs)";
$result = $mysqli->query($query) or die($mysqli->error . __LINE__);
$topjob = $result->fetch_assoc();
$nxtjob = $topjob['job_id'] + 1;
<button class="btn btn-primary pull-right ajaxCall" id="addJobBtn" onclick="nxtJob('<?php echo $nxtjob; ?>')">Add Job</button>
function nxtJob(job) {
var nxtjob = job;
$("#jobDetails").html("Loading...");
$.ajax({
type: "GET",
data: {'id':nxtjob},
url: "addjob.php",
async: true,
success: function(data) {
$("#jobDetails").html(data);
}
});
}
The reasoning behind the get variable is that I need the next job # to be used as a value in the form.
The form itself is on addjob.php, and the very simplified version is this:
<?php
require 'database.php';
if (isset($_POST['addNewJob'])) {
$error = '';
//Check Job # for duplicate if manually changed
$job = $_POST['addjob'];
$query = "SELECT job_id from jobs WHERE job_id = '$job'";
$result = $mysqli->query($query) or die($mysqli->error . __LINE__);
if (mysqli_num_rows($result) > 0) {
$error .= '<br/>Job # already exists.'
}
if ($error == '') {
//Set variables for insert
$job = $mysqli->real_escape_string($_POST['addjob']);
$status = $mysqli->real_escape_string($_POST['addstatus']);
$sql = "INSERT INTO jobs (job_id, status)
VALUES ('$job', '$status')";
if (mysqli_query($mysqli, $sql)) {
$validation = '< div class="alert alert-success" > Job ' . $job . ' Successfully Added </div >';
} else {
$validation = '<div class="alert alert-danger" > "ERROR: Could not able to execute' . $sql . mysqli_error($mysqli);
}
} else {
$validation = ' <div class="alert alert - danger">Job Not Added:' . $error . '</div>';
}
?>
<form class="form - horizontal" method="post" id="addJobForm">
<div class="form - group">
<label for="addjob" class="col - sm - 2 control - label">Job #</label>
<div class="col - sm - 4">
<input type="text" class="form - control" name="addjob"
value=" <?php echo $nxtjob; ?>">
</div>
<label for="addstatus" class="col-sm-2 control-label">Status</label>
<div class="col-sm-4">
<?php
$options = array("New", "In Progress", "Waiting for Parts", "Ready for Customer", "Completed");
?>
<select class="form-control" name="addstatus">
<?php foreach ($options as $option): ?>
<option>
<?php echo $option; ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
<button type="submit" name="addNewJob" id="addNewJob" class="btn btn-primary pull-right">Submit New
Job
</button>
</form>
<?php echo $validation; ?>
When the add job button is clicked on jobs.php (below), the form loads beautifully, but it doesn't work.
<div class="row">
<div class="col-md-4">
<table class="table table-hover" id="jobTable" data-link="row">
<thead>
<tr>
<th class="col-md-2">Job #</th>
<th class="col-md-4">Customer Name</th>
<th class="col-md-6">Description</th>
</tr>
</thead>
<?php
while ($row = mysqli_fetch_array($jobs)) {
// Print out the contents of the entry
date_default_timezone_set('America/Los_Angeles');
$startdate = date("m/d/Y", strtotime($row['started']));
echo '<tr>';
echo '<td><a class="ajaxCall" href="#" rel="' . $row['job_id'] . '"></a>' . $row['job_id'] . '</td>';
echo '<td>' . $row['cust_name'] . '</td>';
echo '<td class="col-lg-2">' . $row['description'] . '</td>';
echo '</tr>';
}
?>
</tbody>
</table>
</div>
<div class="col-md-8">
<div id='jobDetails'></div>
</div>
</div>
When I click Submit New Job, the right side of the page simply goes blank. The form disappears, and no new entry is created in the sql table. However, the form works just fine if I use it directly from addjob.php.
I've read about binding after an AJAX call, and I'm guessing it has something to do with that, but I can't seem to get it working. This is my first attempt at AJAX, so any help is appreciated.

Categories