I have an ajax call to dynamically create select elements. the amount of selects is dependent on another select. This works fine. for my test 3 select menus should be created dynamically which works fine. the dynamically created selects will make ajax calls on their own to create some options dynamically, this is where I have the issue. Everything seems to be working except the options for a second select is not getting populated. Please see code below.
Thank you
$('#union').on('change',function(){
var union_id = $(this).val();
if(union_id){
$.ajax({
type:'POST',
url:'fetch_referee.php',
data:'union_id='+union_id,
dataType: 'json',
success:function(data){
$('#dynamic_selects').html(data.html);
var total = data.total;
for(i=1; i<=total; i++){
$('#allreferee'+i).on('change', function(){
var all_games = $(this).val();
//alert(all_games);// this is good output is valid
if(all_games){
$.ajax({
type:'POST',
url:'fetch_places.php',
data:'all_games='+all_games,
dataType: 'json',
success:function(html){
alert(html);/// this is good.. returns option values
$('#refposition'.i).html(html);//the select menu does not get updataded
}
});
}else{
$('#refposition'+i).html('<option value=""></option>');
}
});
}
}
});
}else{
}
});
You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content). Check this for more details
Your code should now look like this
$(document.body).on('change','#union',function(){
var union_id = $(this).val();
if(union_id){
$.ajax({
type:'POST',
url:'fetch_referee.php',
data:'union_id='+union_id,
dataType: 'json',
success:function(data){
$('#dynamic_selects').html(data.html);
var total = data.total;
for(i=1; i<=total; i++){
$(document.body).on('change','#allreferee'+i, function(){
var all_games = $(this).val();
//alert(all_games);// this is good output is valid
if(all_games){
$.ajax({
type:'POST',
url:'fetch_places.php',
data:'all_games='+all_games,
dataType: 'json',
success:function(data){
alert(html);/// this is good.. returns option values
$('#refposition'+i).html(data.html);//the select menu does not get updataded
}
});
}else{
$('#refposition'+i).html('<option value=""></option>');
}
});
}
}
});
}else{
}
});
I'm sure that your methodology is flawed, but if you must:
$('#union').change(function(){
var union_id = $(this).val();
if(union_id !== ''){
$.post('fetch_referee.php', 'union_id='+union_id, function(data){
$('#dynamic_selects').html(data.html);
$('[id^=allreferee').change(function(){ // I would give the Elements an HTML class instead - but
var t = $(this), all_games = t.val();
// console.log(all_games); // this is good output is valid ??
if(all_games === ''){
t.html("<option value=''></option>");
}
else{
$.post('fetch_places.php', 'all_games='+all_games, function(html){
// console.log(html); // this is good.. returns option values ??
t.html(html); // the select menu does get updataded ??
}, 'json');
}
});
}, 'json');
}
});
Related
I've got checkbox inputs on a page and am filtering the results using ajax.
One search option is type and the vendors option updates depending on the type selected. But this means that the change function used to update the actual results no longer works within the document.ready(). To rectify this, I also call the function within .ajaxComplete().
But as an ajax call is being called within the ajaxComplete(), it is causing an infinite loop and crashing the site.
$(document).ready(function(){
$('input[type=radio]').change(function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});
$('#vendor-filter input[type=checkbox]').change(function(){
filterResults(this);
});
});
$(document).ajaxComplete(function(){
$('#vendor-filter input[type=checkbox]').click(function(){
filterResults(this);
});
});
function filterResults($this)
{
var type = $('input[type=radio]:checked').attr("data-id");
var vendor = $($this).attr('data-id');
if($($this).prop('checked'))
{
var action = 'add';
vendors.push(vendor);
}
else
{
var action = 'remove';
var index = vendors.indexOf(vendor);
if(index >= 0)
{
vendors.splice(index, 1);
}
}
$.ajax({
method: 'POST',
url: 'assets/ajax/filter-results.php',
data: {'vendor' : vendor, 'action' : action, 'vendors' : vendors, 'filter_type' : type},
success: function(data)
{
$('#results').empty();
if(action == 'add')
{
window.history.pushState("", "Title", window.location.href+"&v[]="+vendor);
}
else if(action == 'remove')
{
var newUrl = window.location.href.replace("&v[]="+vendor, "");
window.history.replaceState("", "Title", newUrl);
}
$('#results').html(data);
}
});
}
How do I get the .change function to still work after the input checkbox has been called via ajax previously and without causing a loop with .ajaxComplete() ?
Any help would be greatly appreciated.
Thanks
Please try by change function as follow :
$(document.body).on("change",'input[type=radio]',function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});
Hi everyone I have a script that has an ajax call within it.
$(document.body).on('click', '#postAppt', function (e) {
var serviceSelected = $("#selectServ option:selected").val();
var location = $('input[name="location"]:checked').val();
var price = $("#sessionPrice").val();
var date = $("#apptDate").val().replace(/\-/g, '');
var time = $("#time option:selected").val();
if(!$('input[name="location"]:checked').val()){
alert("Please select a location!");
return false;
}else{
$("#schedulePhaseOne").hide();
$("#schedulePhaseTwo").show();
$("#goBackSP").show();
var userid = $('div[id^="prfSchedule"').attr("id").replace("#", "").replace("prfSchedule","");
$.ajax({
type: "POST",
url: "../users/functions.php?id=" + userid,
data: {getServDetails: serviceSelected},
cache: false,
success: function(result){
alert("success");
}
});
}
return false;
});
the ajax call only seems to work on desktop devices and not on mobile. I've been conflicted for a couple of hours now. Any suggestions? Also i want to load the contents (which are html) into a bootstrap modal. Could this also be a problem?
I think it's the problem of cross-domain.
i'm passing the array value to url like this
view code
from_multiselect('functio[]',$function,'','id=function')
baseurl/test/roles?id=1,2,3
this is my jquery
$("#role > option").remove();
var id = $('#function').val();
alert(id);
var str=new Array();
alert(id);
$.ajax({
type: "POST",
url: "test/roles?id="+id,
success: function(roles)
{
alert(roles);
$.each(roles,function(id,roles)
{
var opt = $('<option />');
opt.val(id);
opt.text(roles);
$('#role').append(opt);
});
}
});
});
});
Page give error when i pass the array value in url like Disallowed Key Characters.
Thank in advance
and then post this array like this:
$("#role > option").remove();
var id = $('#function').val();
var valArray = id.split(',');
var str=new Array();
alert(id);
$.ajax({
type: "POST",
url: "test/roles?id="+valArray,
success: function(roles)
{ alert(roles);
$.each(roles,function(id,roles)
{
var opt = $('<option />');
opt.val(id);
opt.text(roles);
$('#role').append(opt);
});
}
});
});
});
in the method add parameter to accept array.
This is CodeIgniter error.
So, to solve this, please go to
/application/config/config.php
AND
search for
$config['permitted_uri_chars']
change to:
$config['permitted_uri_chars'] = 'a-z 0-9~%\.\:_\+-,?&=';
I'm a pretty new programmer who made an application that sends out a heartbeat every 3 seconds to a php page and returns a value, the value of which decides which form elements to display. I've been fairly pleased with the results, but I'd like to have my jquery as fast and efficient as possible (its a little slow at the moment). I was pretty sure SO would already have some helpful answers on speeding up heartbeats, but I searched and couldn't find any.
So here's my code (just the jquery, but I can post the php and html if needed, as well as anything anyone needs to help):
<script type="text/javascript">
$(document).ready(function() {
setInterval(function(){
$('.jcontainer').each(function() {
var $e = $(this);
var dataid = $e.data("param").split('_')[1] ;
$.ajax({
url: 'heartbeat.php',
method: 'POST',
contentType: "application/json",
cache: true,
data: { "dataid": dataid },
success: function(data){
var msg = $.parseJSON(data);
if (msg == ""){ //after reset or after new patient that is untouched is added, show checkin
$e.find('.checkIn').show();
$e.find('.locationSelect').hide();
$e.find('.finished').hide();
$e.find('.reset').hide();
}
if ((msg < 999) && (msg > 0)){ // after hitting "Check In", Checkin button is hidden, and locationSelect is shown
$e.find('.checkIn').hide();
$e.find('.locationSelect').show();
$e.find('.finished').hide();
$e.find('.reset').hide();
$e.find('.locationSelect').val(msg);
}
if (msg == 1000){ //after hitting "Checkout", Option to reset is shown and "Finished!"
$e.find('.checkIn').hide();
$e.find('.locationSelect').hide();
$e.find('.finished').show();
$e.find('.reset').show();
}
}
});
});
},3000);
$('.checkIn').click(function() {
var $e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of button (1 for the first button)
// You can map this to the corresponding button in database...
$.ajax({
type: "POST",
url: "checkin.php",
// Data used to set the values in Database
data: { "checkIn" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.locationSelect').show();
$container.find('.locationSelect').val(1);
}
});
});
$('.reset').click(function() {
var $e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of button (1 for the first button)
// You can map this to the corresponding button in database...
$.ajax({
type: "POST",
url: "reset.php",
// Data used to set the values in Database
data: { "reset" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.checkIn').show();
}
});
});
$('.locationSelect').change(function(e) {
if($(this).children(":selected").val() === "CheckOut") {
$e = $(this);
var data = $e.data("param").split('_')[1] ;
$.ajax({
type: "POST",
url: "checkout.php",
// Data used to set the values in Database
data: { "checkOut" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.finished').show();
$container.find('reset').show();
}
});
}
else{
$e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of select (1 for the first select)
// You can map this to the corresponding select in database...
$.ajax({
type: "POST",
url: "changeloc.php",
data: { "locationSelect" : $(this).val(), "selectid" : data},
success: function() {
// Do something here
}
});
}
});
});
</script>
Thanks for all and any help! Please just ask if you need any more details! Thanks!
Alot of factors could be causing slowness. Some things to consider:
The speed of the heartbeat is not dependent on your client-side javascript code alone. There may be issues with your server-side php code.
Also, a heartbeat every three seconds is very frequent, perhaps too frequent. Check in your browser's developer debug tools that each of the requests is in fact returning a response before the next 3 second interval. It could be that your server is slow to respond and your requests are "banking up".
You could speed your your jQuery a fraction by streamlining your DOM manipulation, eg:
if (msg == "")
{
$e.find('.checkIn').show();
$e.find('.locationSelect, .finished, .reset').hide();
}
Below is the code through which I get the values of checked input boxes:
$('#agent_region').click(function()
{
var ids = $('#agent_favourites_form input:checked').map(function(){
return this.value;
}).get();
$.ajax({
type: "POST",
url: "set_agent_favourites.php",
data: {map: ids},
success: function(msg){
$.jnotify(msg, 3000);
}
});
return false;
});
I want to get the values of unchecked checkboxes as well and pass it, I don't know how to pass two data: {map : ids}, {map1 : ids1} or something else. Please help.
You can use input:not(:checked) and just add it into your data object:
$('#agent_region').click(function()
{
var ids = $('#agent_favourites_form input:checked')
.map(function(){
return this.value;
}).get();
var nonids = $('#agent_favourites_form input:not(:checked)')
.map(function(){
return this.value;
}).get();
$.ajax({
type: "POST",
url: "set_agent_favourites.php",
data: {map: ids, unmap: nonids},
success: function(msg){
$.jnotify(msg, 3000);
}
});
return false;
});
Use the jQuery checked selector
See: http://api.jquery.com/checked-selector/
$(function() {
var checked = {};
var unchecked = {};
$('input[type=checkbox]').each(function() {
if ($(this).is(':checked')) {
checked[$(this).attr('name')] = $(this).val();
} else {
unchecked[$(this).attr('name')] = $(this).val();
}
});
// Only works with FireBug enabled
console.debug(checked);
console.debug(unchecked);
});
Demo: http://jsfiddle.net/x3TcD/