Probably there are lots of similar posts here in StackOverflow, but my scenario is a bit different. So, I decided to post this question using this title.
I'd like to describe my problem in small parts:
Part - 1:
I have a normal view page, where I can select specific date. This part is working.
enter image description here
Part - 2:
The view page will show some data for the selected date(by default, it's the current date).
For example, on 2 November, 2014, there are some data. They will be displayed on load as such:
enter image description here
But, these data are coming from another view page, which I have loaded here using ajax call. I've done so because I want to restrict the displayed data to the selected date only. This part is also working.
Part - 3:
This is the main problem description. This is the part which is not working.
To further restrict the amount of data to be displayed, I'm using pagination. The pagination is working fine, except for the active link part. No matter which link I click, the selected link by default is only the first one.
enter image description here
In the above picture, I have selected link 2, but link 1 is shown to be active instead of link 2.
So my view -
<fieldset>
<legend id="meal_view_page_legend">Meal</legend>
<div id="content" class="box">
<button id="button_add">Add Meal</button>
<br>
<br>
<div>
<?php
if (isset($message)) {
if ($message == 'Meal information added successfully' || $message == 'Meal information edited successfully' || $message == 'Meal information deleted successfully') {
?>
<p class="msg done">
<?php echo $message; ?>
</p>
<?php
} else if ($message == 'Employee ID doesn\'t exist') {
?>
<p class="msg error">
<?php echo $message; ?>
</p>
<?php
}
}
?>
</div>
<label style="font-weight: bold">Select Date: </label>
<select onchange="ajaxGetInfoByDate()" id="day" name="day">
<!--option selected><--?php echo $day; ?></option-->
<option <?php if(date("d")=='01'){ ?> selected <?php } ?>>01</option>
<option <?php if(date("d")=='02'){ ?> selected <?php } ?> >02</option>
<option <?php if(date("d")=='03'){ ?> selected <?php } ?>>03</option>
<option <?php if(date("d")=='04'){ ?> selected <?php } ?>>04</option>
<option <?php if(date("d")=='05'){ ?> selected <?php } ?>>05</option>
<option <?php if(date("d")=='06'){ ?> selected <?php } ?>>06</option>
<option <?php if(date("d")=='07'){ ?> selected <?php } ?>>07</option>
<option <?php if(date("d")=='08'){ ?> selected <?php } ?>>08</option>
<option <?php if(date("d")=='09'){ ?> selected <?php } ?>>09</option>
<option <?php if(date("d")=='10'){ ?> selected <?php } ?>>10</option>
<option <?php if(date("d")=='11'){ ?> selected <?php } ?>>11</option>
<option <?php if(date("d")=='12'){ ?> selected <?php } ?>>12</option>
<option <?php if(date("d")=='13'){ ?> selected <?php } ?>>13</option>
<option <?php if(date("d")=='14'){ ?> selected <?php } ?>>14</option>
<option <?php if(date("d")=='15'){ ?> selected <?php } ?>>15</option>
<option <?php if(date("d")=='16'){ ?> selected <?php } ?>>16</option>
<option <?php if(date("d")=='17'){ ?> selected <?php } ?> >17</option>
<option <?php if(date("d")=='18'){ ?> selected <?php } ?>>18</option>
<option <?php if(date("d")=='19'){ ?> selected <?php } ?>>19</option>
<option <?php if(date("d")=='20'){ ?> selected <?php } ?>>20</option>
<option <?php if(date("d")=='21'){ ?> selected <?php } ?>>21</option>
<option <?php if(date("d")=='22'){ ?> selected <?php } ?>>22</option>
<option <?php if(date("d")=='23'){ ?> selected <?php } ?>>23</option>
<option <?php if(date("d")=='24'){ ?> selected <?php } ?>>24</option>
<option <?php if(date("d")=='25'){ ?> selected <?php } ?>>25</option>
<option <?php if(date("d")=='26'){ ?> selected <?php } ?>>26</option>
<option <?php if(date("d")=='27'){ ?> selected <?php } ?>>27</option>
<option <?php if(date("d")=='28'){ ?> selected <?php } ?>>28</option>
<option <?php if(date("d")=='29'){ ?> selected <?php } ?>>29</option>
<option <?php if(date("d")=='30'){ ?> selected <?php } ?>>30</option>
<option <?php if(date("d")=='31'){ ?> selected <?php } ?>>31</option>
</select>
<select onchange="ajaxGetInfoByDate()" id="month" name="month" >
<!--option selected><--?php echo $month; ?></option-->
<option <?php if(date("m")=='01'){ ?> selected <?php } ?>>01</option>
<option <?php if(date("m")=='02'){ ?> selected <?php } ?>>02</option>
<option <?php if(date("m")=='03'){ ?> selected <?php } ?>>03</option>
<option <?php if(date("m")=='04'){ ?> selected <?php } ?>>04</option>
<option <?php if(date("m")=='05'){ ?> selected <?php } ?>>05</option>
<option <?php if(date("m")=='06'){ ?> selected <?php } ?>>06</option>
<option <?php if(date("m")=='07'){ ?> selected <?php } ?>>07</option>
<option <?php if(date("m")=='08'){ ?> selected <?php } ?>>08</option>
<option <?php if(date("m")=='09'){ ?> selected <?php } ?>>09</option>
<option <?php if(date("m")=='10'){ ?> selected <?php } ?>>10</option>
<option <?php if(date("m")=='11'){ ?> selected <?php } ?>>11</option>
<option <?php if(date("m")=='12'){ ?> selected <?php } ?>>12</option>
</select>
<select onchange="ajaxGetInfoByDate()" id="year" name="year">
<!--option selected><--?php echo $year; ?></option-->
<option <?php if(date("y")=='14'){ ?> selected <?php } ?>>2014</option>
<option <?php if(date("y")=='15'){ ?> selected <?php } ?>>2015</option>
<option <?php if(date("y")=='16'){ ?> selected <?php } ?>>2016</option>
<option <?php if(date("y")=='17'){ ?> selected <?php } ?>>2017</option>
</select>
<div id="indexView"></div>
</fieldset>
And another view page, the one that I have loaded inside the above view page using ajax load:
<fieldset>
<table id = "meal_list_table">
<tr>
<th scope="col" >Employee Id</th>
<th scope="col" >Guest?</th>
<th scope="col" >No. of Guest</th>
<th scope="col" >Remarks</th>
<th scope="col" colspan="2" >Action</th>
</tr>
<?php foreach ($info as $list) { ?>
<tr>
<td><?php echo $list['emp_id']; ?></td>
<td><?php echo $list['is_guest']; ?></td>
<td><?php echo $list['num_of_guest']; ?></td>
<td><?php echo $list['remarks']; ?></td>
<td><button id="button_edit">Edit</button></td>
<td>
<a href="<?php echo base_url(); ?>index.php/admin_logins/meal4/<?php echo $list['id']; ?>"
onclick="return confirm('Do you want to delete this Meal Information?');">
<button id="button_delete">Delete</button>
</a>
</td>
</tr>
<?php } ?>
</table>
<p><?php echo $links; ?></p>
</fieldset>
The ajax call(in first view page):
function ajaxGetInfoByDate() {
//alert("ok");
var offset = document.getElementById("offset").value;
var day = document.getElementById("day").value;
var month = document.getElementById("month").value;
var year = document.getElementById("year").value;
var date = year + '-' + month + '-' + day;
//alert(offset);
// alert(date);
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("indexView").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "<?php echo base_url(); ?>index.php/admin_logins/ajaxGetInfo?date=" + date + "&&offset=" + offset, true);
xmlhttp.send();
}
Controller method to view the first view page:
function meal() {
$data['message'] = $this->session->flashdata('message');
$this->load->view('/admin_logins/meal_list', $data);
}
And controller method to load the second view page by ajax call:
function ajaxGetInfo() {
$customDate = $this->input->get('date');
$offset = $this->input->get('offset');
$query_string = "SELECT m.id, e.emp_id, m.is_guest, m.num_of_guest, m.remarks
FROM meal m
LEFT JOIN employee e
ON e.id = m.emp_id
WHERE m.entry_date ='$customDate' ";
$query = $this->db->query($query_string);
//pagination codes
$config = array();
$config['base_url'] = site_url('admin_logins/meal');
$config['per_page'] = 10;
$config['uri_segment'] = 3;
$config['total_rows'] = $query->num_rows();
$choice = $config['total_rows'] / $config['per_page'];
$config['num_links'] = round($choice);
$this->pagination->initialize($config);
$page = ($offset) ? $offset : 0 ;
$conf = $config['per_page'];
$query_string2 = "SELECT m.id, e.emp_id, m.is_guest, m.num_of_guest, m.remarks
FROM meal m
LEFT JOIN employee e
ON e.id = m.emp_id
WHERE m.entry_date ='$customDate'
LIMIT $page, $conf ";
$query2 = $this->db->query($query_string2);
$dataByDate['info'] = $query2->result_array();
//echo "<pre>";
//print_r($dataByDate['info']);
//die();
$dataByDate['links'] = $this->pagination->create_links();
$this->load->view('admin_logins/ajaxIndex', $dataByDate);
}
What/where is wrong in my code?
Did you check what value $offset returns and if it is the correct value ?
Related
JQuery connected, AJAX probably works correctly, because when I change select in the console the values are correct. But the query to the database doesn't change. Checking var_dump($_POST['filter']) shows that there value from previous request.
If I wrap select in a form and send it via POST using submit button, the requests are sent.
Where can there be an error here?
And how to add a condition, so that when selecting "All" the query will just be to all items "SELECT * FROM orders, without the condition "WHERE?
<script>
$('#filter').change(function() {
$.ajax({
method: "POST",
url: "thispage.php",
data: {
filter: $("#filter").val()
},
success: function(response) {
console.log($("#filter").val())
}
});
});
</script>
<?php
require_once __DIR__ . "/database/database.php";
$item1 = $_POST['item1'];
$worker_name = $_POST['worker_name'];
$worker_company = $_POST['worker_company'];
$errors = [];
if (empty($item1)) {
$errors['item1'] = true;
}
if (empty($errors)) {
$sql = "INSERT INTO `orders`(`order_dish1`, `order_name_worker`, `order_company`) VALUES (:order1, :order_name_worker, :worker_company)";
$params = [
"order1" => $item1,
"order_name_worker" => $worker_name,
"worker_company" => $worker_company
];
$dbh->prepare($sql)->execute($params);
}
$order_dishes1 = [];
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Document</title>
</head>
<body>
<select type="text" name="filter" id="filter">
<option value="*">All</option>
<?php
$sql = "SELECT * FROM `companies`";
$rows = $dbh->query($sql);
foreach ($rows as $row) {
?>
<option value="<?php echo $row['name'] ?>">
<?php echo $row['name'] ?>
</option>
<?php } ?>
</select>
// In this form it works
<form action="thispage.php" method="POST">
<select type="text" name="filter" id="filter">
<option value="*">All</option>
<?php
$sql = "SELECT * FROM `companies`";
$rows = $dbh->query($sql);
foreach ($rows as $row) {
?>
<option value="<?php echo $row['name'] ?>">
<?php echo $row['name'] ?>
</option>
<?php } ?>
</select>
<button type="submit">submit</button>
</form>
<div class="orders__wrapper" id="result">
<?php
$company = $_POST['filter'];
var_dump($_POST['filter']);
$sql = "SELECT * FROM `orders` WHERE `order_company` = '$company'";
$rows = $dbh->query($sql);
foreach ($rows as $row) {
?>
<div class="order-items">
<div class="order-items__header">
<div class="order-items__wrapper">
<div class="order-items__number">
Order №: <?php echo $row['order_id'] ?> </div>
</div>
<div class="order-items__wrapper">
<div class="order-items__name">
<?php echo $row['order_name_worker'] ?> </div>
<div class="order-items__company">
Company:
<span>
<?php echo $row['order_company'] ?>
</span>
</div>
</div>
</div>
<div class="order-items__orders">
<div class="orders-item orders-item-1">
Order №1:
<span class="order1">
<?php echo $row['order_dish1'] ?>
</span>
</div>
</div>
</div>
<?php
$order_dishes1[] = $row['order_dish1'];
}
$content = ob_get_contents();
ob_end_clean();
?>
<div class="result__all" id="result__all">
<div class="result__all-company">
<?php echo $row['order_company'] ?>
</div><br>
<div class="result__all__wrapper">
<div class="result__all-view">
<div class="result__all-title">
Soups:
</div>
<?php
$count_dishes1 = array_count_values($order_dishes1);
foreach ($count_dishes1 as $key => $val) echo '<div class="result__all-item">' . $key . ' - ' . $val . ' шт.,</div>';
?>
</div><br>
</div>
</div>
<?= $content ?>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</body>
</html>
What i want to achieved is when a user pick or choose a speaker name on a dropdown list only the speaker expertise will show up in the next topic dropdown list. Ex. When He choose Ms. Cimatu the topic dropdown list must only show the topics that Ms. Cimatu is familiar like Motivational, Entertainment, Healtcare. And When the user choose Mr. Santos the topic dropdown list must only show the topics that he know like Business, and Technology. Btw the speakers names and topics that is show on the dropdown list is from a database that i get using select query and mysqli_fetch_array. Please guys any suggestions and help is really appreciated.
I already try this solution but my problem in this code is when i add new speaker, when i select their name it will not show any topics.
<?php
$conn = new mysqli($servername, $username, $password, $dbname);
$selectspeakers = "SELECT * FROM speakers";
$sp_result = mysqli_query($conn, $selectspeakers);
$result = mysqli_query($conn, "SELECT speaker_fullname FROM speakers");
$storeArray = Array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$storeArray[] = $row['speaker_fullname'];
}
$msCimatuTopics = "SELECT speaker_specialization1, speaker_specialization2, speaker_specialization3, speaker_specialization4, speaker_specialization5 FROM speakers WHERE speaker_fullname = '$storeArray[0]' ";
$msCimatuTopics_result = mysqli_query($conn, $msCimatuTopics);
$mrSantosTopics = "SELECT speaker_specialization1, speaker_specialization2, speaker_specialization3, speaker_specialization4, speaker_specialization5 FROM speakers WHERE speaker_fullname ='$storeArray[1]' ";
$mrSantosTopics_result = mysqli_query($conn, $mrSantosTopics);
?>
<html>
<head>
</head>
<body>
<div class="form-group">
<label for="speaker">Preferred Speaker:</label>
<select name="speaker" class="form-control" id="speaker" style='text-transform:capitalize;'>
<?php while($array = mysqli_fetch_array($sp_result)):;?>
<option value = "<?php echo $array['speaker_fullname'];?>" <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_fullname'];?></option>
<?php endwhile;?>
</select>
</div>
<div class="form-group">
<label for="msCimatuTopics" id="topicTitle" class="hidden">Topic:</label>
<select name="topic" class="form-control hidden" id="msCimatuTopics" style='text-transform:capitalize;' autofocus required="required">
<?php $array = mysqli_fetch_array($msCimatuTopics_result);?>
<option value = "" <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> >Please Select...</option>
<option value = "<?php echo $array['speaker_specialization1'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization1']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization1'];?></option>
<option value = "<?php echo $array['speaker_specialization2'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization2']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization2'];?></option>
<option value = "<?php echo $array['speaker_specialization3'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization3']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization3'];?></option>
<option value = "<?php echo $array['speaker_specialization4'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization4']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization4'];?></option>
<option value = "<?php echo $array['speaker_specialization5'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization5']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization5'];?></option>
</select>
<select name="topic" class="form-control hidden" id="mrSantosTopics" style='text-transform:capitalize;' autofocus required="required">
<?php $array = mysqli_fetch_array($mrSantosTopics_result);?>
<option value = "" <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> >Please Select...</option>
<option value = "<?php echo $array['speaker_specialization1'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization1']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization1'];?></option>
<option value = "<?php echo $array['speaker_specialization2'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization2']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization2'];?></option>
<option value = "<?php echo $array['speaker_specialization3'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization3']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization3'];?></option>
<option value = "<?php echo $array['speaker_specialization4'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization4']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization4'];?></option>
<option value = "<?php echo $array['speaker_specialization5'];?>" <?php if ($_POST['topic'] == $array['speaker_specialization5']) echo 'selected="selected"';?> <?php if($_SESSION["selectedSpeaker"] == $array['speaker_fullname']) echo "selected";?> ><?php echo $array['speaker_specialization5'];?></option>
</select>
</div>
</body>
</html>
<script>
$('#speaker').change(function(){
var selected_item = $(this).val()
if(selected_item == "Ms. Cimatu")
{
$('#msCimatuTopics').val("").removeClass('hidden')
$('#topicTitle').val("").removeClass('hidden');
$('#mrSantosTopics').val(selected_item).addClass('hidden');
}
else if(selected_item == "Mr. Santos")
{
$('#mrSantosTopics').val("").removeClass('hidden')
$('#topicTitle').val("").removeClass('hidden');
$('#msCimatuTopics').val(selected_item).addClass('hidden');
}
else
{
$('#msCimatuTopics').val(selected_item).addClass('hidden');
$('#mrSantosTopics').val(selected_item).addClass('hidden');
$('#topicTitle').val(selected_item).addClass('hidden');
}
});
</script>
this is the image of dropdown list
This is the image of the database data
There are some basic things you can look to improve with your implementation. The biggest is you don't need to keep querying the same table for different pieces of data. If you are okay with running the SELECT * on the speakers table then you can skip the rest of your queries.
The next task is to try and make your code less dependent on singular values. If you notice you are writing the same code for value 1, value 2, etc then try to think about how to abstract your code so that it can work for an unlimited number of values.
This is a very rough implementation based on your sample code implementing the items I've mentioned. I have no way of testing it so there may be some small errors you need to debug before it works for your purpose:
<?php
// Based on your code and image these appear to be the fields in the speakers table:
// speaker_fullname
// speaker_image
// speaker_videolink
// speaker_specialization1
// speaker_specialization2
// speaker_specialization3
// speaker_specialization4
// speaker_specialization5
// Make your connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Get speakers and all their data (you only need one query!)
$result = mysqli_query($conn, "SELECT * FROM speakers");
// Store the speakers for later
// (You could maybe use this instead but depends on your PHP version:)
// -> http://php.net/manual/en/mysqli-result.fetch-array.php
$speaker_array = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$speaker_array[] = $row;
}
// Apparently you have session values? You don't start the session though?
// See: http://php.net/session_start
$session_speaker_fullname = ( ! empty($_SESSION["selectedSpeaker"])) ? $_SESSION["selectedSpeaker"] : '';
?>
<html>
<head>
</head>
<body>
<div class="form-group">
<label for="speaker">Preferred Speaker:</label>
<select name="speaker" class="form-control" id="speaker" style='text-transform:capitalize;'>
<option value=""></option>
<?php foreach($speaker_array as $row):;?>
<option value="<?php echo $row['speaker_fullname'];?>"
<?php if($session_speaker_fullname == $row['speaker_fullname']) echo "selected";?>
><?php echo $row['speaker_fullname'];?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label for="topic" id="topicTitle" class="hidden">Topic:</label>
<select name="topic" class="form-control" id="topic" style='text-transform:capitalize;' autofocus required="required">
<!-- this will get populated via JavaScript -->
</select>
</div>
<script type="text/javascript">
// Let your data be used by JavaScript
var speaker_array = <?php echo json_encode($speaker_array); ?>;
// A function to update the topic select
function update_topic_select_list() {
// Clear the current topic list
$('#topic').html('');
// Only re-build the topic list if a speaker is selected
if ($('#speaker option:selected').val() != '') {
var topic_array = Array();
// Find the correct speaker
for (var i = 0; i < speaker_array.length; i++) {
// The speaker name matches
if (speaker_array[i].speaker_name == $('#speaker option:selected').val())
// Add the values to the topic array
topic_array.push(speaker_array[i].speaker_specialization1);
topic_array.push(speaker_array[i].speaker_specialization2);
topic_array.push(speaker_array[i].speaker_specialization3);
topic_array.push(speaker_array[i].speaker_specialization4);
topic_array.push(speaker_array[i].speaker_specialization5);
// Stop the loop
break;
}
}
// Update the topic list
for (var i = 0; i < topic_array.length; i++) {
// Don't add empty values
if (topic_array[i] != '') {
$('#topic').append('<option value="' + topic_array[i] + '">' + topic_array[i] + '</option>');
}
}
}
}
// Watch for changes to the speaker selection
$('#speaker').change(function() {
// Do you need to do anything else?
// Call the update function
update_topic_select_list();
});
// Force a change trigger after page load - in case you need that session value set?
$('#speaker').trigger('change');
</script>
</body>
</html>
I would suggest to use AJAX. In this way, when the user selects a speaker, Javascript will request the server the list of specializations for the selected speaker. For example:
<!-- This is your <select> of speakers -->
<select id="select-speaker">
<?php echo($speaker_options); ?>
</select>
<!-- This is your <select> of specializations -->
<select id="select-specialization">
<option value=""></option>
</select>
<!-- This is your JS code -->
<script>
// When users select the speaker, #select-specialization gets updated
$("#select-speaker").change(function (){
var speaker = document.getElementById("select-speaker");
GetSpecializations(speaker.value).then(function (data){
document.getElementById("select-specialization").innerHTML = data;
});
});
async function GetSpecializations(speaker){
// Request the server via AJAX the list of specializations for that speaker
var options = await AjaxPOST("page.php", speaker);
// Returns something like "<option value='spec1'>Spec1</option>..."
return options;
}
</script>
This is just an idea. Here's a possible implementation of AjaxPOST():
function AjaxPOST(url, speaker){
return new Promise(resolve => {
var http = new XMLHttpRequest();
var params = {"sentFromAJAX" : "true", "speaker" : speaker};
http.onreadystatechange = function (){
if (this.readyState == 4 && this.status == 200){
resolve(this.responseText);
}
};
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/json; charset=utf-8");
http.send(JSON.stringify(params));
});
}
This is a basic AJAX tutorial from W3C and this is a useful article on async/await from MDN.
P.S.: I didn't test this code. But it should work.
P.P.S.: It's missing the PHP part of code. You have to handle AJAX requests sent from Javascript. Note that this code sends the params encoded in JSON, so in PHP you have to retrieve $_POST variable using something like: $_POST = json_decode(file_get_contents("php://input"), true) ?: [];.
I have created two select boxes each have different country names with flag images using select2 plugin and values are fetching from Database below is the code.
JS CODE
$(".currencyconverterselect").select2({
templateResult: addflag,
templateSelection: addflag
});
function addflag(opt) {
if (!opt.id) {
return opt.text;
}
var $opt = $(
'<span><img src="./img/flags/' + $(opt.element).attr('data-country-code') + '.png" class="userPic" /> ' + $(opt.element).text() + '</span>'
);
return $opt;
};
HTML CODE
<label style="color:white">Currency from</label>
<select name="fromcurrency_cc" id="fromcurrency_cc" class="form-control charts_currency" style="width:100%" required="required">
<?php
$sql = "SELECT fc.country_id,fc.code,fc.name,cc.country_code AS countrycode FROM fx_currency fc LEFT JOIN fx_country cc ON fc.country_id = cc.id ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ($row['code'] == 'AED')
{ ?>
<option data-country-code='<?php echo $row['countrycode']; ?>' value="<?php echo $row['code']; ?><?php echo $row['countrycode']; ?>" selected>
<?php echo $row['name']; ?>(
<?php echo $row['code']; ?> )</option>
<?php } else { ?>
<option data-country-code='<?php echo $row['countrycode']; ?>' value="<?php echo $row['code']; ?><?php echo $row['countrycode']; ?>">
<?php echo $row['name']; ?>(
<?php echo $row['code']; ?> )</option>
<?php }}
} else {
echo "0 results";
}
?>
</select>
I have also created a button below is the code
</i>
I want to swap the value of FROM currency to TO Currency and vice versa by clicking the button.
I have tried below code
$("#swapvalues_btn1").on('click', function() {
var pickup = $('#fromcurrency_cc').val();
$('#from').val($('#tocurrency').val());
$('#to').val(pickup);
});
Select2 will listen for the change event on the that it is attached to. If you make any external changes that need to be reflected in Select2 (such as changing the value).
Just use below code
$("#swapvalues_btn1").on('click', function() {
var fromcurrency = $('#fromcurrency').val();
var tocurrency = $('#tocurrency').val();
$('#fromcurrency').val(tocurrency).trigger('change');
$('#tocurrency').val(fromcurrency).trigger('change');
});
For More follow the link
https://select2.github.io/options.html#events
I have 4 pages: register.php, view.php , edit.php and display.php
On view.php i have a form that displays all data from database.
I have a search box, results of which are displayed in display.php(it displays just one row from database).
In display php i have a form with edit button for the entry. The edit button redirect me to edit.php where i can change my data. When i save, it redirect me on view.php but i want in display php with saved values of edited entry.
I tried in but it desnt work.
The second problem i have here is to keep in edit.php the dropdown option that i selected in in register.php
I;m new in programation and i hope someone will help me in this problem. THX for help.
My pages:
DISPLAY.PHP
<?php
include('connect-db.php');
$client = $_POST['client'];
$contract = $_POST['contract'];
if(
$contract = $_POST['contract'] )
{$query = "select * from users where contract = '$contract'"; }
else{
$query= "select * from users where client = '$client'";
}
$result = mysql_query($query);
echo "<table>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
// echo out the contents of each row into a table
echo '<label>Contract</label><input readonly="true" value=' . $row['contract'] . '>';
echo '<label>Client</label><input readonly="true" type="text" value="' . $row['client'] . '">';
echo '<label>Step</label><input type="text" readonly="true" value=' . $row['Step'] . '>';
echo '<br><input type="submit"value="Change">';
echo '<br>';
echo "</table>";
}
?>
EDIT.PHP
<?php
function renderForm($contract, $client, $step
{
?>
<!DOCTYPE html>
<body>
<form id="base" name="base" method="post" action="">
<input data-validate="number" value="<?php echo $contract; ?>" readonly="true" id="contract">
<input data-validate="text" value="<?php echo $client; ?>" id="client">
<select name="step">
<option value="option1">Option1</option>
<option value="option2">Option2</option>
</select>
<input type="submit" value="Change">
</form>
</body>
</html>
<?php
}
include('connect-db.php');
if (isset($_POST['submit']))
{
if (is_numeric($_POST['contract']))
{
$contract = mysql_real_escape_string(htmlspecialchars($_POST['contract']));
$client = mysql_real_escape_string(htmlspecialchars($_POST['client']));
$step = mysql_real_escape_string(htmlspecialchars($_POST['step']));
if ($contract == '' || $client == '' )
{
$error = 'ERROR: Please fill in all required fields!';
renderForm($contract, $client, $step, $error);
}
else
{
mysql_query("UPDATE users SET
contract='$contract', client='$client', step='$step', WHERE contract='$contract'")
or die(mysql_error());
header("Location: view.php");
}
}
else
{
echo 'Error!';
}
}
else
{
if (isset($_GET['contract']) && is_numeric($_GET['contract']) && $_GET['contract'] > 0)
{
$contract = $_GET['contract'];
$result = mysql_query("SELECT * FROM users WHERE contract=$contract")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
$contract = $row['contract'];
$client = $row['client'];
$step = $row['step'];
renderForm($contract, $client, $step, '');
}
else
{
echo "No results!";
}
}
else
{
echo 'Error!';
}
}
?>
VIEW.PHP
<!DOCTYPE html>
<html>
<?php
include('connect-db.php');
$sql="SELECT * FROM users";
$result =mysql_query($sql);
{
?>
<table>
<thead>
<tr>
<th span style="font-weight: normal;">Contrat</th>
<th span style="font-weight: normal;">Client</th>
<th span style="font-weight: normal;">Step</th>
</tr>
</thead>
<?php
}
while ($data=mysql_fetch_assoc($result)){
?>
<tbody>
<tr>
<td><?php echo $data['contract'] ?></td>
<td><?php echo $data['client'] ?></td>
<td><?php echo $data['step'] ?></td>
<td><input type="button" value="Change"></td>
</tr> <?php } ?>
</tbody>
</table>
</body>
</html>
REGISTER.PHP
<!DOCTYPE html>
<html>
<form id="base" method="post" action="insert.php">
<br>
<br>
<input data-validate="number" id="contract" name="contract">
<input data-validate="text" id="client" name="client">
<select name="step">
<option value="option1">OPTION1</option>
<option value="option2">OPTION2</option>
</select>
<button data-validate="submit">Register</button>
</form>
</body>
</html>
use this instead of your edit.php
<?php
function renderForm($contract, $client, $step
{
?>
<!DOCTYPE html>
<body>
<form id="base" name="base" method="post" action="">
<input data-validate="number" value="<?php echo $contract; ?>" readonly="true" id="contract">
<input data-validate="text" value="<?php echo $client; ?>" id="client">
<select name="step">
<option value="option1">Option1</option>
<option value="option2">Option2</option>
</select>
<input type="submit" value="Change">
</form>
</body>
</html>
<?php
}
include('connect-db.php');
if (isset($_POST['submit']))
{
if (is_numeric($_POST['contract']))
{
$contract = mysql_real_escape_string(htmlspecialchars($_POST['contract']));
$client = mysql_real_escape_string(htmlspecialchars($_POST['client']));
$step = mysql_real_escape_string(htmlspecialchars($_POST['step']));
if ($contract == '' || $client == '' )
{
$error = 'ERROR: Please fill in all required fields!';
renderForm($contract, $client, $step, $error);
}
else
{
mysql_query("UPDATE users SET
contract='$contract', client='$client', step='$step', WHERE contract='$contract'")
or die(mysql_error());
header("Location:display.php");
}
}
else
{
echo 'Error!';
}
}
else
{
if (isset($_GET['contract']) && is_numeric($_GET['contract']) && $_GET['contract'] > 0)
{
$contract = $_GET['contract'];
$result = mysql_query("SELECT * FROM users WHERE contract=$contract")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
$contract = $row['baza_contract'];
$client = $row['baza_client'];
$step = $row['step'];
renderForm($contract, $client, $step, '');
}
else
{
echo "No results!";
}
}
else
{
echo 'Error!';
}
}
?>
I know this is a stupid question but i am new with AJAX and
i tried many of the code i got from internet but still not able to do this simple thing
so at last i am posting my question here
something is wrong and when i select option in first drop down list
nothing happens
database table name is sub_menu and its fields are as follows
id,sub_item_name,item_name,price
this is my script i put on additem.php file
<script>
function showSubItem(sel) {
var item_name = sel.options[sel.selectedIndex].value;
$("#subItemTr").html( "" );
if (item_name.length > 0 ) {
$.ajax({
type: "POST",
url: "subitem.php",
data: "item_name="+item_name,
cache: false,
success: function(html) {
$("#subItemTr").html( html );
}
});
}
}
</script>
and he is my both drop down menu both are in a table form
My master menu is still working and displaying all option from database so i am not posting that
part here
<tr>
<td width="251">Select Master Menu Name</td>
<td width="47">:</td>
<td width="342"><select name="iname" id="iname" class="form-control" onChange="showSubItem(this);">
<option selected="selected">Select Main Menu</option>
<?php
$abc = "select * from main_menu";
$lkg = mysql_query($abc);
while($ukg = mysql_fetch_row($lkg))
{
?>
<option><?php echo $ukg[1]; ?></option>
<?php } ?>
</select> </td>
</tr>
<tr>
<td width="251">Sub Item Name</td>
<td width="47">:</td>
<td width="342" id="subItemTr" ><select name="subname" id="subname" class="form-control">
<option selected="selected">Select Sub Item</option>
</select></td>
</tr>
And here is my subitem.php file code as follows
<?php
include 'config.php';
$item_name = ($_POST["item_name"] <> "") ? trim( addslashes($_POST["item_name"])) : "";
if ($country_id <> "" ) {
$sql = "SELECT * FROM sub_menu WHERE item_name = ".$item_name ." ORDER BY sub_item_name";
$count = mysql_num_rows( mysql_query($sql) );
if ($count > 0 ) {
$query = mysql_query($sql);
?>
<select name="sub_item">
<option value="">Please Select</option>
<?php while ($rs = mysql_fetch_array($query)) { ?>
<option><?php echo $rs["item_name"]; ?></option>
<?php } ?>
</select>
<?php
}
}
?>
This should
<option><?php echo $rs["item_name"]; ?></option>
to
<option value="<?php echo $rs["item_id"]; ?>"><?php echo $rs["item_name"]; ?></option>
I given $rs["item_id"]; whatever field you want in value fix it.
And also,
change this line also
Your selectbox option should have value attributes. Until your condition if (item_name.length > 0 ) { should be fail.
<option><?php echo $ukg[1]; ?></option>
Should be
<option value="<?php echo YOUR_VALUE ?>"><?php echo $ukg[1]; ?></option>
<option><?php echo $rs["item_name"]; ?></option>
Should be
<option value="<?php echo YOUR_VALUE ?>"><?php echo $rs["item_name"]; ?></option>
Also currently you are sending the object instead on value.
<select name="iname" id="iname" class="form-control" onChange="showSubItem(this);">
Should be
<select name="iname" id="iname" class="form-control" onChange="showSubItem(this.value);">
So you can access the selected value directly from your variable sel
var item_name = sel;
You not defined the $country_id in subitem.php file, Thats why code fails to execute inside if statement. You define something for $country_id or remove the condition if not necessary. Then it will work
Example:
<?php
include 'config.php';
$country_id = 'something';
$item_name = ($_POST["item_name"] <> "") ? trim( addslashes($_POST["item_name"])) : "";
if ($country_id <> "" ) {
$sql = "SELECT * FROM sub_menu WHERE item_name = ".$item_name ." ORDER BY sub_item_name";
$count = mysql_num_rows( mysql_query($sql) );
if ($count > 0 ) {
$query = mysql_query($sql);
?>
<select name="sub_item">
<option value="">Please Select</option>
<?php while ($rs = mysql_fetch_array($query)) { ?>
<option><?php echo $rs["item_name"]; ?></option>
<?php } ?>
</select>
<?php
}
}
?>