I have a form that has two select fields, one representing the region and one the name of the city/village/etc. I have a database with all these entries in the following form:
id (int 11, ai)
region (varchar 50)
city(varchar 50)
I've found a script here on so that lets you select different options but it's made with JS and I have no idea how to adapt it to my needs. I need a database because I have 13.000+ entries and it's not really a good idea to enter them manually in the code. Here is the link to the topic that I've read, it's solution is in one of the comments as well.
how to change a selections options based on another select option selected?.
Please let me know if I need to edit my post before downrating. Thanks in advance!
Just use ajax for this, when one select change fetch data from the server to feed other select.
<select class="select_one">
<?php /* render first select ?>
</select>
<select class="select_two"></select>
<script>
$(function() {
$('.select_one').change(function() {
var select = $('.select_two').empty();
$.get('script.php', {region: $(this).val()}, function(result) {
$.each(result, function(i, item) {
$('<option value="' + item.value + '">' + item.name + '</option>').
appendTo(select);
});
});
});
});
</script>
and you script.php should return JSON from db:
if (isset($_GET['region'])) {
$sql = new mysqli('localhost','username','password','database');
$region = mysqli_real_escape_string($sql,$_GET['region']);
$query = "SELECT * FROM cities WHERE region = $region";
$ret = $sql->query($query);
$result = array();
while ($row = $ret->fetch_assoc()) {
$result[] = array(
'value' => $row['id'],
'name' => $row['city']
);
}
echo json_encode($result);
}
Related
I am running a POST + json code to collect data from database, all results come with only one value (this is correct), however there is only one column which should show more than one value but shows only the first one. What I need to change in my code to get this list instead of the first row result?
I've run one MYSQL query linking three databases those share the same id PCRNo, the first two databases tPCR and tcomplement should only have one result and the third one should receive more results due to we can have more lines with the same id.
This is my JavaScript
<script>
$(document).ready(function(){
$('#table').on('click', '.fetch_data', function(){
var pcr_number = $(this).attr('id');
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
$('#description').val(data.Name);
$('#Comments').val(data.Comments);
$('#originator').val(data.Creator);
$('#change_type').val(data.Category);
$('#product_type').val(data.Product);
$('#req_dept').val(data.Department);
$('#flow').val(data.Flow_Start_Date);
$('#own').val(data.Owning_Site);
$('#impacted').val(data.Impacted_Site);
$('#approval').val(data.Meeting_Status);
$('#review').val(data.Review_Date);
$('#cat').val(data.Cat);
$('#cost').val(data.Cost);
$('#labor').val(data.Labour);
$('#volume').val(data.Volume);
$('#request').val(data.Request);
$('#justification').val(data.Justification);
$('#PCNlist').val(data.PCNNo);
$('#monitor').val(data.Monitor);
$('#env').val(data.Environment);
$('#trial').val(data.Trial);
$('#resp').val(data.Responsible);
$('#deadline').val(data.Deadline);
$('#dataModal').modal('show');
}
});
});
$(document).on('click', '#update', function(){
var pcr_number = document.getElementById("PCR").value;
var Comments= document.getElementById("Comments").value;
var approval= document.getElementById("approval").value;
var review= document.getElementById("review").value;
var cat= document.getElementById("cat").value;
var monitor= document.getElementById("monitor").value;
var env= document.getElementById("env").value;
var trial= document.getElementById("trial").value;
var resp= document.getElementById("resp").value;
var deadline= document.getElementById("deadline").value;
var PCC = document.getElementById("PCC").value;
$.ajax({
url:"edit.php",
method:"POST",
data:{pcr_number:pcr_number, Comments:Comments, PCC:PCC, approval:approval, review:review, cat:cat, monitor:monitor, env:env, trial:trial, resp:resp, deadline:deadline},
dataType:"text",
success:function(data)
{
alert('PCR Information Updated');
}
});
});
});
</script>
this is my fetch.php
<?php
$SelectedPCRNo = $_POST['pcr_number'];
if(isset($_POST['pcr_number']))
{
$output = '';
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "change_management";
$dbConnected = #mysqli_connect($hostname, $username, $password);
$dbSelected = #mysqli_select_db($databaseName,$dbConnected);
$dbSuccess = true;
if ($dbConnected) {
if ($dbSelected) {
echo "DB connection FAILED<br /><br />";
$dbSuccess = false;
}
} else {
echo "MySQL connection FAILED<br /><br />";
$dbSuccess = false;
}
$sql = mysqli_query($dbConnected, "SELECT * FROM change_management.tPCR INNER JOIN change_management.tcomplement ON change_management.tPCR.PCRNo = change_management.tcomplement.PCRNo INNER JOIN change_management.tPCN ON change_management.tPCR.PCRNo = change_management.tPCN.PCRNo WHERE tPCR.PCRNo = '".$_POST['pcr_number']."'");
$row = mysqli_fetch_array($sql);
echo json_encode($row);
}
?>
I have no problems with the results and the table is filled OK, only the #PCNlist should be filled with the values of all rows it is related and now just is just coming one value, the first row only. Is there any way to bring the whole PCNlist only changing some code at the fetch.php?
If I understood you correctly, the table tPCN can contain multiple rows associated with each PCR number. And you want to fetch all these rows and return them in your JSON.
If you want to achieve that, but also make sure the other two tables only return one row, then I think simply you should remove the JOIN to tPCN in your first query, and then create a second query to fetch the tPCN rows specifically.
$output = [];
$stmt = $dbConnected->prepare("SELECT * FROM change_management.tPCR INNER JOIN change_management.tcomplement ON change_management.tPCR.PCRNo = change_management.tcomplement.PCRNo WHERE tPCR.PCRNo = ?");
$stmt->bind_param('s', $_POST['pcr_number']);
$stmt->execute();
$result = $stmt->get_result();
//select a single row from the result and assign it as the output variable
if ($row = $result->fetch_assoc()) {
$output = $row;
}
$stmt2 = $dbConnected->prepare("SELECT * FROM change_management.tPCN WHERE PCRNo = ?");
$stmt2->bind_param('s', $_POST['pcr_number']);
$stmt2->execute();
$result2 = $stmt2->get_result();
$output["tPCN"] = array(); //create a new property to put the tPCN rows in
//loop through all the tPCN rows and append them to the output
while ($row2 = $result2->fetch_assoc()) {
$output["tPCN"][] = $row2;
}
echo json_encode($output);
This will produce some JSON with this kind of structure:
{
"PCRNo": "ABC",
"CreationDate": "2019-08-07",
"Name": "A N Other",
//...and all your other properties, until the new one:
"tPCN": [
{
"SomeProperty": "SomeValue",
"SomeOtherProperty": "SomeOtherValue",
},
{
"SomeProperty": "SomeSecondValue",
"SomeOtherProperty": "SomeOtherSecondValue",
}
]
}
You will then need to amend your JavaScript code to be able to deal with the new structure. Since I don't know exactly which fields come from the tPCN table, I can't give you an example for that, but hopefully it's clear that you will need to loop through the array and output the same HTML for each entry you find.
N.B. As you can see I re-wrote the query code to use prepared statements and parameterised queries, so you can see how to write your code in a secure way in future.
P.S. You have a lot of code there in the "success" function just to set the values of individual fields. You might want to consider using a simple JS templating engine to make this less verbose and cumbersome, and generate the HTML you need with the values automatically added into it in the right place. But that's a separate issue, just for the maintainability of your code
I've added this code into my ajax function to bring only what I needed and it works + what #ADyson has posted.
var PCN = data.tPCN;
var i;
var PCNList = '';
for (i = 0; i < PCN.length; i++){
var PCNList = PCNList + PCN[i]['PCNNo'] + ' - ' + PCN[i]['Stage'];
}
$('#PCNlist').val(PCNList);
I am trying to .append() a selected data from a radio button but it display all the previous respond result.
My HTML :
$sql = "SELECT DISTINCT(name) FROM table1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$i = 1;
while($row = $result->fetch_assoc()) {
echo '<label>'.$row['name'].'</label>';
$sql2 = "SELECT * FROM table1 WHERE list = '".$row['list']."'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
echo '<input name="group['.$i.']" class="id" type="radio" data-id="'.$row2['id'].'" />'.$row2['list'];
}
}
$sql2 = NULL;
$i++;
}
}
$sql = NULL;
My ajax to get data and append :
$('.id').on('click', function(){
var id = $(this).data('id');
$.ajax ({
type: 'POST',
url: 'url-here',
data: { id : id },
success : function(data) {
$('#list').append(data);
}
});
});
For PHP side if there is $_POST['id'] then do mysql query to filter from table and return result.
if(isset($_POST['id'])){
$sql = "SELECT * FROM table1 WHERE id = '".$_POST['id']."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<label>'.$row['name'].'</label>';
}
}
}
So what happened in my ajax result box, it keep appending the previous data that been processed by ajax together with the new data.
EDIT : Example append result :
First result of selected radio button : string 1
Second result of selected radio button : string 2
So result should be :
string 1
string 2
Sorry there was a mistake with my explanation. My ajax box result is resulting something like this :
string 1
string 2 (new data from another selected radio)
string 2 (new data is duplicating)
If adding select another radio it will become like this :
string 1
string 2
string 2
string 3 (new data)
string 3 (new data duplicating)
string 3 (new data duplicating)
string 3 (new data duplicating)
My ajax box result :
<div id="list"></div>
Add any class in label and input
echo '<label class="ajax">'....
....
echo '<input class="ajax" ...
....
And Remove in each selection or change in ajax
$('.ajax').remove();
$('#list').append(data);
Or better
$('#list .ajax').remove();
$('#list').append(data);
Update
Or simple add div to your ajax response
$('#list').append("<div class='ajax'>"+data+"</div>");
and then use this code
$('#list .ajax').remove();
$('#list').append(data);
I think you jQuery looks ok. It would be possible for your SQL query to have multiple rows as a result. This could mean that your id value is actually returning two rows. They include the first row and the second row.
You should remove a previously-attached event handler from the elements to avoid multiple click.
$('.id').on('click', function(){
var id = $(this).data('id');
$.ajax ({
type: 'POST',
url: 'url-here',
data: { id : id },
success : function(data) {
$('#list').append(data);
$('.id').off('click'); // remove a previously-attached event handler from the element.
}
});
});
I am trying to pull the latest entry of a mysql table through ajax and display it as html content inside a div. I have ajax and php functioning correctly, the only problem I have is that I want to query for new entries and stack the results at a time interval within a loop and I've run into two problems: getting the data to behave like a normal javascript string, and getting the loop to only return unique entries.
update.php file
$con=mysqli_connect("mydbhost.com","username","password","database_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM conversations");
$j = 0;
while($row = mysqli_fetch_array($result))
{
$carray[j] = $row['comment'];
$j++;
}
$comment = (array_pop($carray));
echo $comment;
echo "<br>";
mysqli_close($con);
JQuery Ajax request loop:
$(document).ready(function(e){
var comment;
function commentLoop() {
comment = $('#testdiv').load('update.php');
$('#testdiv').append(comment);
setTimeout(commentLoop, 6000);
}
commentLoop();
$(document).focus();
});
The problem is by doing SELECT * FROM conversations you keep requesting whole table -- although you only take the last one.
Your code need to remember which comment has been loaded, and only get any comment newer than that.
For example, assuming your primary key is incremental, do SELECT * FROM conversations WHERE convid > ?. Replace ? with latest comment that has been loaded. If you're loading for the first time, just do SELECT * FROM conversations
You could pass the last comment id displayed using request parameter into update.php. Also I recomment returning the data in JSON format so you can return a collection of comment and id and parse it easily
This will count the comments in the table and select the last entered comment then pass them to ajax as json data only if the received count is lower than the count of the comments in the table:
PHP:
if(isset($_GET['data']))
{
$con = new mysqli('host', 'user', 'password', 'database');
$init_count = $_GET['data'];
$stmt1 = "SELECT COUNT(*) AS count FROM conversations";
$stmt2 = "SELECT comment FROM conversations ORDER BY date_column DESC LIMIT 1";
$total = $con->prepare($stmt1);
$total->execute();
$total->bind_result($count);
$total->fetch();
$total->close();
if( ($init_count != '') && ($init_count < $count) )
{
$lastComment = $con->prepare($stmt2);
$lastComment->execute();
$result = $lastComment->get_result();
$row = $result->fetch_assoc();
$lastComment->close();
$data = array(
'comment' => $row['comment'],
'count' => $count
);
}
elseif($init_count == '')
{
$data = array(
'comment' => '',
'count' => $count
);
}
$pdo->close();
echo json_encode($data);
}
HTML:
<input type="hidden" id="count" value="" />
JQUERY:
$(document).ready(function(e){
function getComment(){
var count = $('#test').val();
$.ajax({
type: 'get',
url: 'update.php?data=' + count,
dataType: 'json',
success: function(data)
{
$('#count').val(data.count);
if(data.comment) != $('#testdiv').html(data.comment);
}
});
}
getComment();
setInterval(getComment, 6000);
});
SELECT * FROM conversations order by insert_date desc limit 10
insert_date the date time comment is inserted, i hope you will have a field for storing that if not add it now
I have two autocomplete fields in my form. I populate the first field's list by using the following code...
$result = mysql_query("SELECT * FROM exercise_strength");
$arr_autoCompleteExerciseStr=array();
$s=0;
while($row = mysql_fetch_array($result)){
$autoCompleteExerciseStr = "\"".ucfirst($row['exercise'])."\", ";
$arr_autoCompleteExerciseStr[$s] = $autoCompleteExerciseStr;
$s++;
}
and...
$(function() {
var availableTags = [
<?php for($k=0; $k<sizeof($arr_autoCompleteExerciseStr); $k++) {echo $arr_autoCompleteExerciseStr[$k]; } ?>
];
$( "#inputExercise" ).autocomplete({
source: availableTags,
minLength: 0
});
$( "#inputExercise" ).focus(function(){
$(this).autocomplete("search");
});
});
The same code with a different mysql_query is used for the other field. What I want to do is change the list of the second field based on what's typed in the first. For instance, if the user types Chest in the first field, a list of relevant Exercises is shown in the second field, selected from my sql database.
What is the best way to do this?
I would prefer if I wouldn't have to leave the page, cause then the user have to refill the rest of the form..
Please help! :)
-- UPDATE --
Based on your advice about JSON my code now looks like this.
Script:
$(document).ready(function(){
$.post('json_exercise.php', { /**/ }, showExercise, "text");
});
function showExercise(res){
var list = JSON.parse(res);
$("#inputExercise").autocomplete({
source: list,
minLength: 0
});
$( "#inputExercise" ).focus(function(){
$(this).autocomplete("search");
});
}
PHP file:
$con = mysql_connect(***);
if (!$con) {die('Could not connect: ' . mysql_error());}
mysql_select_db("test", $con);
$result = mysql_query("SELECT * FROM exercise_strength");
$i = 0;
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
//add the row to the $chat array at specific index of $i
$exercise[$i] = $row['exercise'];
$i += 1;
}
echo json_encode($exercise);
Now I just need to change the php filed based on whats selected in the first autocomplete field.
If you want to autocomplete based on results from a SQL query without having to leave the page, you might want to look into AJAX and JSON.
Also, please use PDO instead of the mysql_* functions for interfacing with DBMS's with PHP.
I currently have code which will pull the first element from a database record and print it in an output box.
What is the easiest way to print the rest of the elements of that record to the other relevant output boxes?
My PHP file takes an 'id' specified by the user.
$id = $_POST['id'];
$query = "SELECT * FROM Customers WHERE ID = $id";
$result= mysql_query($query);
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)) {
echo $row[1];
}
}
And this is the code in the HTML file
jQuery(document).ready(function(){
jQuery("input.myid").keyup(function(e){
e.preventDefault();
ajax_search();
});
});
function ajax_search(){
var search_val=jQuery("input.myid").val();
jQuery.post("find.php", {id : search_val}, function(data){
if (data.length>0){
jQuery("input.fname").val(data);
}
});
}
The code takes the id ('myid') and prints to a text box named 'fname'.
I find it easier to json_encode the whole thing (record I mean) and use something like jquery.populate which basically takes an object and fills a form with it (all fields it can find which names' match properties from the object).
I hope this makes sense.