I am trying to create a chain of drop downs in a form. The first select is populating the second form, but I can't call a third from the results. I have figured out (I think) that it is a binding issue, but how would I go about correcting this.
The JavaScript on the page:
<script>
var selected_form_div = null;
var frm_submit_event = function(e){
var $this = $(this); // the button
//var frm = $this.closest(form);
var frm = $('#'+selected_form_div + " form");
console.log(frm);
console.log(frm.serialize());
e.preventDefault();
$.ajax({
type: "POST",
url: "classes/forms/ajaxPost.php",
data: frm.serialize(),
dataType: "text",
success: function($result) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
$('#'+selected_form_div).html($result);
},
error: function() {
alert('error handing here');
}
});
}
function loadSubSelects(value,form,select)
{
$.post("classes/forms/update_form.php",{catid : value,form : form,select : select},function(data)
{
jQuery('#sub_categories').html(data);
});
}
$(document).ready(function(){
$('._form_selector').click(function(e){
e.preventDefault();
var $this = $(this);
$.get('classes/forms/forms.php', {
form: $(this).attr('form_data')
},
function($result){
$('#'+$this.attr('form_div')).html($result);
//selected_form_div = $this.closest("form");
selected_form_div = $this.attr('form_div');
//console.log($result);
});
console.log($(this).attr('form_data'));
});
$(document).on("click", '.frm_submit_btn', frm_submit_event);
$('._pay').click(function(){
var $this = $(this);
console.log($this.attr('form_id'));
$('._form_pay').css('display', 'none');
$('#form_'+$this.attr('form_id')+'_pay').css('display','block');
});
});
function showForms(form,click_listen) {
jQuery.noConflict();
jQuery('form').hide();//hide initially
jQuery("#click_listen").click(function(e){
jQuery(form).toggle('fast');//or just show instead of toggle
});
}
function reportError(request) { alert("Something Went Wrong, Please Submit A Support Ticket.");}
</script>
and LoadSubSelects is the function in question, and the PHP results:
What I am trying to bind in the results (I think)
the PHP code:
$query="SELECT letter_id,letter_title FROM letter_template where letter_category_id = $catid";
$result = mysql_query ($query) or die(mysql_error());
echo'<select name="sselect1" class="e1" style="width:100% !important; height: 1.85em !important; color: #a8a8a8 !important; border-color:#d7d7d7 ! onChange="loadSubSelects(this.value,\'write_letter\',this.name)"><option value="0">Please Select A Letter</option>';
// printing the list box select command
while($catinfo=mysql_fetch_array($result)){
//Array or records stored in $nt
echo "<option value=\"".htmlspecialchars($catinfo['letter_id'])."\">".$catinfo['letter_title']."</option>";
}
echo"</select>";
echo htmlspecialchars($catinfo['letter_id']);
Any help would be most appreciated, thanks so much guys :)
Related
I have an AJAX autocomplete form. After many issues it works.
However I need help with three issues.
If the user type and result display, if the user backspace, the
results remain in schoollist. How do I clear schoollist
searchbox if is empty.
Some of the words contain letters like ë. When retrieved from the
database it display a ■ instead of ë.
If there is no results, it will display "School not found". If you click on school not found, it accepts the answer. I prevent clicking on "School not found?
HTML
<div class="ui-widget">
<label>What school does the child attend<input type="text" name="school" id="school" class="form-control" placeholder="Enter school Name"/></label>
<div id="schoollist"></div>
</div>
AJAX
$(document).ready(function(){
$('#school').keyup(function(){
var query = $(this).val();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#schoollist').fadeIn();
$('#schoollist').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#school').val($(this).text());
$('#schoollist').fadeOut();
});
});
PHP
if (isset($_GET['term'])){
$return_arr = array();
try {
$conn = new PDO("mysql:host=".DB_SERVER.";port=8889;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT School FROM Schools WHERE School LIKE :term');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['School'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
}
https://jsfiddle.net/47v1t3k4/1/
1- I think a simple empty before your AJAX call will solve the problem: $('#schoollist').empty();
2- Use <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> In your html, and also try to set the content type header of your response to utf-8 Like this: header('Content-Type: text/html; charset=utf-8');
3- To prevent click event if no result found you have to use off method:
$('#school').keyup(function(){
var query = $(this).val().trim();
$('#schoollist').empty();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#schoollist').fadeIn();
$('#schoollist').html(data);
if ( data.indexOf("School not found") > -1 ) {
// detach click event
$(document).off('click', 'li', go);
} else {
// attach click event
$(document).on('click', 'li', go);
}
}
});
}
});
function go(){
$('#school').val($(this).text());
$('#schoollist').fadeOut();
}
For 1. issue:
$(document).ready(function(){
// I added two new variables:
var $schoolInput = $('#school');
var $schoolList = $('#schoollist');
$schoolInput.on('keyup', function(){
var query = $(this).val();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$schoolList.html(data).fadeIn();
}
});
}
else { // It's answer for your 1. issue:
$schoolList.fadeOut().html('');
}
});
$(document).on('click', 'li', function(){
$schoolInput.val($(this).text());
$schoolList.fadeOut();
});
});
For 2. issue:
Probably your database has invalid charset. Try to use utf8_general_ci.
For 3. issue:
I suggest to do this if you find a list of schools then enter the response from the server to #schoollist - that is like now. Otherwise, if no school is found then pass a string such as 'notFound'. And then:
$(document).ready(function(){
// I added two new variables:
var $schoolInput = $('#school');
var $schoolList = $('#schoollist');
$schoolInput.on('keyup', function(){
var query = $(this).val();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
// 3. issue:
if(data == 'notFound') {
$schoolList.html('<div class="notFound">School not found</div>').fadeIn();
}
else {
$schoolList.html(data).fadeIn();
}
}
});
}
else { // It's answer for your 1. issue:
$schoolInput.val($(this).text());
$schoolList.fadeOut().html('');
}
});
$(document).on('click', 'li', function(){
$schoolInput.val($(this).text());
$schoolList.fadeOut();
});
// 3. issue
$(document).on('click', '.notFound', function(){
var text = $(this).text();
$schoolInput.val(text);
});
});
I am appending a button to a row when adding via Ajax and PHP:
var addHistory = function()
{
var patient_medication = $("#patient_medicationn").val();
var disease = $("#disease option:selected").text();
var patient_side_effect = $("#patient_side_effect").val();
var pid = $("#pid").val();
var elem = '<button type="button" class="btn btn-danger btn-sm"
id="delete_disease" name="delete_disease"><i class="fa fa-remove"></i>
</button>';
$.ajax({
url: '../php/history.php',
data: {pid: pid, patient_medication: patient_medication, disease:
disease, patient_side_effect: patient_side_effect},
type: 'POST',
dataType: 'TEXT',
success:function(resp)
{
console.log(resp)
$("#after_th").after("<tr id='resp'><td>"+disease+"</td><td>"+patient_medication+"</td><td>"
+patient_side_effect+"</td><td>"+elem+"</td></tr>")
},
error:function(resp)
{
console.log(resp)
}
})
}
And on click:
$(document).ready(function()
{
$("#add_history").on('click', addHistory);
});
In my php file:
$addHistory = "INSERT INTO history(patient_medication, patient_side_effect, disease, patient_id, clinic_id)
VALUES(:patient_medication, :patient_side_effect, :disease, :patient_id, :clinic_id)";
$ExecAddHistory = $conn->prepare($addHistory);
$ExecAddHistory->bindValue(':patient_medication', $patient_medication);
$ExecAddHistory->bindValue(':patient_side_effect', $patient_side_effect);
$ExecAddHistory->bindValue(':disease', $disease);
$ExecAddHistory->bindValue(':patient_id', $pid);
$ExecAddHistory->bindValue(':clinic_id', $clinic_id);
$ExecAddHistory->execute();
$lastId = $ExecAddHistory->lastInsertId();
echo $lastId;
I am echoeing the last insert ID so I can append it to the newly added <tr> and then if directly the user clicked on the remove button, to delete directly if a mistake happened while adding the history.
Now everything working properly and the new row is appending, but it's remove button does not work at all.
The remove button of already existing rows works fine:
$("#delete_disease ").on('click', function()
{
var elem = $(this).closest('tr');
console.log(elem)
var patient_medication_id = $(this).closest('tr').attr('id');
var pid = $("#pid").val();
if(confirm("Are you sure that you want to remove the selected history?"))
{
$.ajax({
url: "../php/deleteDiseaseFromHistory.php",
type: 'POST',
data: { pmid: patient_medication_id, pid: pid},
dataType: 'TEXT',
success:function(resp)
{
if(resp="deleted")
{
elem.fadeOut(800, function() {
//after finishing animation
});
}
},
error:function(resp)
{
alert("Please try again");
}
});
}
});
You need
$(document).on('click', '#delete_disease ', function(event)
in place of
$("#delete_disease ").on('click', function()
Since the content has been loaded through AJAX.
On first time page load, help text and announcements are displayed, on refresh after validation the help text and announcement don't show again on the view. I think I need to on page load call change event for both drop down, I'm not quiet sure how to do this. The first dropdown Div id is #profession and the second drop down is div id is #enquirytype.
$('#profession').on('change', function (e) { //Gets the ID of profession drop down list
var selectedVal = $(this).val(); //Variable selectedVal this . value
$.ajax({ //Ajax declared
type: 'GET', //Its a get
url: "#Url.Action("GetenquiryTypes", "UnauthEnquiry")", //It goes to the enquiry controller method GetenquiryTypes
dataType: 'json', //Datatypes JSON
data: { SelectedProfession: selectedVal }, //data is SelectedProfession: selectedVal
success: function (json) { //Jquery Parse Json data from server on ajax success
if (json.helptext != undefined && json.helptext != '')
{
$('#ProfHelp').html(json.helptext)
$('#ProfHelpAlert').show(); ///////
}
else
$('#ProfHelpAlert').hide(); ///////
var targetDropdown = $('#enquirytype') //Var targetDropDropdown goes to dropdown ID enquiry type
targetDropdown.empty(); //target empty dropdown
$("<option />", {
val: "",
text: "Please select enquiry type" //Select enquiry type
}).appendTo(targetDropdown); //add to the target dd
if (json.enquiryTypes.length > 0) { //if JASON data from server greater then 0
for (var EnquiryType in json.enquiryTypes) { //go through each EnquiryType in JSON
$("<option />", {
val: json.enquiryTypes[EnquiryType].EnquiryId, //mapping
text: json.enquiryTypes[EnquiryType].Enquiryname //mapping
}).appendTo(targetDropdown); //add to drop down
};
}
targetDropdown.change();
}
});
});
$('#enquirytype').on('change', function (e) { //onlick of professions DD
var selectedVal = $(this).val(); //Variable selectedVal this .value
$('#enquiryTypeHelpAlert').hide(); ///////
$('#EnquiryTypeAnnouncements').empty();
if (selectedVal != undefined && selectedVal != '') {
$.ajax({
type: 'GET', //Get
url: "#Url.Action("GetEnquiryTypeAndAnnoncements", "UnauthEnquiry")", //It goes to the enquiry controller method GetenquiryTypes
dataType: 'json', //Datatypes JSON
data: { SelectedEnquiryType: selectedVal }, //data is SelectedProfession: selectedVal
success: function (json) { //Jquery Parse Json data from server on ajax success
if (json.helptext != undefined && json.helptext != '') {
$('#enquiryTypeHelp').html(json.helptext)
$('#enquiryTypeHelpAlert').show(); ///////
}
else
$('#enquiryTypeHelpAlert').hide(); ///////
var announcement = $('.EnquiryTypeAnnouncement:first').clone();
$('#EnquiryTypeAnnouncements').empty();
$('#enquiryTypeHelp').html(json.helptext);
for (var i in json.announcements) {
var announcementCopy = announcement.clone();
announcementCopy.find(".notification").html(json.announcements[i]);
$(announcementCopy).appendTo($('#EnquiryTypeAnnouncements')).show();
$('#EnquiryTypeAnnouncements').show();
}
}
});
}
});
That seems correct as on change will keep your DD help text loaded.
$(document).ready(function () {
$('#profession').change(); //Keeps profession dropdown list help text displayed
});
As its not in the Jquery you have to get it from the model.
var EnquiryType ='#Model.EnquiryType
Then get it in the change event.
In the beginning of ypur script call your Professions dropdown in a function such as
$(document).ready(function () {
$('#profession').change(); //Keeps profession dropdown list help text displayed
});
Next as the enquiry type is not available in Jquery. you have get that from Model. By using
var EnquiryType ='#Model.EnquiryType
Then get it in the change event.
I have dropdown list of country suggestions and input above. When i click on one of them - AJAX should work(and it does) and add value to #msg_native. HTML:
echo '<div class="search_native"><input type="text" name="native_input" id="native"/>';
echo "<div id='output'></div></div>";
All JQUERY :
<script type="text/javascript">
$(document).ready(function() {
$("input").keyup(function(){
$array = ['usa','france','germany'];
$input_val = $("input[name='native_input']").val();
$('#output').text('')
r = new RegExp($input_val)
for (i = 0; i < $array.length; i++) {
if ($array[i].match(r)) {
$('#output').append('<p class="match">' + $array[i] + '</p>')
}
}
});
$(document).on('click', '.match', function(){
$value = $(this).text();
$('#native').val($value);
});
});
</script>
<script type="text/javascript">
$(function() {
$('#native').change(function() {
alert('cl');
$.ajax({
type: "POST",
url: "home.php",
dataType: 'json',
encode: true,
data: {native_input: $("input[name='native_input']").val()},
cache: false,
success: function(data){
alert(data);
$("#msg_native").after(data);
}});
return false;
});
});
</script>
The problem is that the value that gets posted is only what Ive typed myself, regardless on clicked element. But I want complete value- not only typed letters...so it firstly posts value and then 'finishes' the input (if clicked)
What can you practically advice to me?
data: {native_input: $value},
returns empty string
Some of this might be debatable but I put those in place for maintainability of the code and/or to match the most recent jQuery.
Only use one document ready handler (if possible)
Remove all the global objects (put var in front of them)
Use the native id when possible as fastest selector (not $("input[name='native_input']") for instance)
use this in the event handler, not the full selector (see next item)
If I enter "France" not "france" match does not work so need to case that input to equality var $input_val = $(this).val().toLowerCase();
You start with an empty field, might be good to show the match for that - simply trigger the keyup on startup to show all the array: }).trigger('keyup'); Now they are available for your clicking.
Attach the click handler on the wrapper for the "match" elements: $('#output').on('click', '.match', function() {
Use the promise form of the ajax .done(
Create a new custom event instead of the "change" on the native. We can then trigger that event as/when needed (the real issue you describe) Example: $('#native').trigger('myMatch'); and as I use it here:
trigger the event on a full match:
if (jQuery.inArray($input_val, $array) !== -1) {
$(this).trigger('myMatch');
}
Revised code:
$(document).ready(function() {
$("#native").on('keyup', function() {
var $array = ['usa', 'france', 'germany'];
var $input_val = $(this).val().toLowerCase();
$('#output').html('');
var r = new RegExp($input_val);
for (var i = 0; i < $array.length; i++) {
if ($array[i].match(r)) {
$('#output').append('<p class="match">' + $array[i] + '</p>');
}
}
// full match entered, trigger the match
if (jQuery.inArray($input_val, $array) !== -1) {
$(this).trigger('myMatch');
}
}).on('myMatch', function() {
alert('cl');
var nativeMatch = {
native_input: $("#native").val()
};
$.ajax({
type: "POST",
url: "home.php",
dataType: 'json',
encode: true,
data: nativeMatch,
cache: false
}).done(function(data) {
alert(data);
$("#msg_native").after(data);
});
return false;
}).trigger('keyup');
$('#output').on('click', '.match', function() {
var $value = $(this).text();
$('#native').val($value).trigger('myMatch');
});
});
What I want to do is, I want to display the selection that registered under accType=Acc1 in Selection. The AccInfo function is my ajax call. I would like to pass the parameter in data. The Acc_response function is a function to operate the option value. I would like to show the branchCode,accType,Code, that is registered under Acc1. How can I do that?
function AccInfo(Acc1){
$.ajax({
type:"POST",
datatype:"json",
async:true,
data:{A:Acc1},
url:AccInfo_url,
success: function(data){
Acc_response(data);
},
error: function(jqXHR, textStatus){
errorHandling(textStatus);
}
})
}
function Acc_response(data){
console.log(data);
for (var i=0;i<data.ClientInfo.length;i++)
{
var $option=$('<option />');
$option.attr('value', data.ClientInfo[i].branchCode+"|"+data.ClientInfo[i].Code+"|"+data.ClientInfo[i].accType);
$option.text(data.ClientInfo[i].accType+" (" + data.ClientInfo[i].Code+"-"+data.ClientInfo[i].branchCode+") ";
$('#Selection').append($option);
}
}
This is more usefull;
var selectedAccType = 'your account type';
//you can set this at post action to
function Acc_response(data){
data.ClientInfo.forEach(function(client) {
if(client.accType==selectedAccType){
var optionValue = client.branchCode+'|'+client.Code+'|'+client.accType;
var optionText = client.accType+'('client.Code+'-'+client.branchCode+')';
var option = '<option value="'+optionValue+'">'+optionText+'</option>';
$('#Selection').append(option);
}
});
}
This works for if you have one <select>. If you have more selects send us your html code.