Cannot populate database column in dropdown - php

This issue is reminiscent of a question I asked a few years ago:
jQuery dropdown option:first selected
Here is the jQuery function that successfully populates the dropdown id #namelist:
$('#edituserModal').on('show.bs.modal', function (e) {
initializeSelect($('#namelist'), 'assets/process/getNames.php', function (item) {
return {
value: item.name,
text: item.name
}
});
});
The code directly above successfully populates the HTML dropdown select here:
<select id="namelist">
</select>
Here is the code that creates the datatable:
$('#datatable').DataTable({
"searching": true,
"paging": true,
"serverSide": false,
"type": "POST",
"ajax": {
"url": "assets/process/getusers.php",
"dataSrc": ""
},
"columns":
[
{ "data": "null",
"render": function ( data, type, row, meta )
{
return "<i class='far fa-edit editUser'
title='Edit User' data-editdeptrepname='"+row.name+"'></i>";
}
},
{"data": "username"},
// few more columns
]
});
The user clicks on the icon with the class .editUser. That onClick event is here:
$('#datatable').on('click', 'tr > td > .editUser', function(e){
e.preventDefault();
var $dataTable = $('#datatable').DataTable();
var tr = $(this).closest('tr');
var rowData = $dataTable.row(tr).data();
var name = $(this).attr('data-name');
$('#namelist').val(name);
// $('#namelist').val(rowData.name); // <-- I tried this
// $('#namelist').val(rowData.name).text(rowData.name); // <-- also tried this
// $('#namelist option:first').val(rowData.name).text(rowData.name); // <-- this too
// $('#namelist option:first').val(name); // <-- this as well
$('#edituserModal').modal('show');
});
As stated above, the dropdown list is populated with a list of names. When a user opens the modal, the first name that should appear in the dropdown should be whatever the name is saved in the db.
Problem is, in the modal, the dropdown list doesn't initially display the name saved in the database. The dropdown does still display all of the selectable name options, but it's the name saved in the database that should initially be displayed.
As you will see in the last piece of code, I've tried several methods to make it work, all to no avail.
Here is a pic of the dropdown after the modal opens. It should initially read the name currently saved in the database. I can click on the dropdown and it shows a whole list of names. But I need it to initially display the saved name:
What on Earth am I missing? I've done this a hundred times, and it has never failed me until now.

Here it is:
$('#datatable').on('click', 'tr > td > .editUser', function(e){
e.preventDefault();
// Here is where sould go your initializeSelect call
initializeSelect($('#namelist'), 'assets/process/getNames.php', function (item) {
return {
value: item.name,
text: item.name
}
});
var row = $(this).parent().parent();
name = row[0].cells[0].innerText;
$('#namelist option:first').val(name).text(name);
$('#edituserModal').modal('show');
});
By doing this, you dont need your modal show event listener anymore.
Hope this helped.

Related

How to update Multiple radio button value into database using id

I have listed my table(leaveform) records(50) using datatable API. In my table I have a column to approve leave. This column consist of two radio buttons(Approve and Reject). Each record have its own unique id. Now I want to update the values into database using those unique id.
This is my Table
You can create one function and that function is called by clicking on 'Approve' or 'Reject'. Let me give you example.
For e.g. : you have two radio button as below.
Approve and Reject
Now, You have to create one function that will be called by clicking on radio button. as explained below.
<input type="radio" name="rndLeave" value="approve" onclick="changeLeaveStatus(leaveid, 'approve')" /> Approve
<input type="radio" name="rndLeave" value="reject" onclick="changeLeaveStatus(leaveid, 'reject')" /> Reject
// first argument is leave id
// second argument is leave status.
function changeLeaveStatus(leaveid, leaveStatus)
{
$.ajax({
url: 'leave_status.php',
data: 'id='+leaveid+'&status='+leaveStatus,
type: 'POST',
success: function() {
},
error: function(){
}
});
}
This way you can update leave status from jquery datatable.
I see your tag has jquery so I guess you may want jquery code for solve this problem. here it is.
$( "#button_update" ).click( function() { //on click button update
var approve = new Array();
for (i=1;i<=count;i++) {
if ($('#id' + i).attr('checked') == 'checked'){
approve[i-1] = $('#id' + i).attr('id');
}
}
$.post(url,
{ approve: approve },
function(data) {
});
});
you should use jquery onclick on table with handler "tr" -> send ajax data to update.
$( "#dataTable tbody" ).on( "change", "input[type=radio]", function() {
console.log( $( this ).text() );
$.get( "path_to_php_page/update.php?id="+$( this ).attr("id")+"&state="+$(this).children("input[type=radio]:checked").val(), function( data ) {
console.log( data );
});
});
in update.php
you should get the id of the row with $_GET['id'] and the state with $_GET['state']

What I see is NOT what I get

(simplified) Scenario: a remote MySql DB and an HTML page with 2 buttons: SHOW and SELECT. The SHOW loads a single record and displays the fields in a form.
Everything is ok on this side.
The SELECT was made with a new approach for me:
I pass a parameter to a PHP function to query the DB and create an html file with the resuls.
This file is a series of <UL><LI><a id="1"...data..</LI></UL> to be inserted within a DIV.
One of the <LI> contains a link that, when clicked, calls the SHOW function. The record identification is made by mean of the ID associated to the anchor.
This procedure works fine; I get the new HTML segment (that I can check on the remote web server).
It is inserted (???) inside my DIV and the content is correctly displayed on screen, but... it does not exist.
Clicking on the links does not activate the SHOW procedure (actually, an Alert with the calling ID is never shown).
Looking to the html page source from Mozilla it still shows the previous content, without the new added (or replaced) code.
This is the reason for this post's title: I see something that really is not there.
Possibly, I should have AJAX to 'refresh' its visibility of the DOM, but and do not understand how.
This is the piece of JQuery script that I use to get the new content:
$("#select").click(function() {
$.ajax({
url: "new_record_list.php",
cache: false,
success:
function(recNumber)
{
$("#selected").val(recNumber); //ok
$("#recordList").load("list.txt"); //'list.txt is created by new_record_list.php
alert($("#recordList").html()); //this is OK
}
});
});
Everything is ok, but where is the meat?
Most likely the listener you created did not attach to the new dom nodes.
You can fix this by attaching a listener to a parent element that exists at page creation or even the document like so:
$(document).on('click', '.show', function() {
//click event
});
Replace ".show" with the jquery selector for the links
Since I'm unable to comment on your new post due to rep:
Remove the click event handler inside the loadRecord function.
The click event was already bound at the top of your script. What happens is that you click, activate the load record function which binds a new click handler, triggering the action on all the clicks following it.
The load record should look like this instead:
function loadRecord(){
ind = $(this).attr("id");
$("#thisRecord").val(ind); //shows the clicked record
$.get("show_record.php",{id:ind}, function(gotString)
{
ptr=0; //used to fetch fields
pos=0;
lun = gotString.length;
if (lun==0) {
alert ("Empty string!");
return false;
};
// fetch received keys and values then fills the fields
while (ptr < lun) {
..... //not interesting here
}; //while
});
return false; //required!
};
Also, you should replace
$(document).on('click', '.compLink', function() {
loadRecord();
});
with
$(document).on('click', '.compLink', loadRecord);
And loadRecord will be passed the mouse event as an argument. $(this) will also refer to the link you clicked inside the loadrecord function.
Otherwise you need to pass the element clicked into that function.
One issue I can see straight away is the AJAX call, it should be along the lines of:
$( "#select" ).on( "click", function ()
{
$.ajax( {
url: "new_record_list.php?record=MY_RECORD_VALUE",
type: "GET",
success: function ( response )
{
$( "#selected" ).val( response );
$( "#recordList" ).html( function ()
{
$.ajax( {
url: "list.txt",
typ: "GET",
success: function ( response2 )
{
$( "#recordList" ).html( response2 );
}
} );
} );
alert( $( "#recordList" ).val() );
},
beforeSend: function()
{
$( "#recordlist" ).html( "Loading..." );
$( "#selected" ).val( "Loading..." );
}
} );
} );
This will give a better result from the $.ajax call that you have made.
The .load() method can be quite unreliable at times, hence why it is (IMO) better to make an ajax within an ajax, because that's what your doing with less control effectively.
Where you have done the function(recNumber) is kinda wrong I'm afraid, whats brought back from the AJAX call is the response, everything that would be shown should you be using it as an actual page, e.g. if you had:
<table>
<tr>
<td>Row 1</td>
</tr>
<tr>
<td>Row 2</td>
</tr>
</table>
<input id="id_valued" value="2" />
Then this whole thing would be returned, not just the id_valued input field.
I followed the hints from Erin plus some other suggestion found on this forum and now the program ALMOST works.
Actually it does, but when a new set of records is loaded, to update the display (that is to call the loadRecord function) it is necessary to click twice on a link, the very first time only. All next clicks reacts immediately.
I try to post the entire script, for you experts to see what I hardly did:
<script type="text/javascript">
$(document).ready(function()
{
$(document).foundation();
var $scrollbar = $("#scrollbar1"); //other stuff
$scrollbar.tinyscrollbar();
//Erin suggestion + my understanding
$(document).on('click', '.compLink', function() {
loadRecord();
});
/* =========== ADD Rows ============================== */
/* action called by hitting the "selectRow" button.
/* query the DB and get a list of rows (5 fields each)
/* that are then inserted into the '#recordList' DIV.
/* Each rows has format:
/* <UL><LI><A id="xxx" class="compLink" ...>item xxx</A></LI><LI>....</LI></UL>
*/
$("#selectRow").on( "click",function()
{
$.ajax(
{
url: "new_record_list.php",
type: "GET",
success: function(recNumber) //if ok, we get the number of records
{
$("#selectedRecords").val(recNumber); //show how many records we got
$("#recordList").load("newRecords.txt"); //loads the remote text file into the DIV
}
});
});
/* ====================================================== */
/* =========== LOAD Record ============================== */
/* loads and displays an entire record from DB,
/* based on the ID of clicked link with class="compLink"
/* in '#recordList' DIV.
/* Example: <a id="1" class="compLink" ...>
*/
function loadRecord(){
$(".compLink").click(function(event)
{
ind = $(this).attr("id");
$("#thisRecord").val(ind); //shows the clicked record
$.get("show_record.php",{id:ind}, function(gotString)
{
ptr=0; //used to fetch fields
pos=0;
lun = gotString.length;
if (lun==0) {
alert ("Empty string!");
return false;
};
// fetch received keys and values then fills the fields
while (ptr < lun) {
..... //not interesting here
}; //while
});
return false; //required!
});
};
/* ====================================================== */
return false;
});
</script>
I hope this is clear enough. Thanks

How to set Jquery Autocomplete to a specific value and display It's Label using a datasource of JSON objects

Background
So I have a table that is populated by a form. Each row can be edited by hitting a edit button. The Edit button opens the form that is populated. I need to auto fill the autocomplete so that the user can see one of His selected course.
How I Cheated
I'm using PHP and Codeigniter server side and am dynamically creating my form based on database. The labels and values are all produced from the Database and populate my JQuery Auto complete (a.k.a datasource variable below). From my controller I'm passing my value to the model and getting the Label from the DB. From there I'm passing it to my view and to my AutoComplete and setting the input value equal to the found label.
I feel dirty having done it this way. The inefficiency of this burns my eyes.
My Goal
I want to use the value that I've gotten and have the autocomplete select it and display it's label client side.
OR
I need to just display the label in the box so the user knows it's not a blank field.
Both options need to allow the user to modify the autocomplete box.
Existing Code
My code for the input looks like this:
<div class="row-start span-2">
<label for="course_code">Course Code </label>
</div>
<div class="row-end span-2">
<input id="course_code">
</div>
My script for the autocomplete looks like this:
<script>
function search_course_code(){
var datasource = [{"value":"1","label":"AAF100 - DL"},{"value":"2","label":"AAF101 - DL+web"},.....];
var searchboxid = "#course_code";
var searchresultid = "#CRSEINVID";
$(searchboxid).autocomplete({
source:datasource,
focus: function( event, ui ) {
$( searchboxid ).val( ui.item.label );
return false;
},
select: function(event,ui){
var UIvalue = ui.item.value;
var UIlabel = ui.item.label;
console.log(UIvalue);
console.log(UIlabel);
$( searchboxid ).val( ui.item.label );
use_search("#search1","#CRSEINVID",UIvalue,UIlabel ); return false;
}
});
};
function use_search(show_select,result_id,uivalue,uilabel){
//loads value to field that takes it's value
$(result_id).val(uivalue);
//Display course below search box
course = "<span>"+uilabel+"</span>";
$(show_select).html(course );
//stops the value from being shown in the search box
return false;
};
$( document ).ready(function() {
search_course_code();
});
</script>
I draw the value from a hidden input with a unique ID simply using JQUERY val() function.
What I've tried
Try 1
Setting value using:
$(searchboxid).val(hiddenInputValue);
Result: Value displayed not the label
Try 2
Using the autocomplete on create method I tried to overwrite the UI object and send it to the select.
ui.item={"value":"","label":""};
ui.item.value=$(hiddenInputValue).val;
this.select(ui);
Result: No observable change, no errors.
Try 3
$(searchboxid).autocomplete("select", hiddenInputValue);
Result:
Uncaught Error: cannot call methods on autocomplete prior to
initialization; attempted to call method 'select'
Try 4
Tried changing value using
$(searchboxid).val(hiddenInputValue);
and having change function detect it and set label with
$( searchboxid ).val( ui.item.label );
Result: Value loaded into input not label
Try 5
Tried Triggering the change function with this:
$("#<?php echo $id;?>").autocomplete("option","change").call(searchBox);
and then setting label. Based on the answer to:
jQuery AutoComplete Trigger Change Event
Result: empty UI object for change function,
Try 6
Tried Triggering the select function with this:
$("#<?php echo $id;?>").autocomplete("option","select",{value:hiddenInputValue}).call(searchBox);
and then using my current select function.
Result: Uncaught Error: undefined is not a function,
Ideas
Ideas 1:
I thought of using the value then searching through the datasource object to find associating label and then using:
$(searchboxid).val(label);
would this work? How would I do it?
Idea 2:
If the value of the input field is set to a value using:
$(searchboxid).val(label);
Would the change function detect it? Not detected used console.log function in change function to give feedback,
So after much research and trying to get this to work I discovered two problems:
that I was using Select2 version 3.5.3 and needed to use text instead of label and :
$myselect.select2("val","somevalue");
The MAJOR source of my problem though was because I was using Web Experience Toolkit tabs and I needed to load the Select 2 after tabs where initialized.
assign the value to the auto complete input element by using
$('#YourAutoCompletBox').val(yourValuefromHiddenControl);
html:
Topic: <input type="text" id="topics" /><input type="hidden" id="topicID" />
<br/><br/><br/><br/>
<p>You selected <span id="results"></span></p>
jQuery:
var topics= [
{
value: "cooking",
label: "Cooking",
id: "1"
},
{
value: "C++",
label: "C++",
id: "2"
},
{
value: "craftsmanship",
label: "Software Craftsmanship",
id: "3"
}
];
$(document).ready(function() {
$( "#topics" ).autocomplete({
minLength: 0,
source: topics,
focus: function( event, ui ) {
$( "#topics" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#topics" ).val( ui.item.label );
$("#topicID").val(ui.item.id);
$( "#results").text($("#topicID").val());
return false;
}
})
});
Playground : jsfiddle

Why do both ajax calls run when I submit a single input?

I am dynamically generating two paragraphs and two input fields inside a div. There may be numerous divs generated, depending upon the number of records pulled from the database. Each para and input field is assigned a unique id.
When the user clicks on a field, say firstText_id, jQuery hides the field and shows an input field firstText_input_id in its place. The user updates the input field, and on clicking away, an ajax script is called to update the database and return a success message.
My problem is that, when the user clicks on one field in any record, and updates it, then clicks away, the ajax calls for both fields are made.
PHP
echo "<div class=\"single seven columns boxTable2 \" id=\"{$vid}\">
<div class=\"seven columns alpha omega\" >
<div class=\"four columns alpha omega\" >
<p class=\"single two columns alpha omega firstHead\">First name: </p>
<p class=\"firstText single two columns alpha omega\" id=\"firstText_{$vid}\"
data-vid=\"{$vid}\">{$first}</p>
<input type=\"text\" id=\"firstText_input_{$vid}\"
class=\"firstText_input single two columns\"
data-vid=\"{$vid}\" value=\"{$first}\"/>
</div>
<div class=\"four columns alpha omega\" >
<p class=\"single two columns alpha omega lastHead\" >Last name: </p>
<p class=\"lastText single two columns alpha omega\" id=\"lastText_{$vid}\"
data-vid=\"{$vid}\">{$last}</p>
<input type=\"text\" id=\"lastText_input_{$vid}\"
class=\"lastText_input single two columns\"
data-vid=\"{$vid}\" value=\"{$last}\"/>
</div>
</div>
</div>
jquery
jQuery.noConflict();
jQuery(document).ready(function($){
var vidID = '';
$(document).on('click', '.firstText', function ()
{
vidID=$(this).data('vid');
$('#firstText_'+vidID).hide();
$('#firstText_input_'+vidID).show();
}).change(function()
{
var newFirstText=$('#firstText_input_'+vidID).val();
var firstTextDataString = 'vid='+ vidID +'&first='+newFirstText;
if(newFirstText.length>0)
{
$.ajax({
type: "POST",
url: "/go/to/php.php",
data: firstTextDataString,
cache: false,
success: function(html)
{
$('#firstText_'+vidID).html(newFirstText);
}
});
} else
{
alert('Enter something.');
}
});
// Edit input box click action
$('.firstText_input').mouseup(function(e)
{
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
// return false; //(does the same as the above 3 functions)
});
// Click away action
$(document).mouseup(function()
{
$('.firstText_input').hide();
$('.firstText').show();
});
$(document).on('click', '.lastText', function ()
{
vidID=$(this).data('vid');
$('#lastText_'+vidID).hide();
$('#lastText_input_'+vidID).show();
}).change(function()
{
var newLastText=$('#lastText_input_'+vidID).val();
var lastTextDataString = 'vid='+ vidID +'&last='+newLastText;
if(newLastText.length>0)
{
$.ajax({
type: "POST",
url: "/go/to/php.php",
data: lastTextDataString,
cache: false,
success: function(html)
{
$('#lastText_'+vidID).html(newLastText);
}
});
} else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".lastText_input").mouseup(function()
{
return false;
});
// Click away action
$(document).mouseup(function()
{
$(".lastText_input").hide();
$(".lastText").show();
});
});
As the unique IDs are generated dynamically from the database records, I can’t find a way of associating the user’s click to the field being updated without the other field in the record being updated. I’m a relative beginner with jQuery/javascript. How can I isolate the user’s action to the field being clicked? I have tried click selectors like ‘[id^=”firstText_input_”]’. Probably a simple error, but I have been round it too many times to see the error.
The event that causes the ajax to happen is actually bound to the document, therefore, anytime ANY input changes, the document receives the event and performs the ajax request.
See below:
$(document).on('click', '.someclass', function () {...}).change(function () {...});
.change is targeting $(document), not $('.someclass'), you'll have to use the same delegation syntax as before to instead delegate it to the target element.
$(document).on('click', '.someclass', function () {...}).on('change', '.someclass', function () {...});
both firstText and lastText are affected by this issue, which is why both trigger any time you change either input.
Additionally... your event binding is very inconsistent. In some cases you're using delegation, and in others you are not. Since you're replacing the entire content of the div, you should be using event delegation for all of the events within that div.

Sending Retrieved Value into a specific page

I have this jQuery code to show retrieved value into the "result" div. My question is, how to target the result into specified page ?
my code is
$(function(){
// SHOW RECORD
$('#headmark').change(function(){
$.post('update_fabrication_data.php',
{
action: "show",
hm:$('#headmark').val()
},
function(res){
$('#result').html(res);
});
});
});
so, my target is to send the result into inside the updateFabrication.php

Categories