I have a jQuery dialog that needs to be opened and populated with data from a database. The dialog has in it drop downs that when in a "new" mode (not editing for re-saving) cascade.
How can I load the dialog with the values from the database, while at the same time causing the cascading to happen.
I have tied using the onfocus event of the dialog when the dialog is in "edit" mode, but the focus hit every time an element gets focus. Didn't work without being sneaky with the editing mode.
I have tried opening the dialog and using jQuery to set the dropdown, which works, but then the cascading does work.
For the cascading I am using .change on the the different dropdowns.
Not sure if the code is going to help, but will post some to itterate the jQuery functionality I am using.
The question is: How do I open a dialog, load dropdowns with information from the server and have the .change functionality work?
$('#collectDD').change(function(){
// first change the item drop down list
var collection = $('#collectDD').val();
data = "coll=" + collection + "&action=getItems&func=";
$('#addCollection').text(collection);
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
$('#itemDD').empty();
$("#itemDD").html(html);
// now update the function collection dropdown
data = "coll=" + collection + "&action=getFunction";
}
});
Collection DD HTML
<select id="collectDD" name="collectionDD">
<option>Select Collection</option>
<option>Option1</option>
</select>
This doesn't exactly match up with your tag names, and I made a little change to the data string, but I think it's in line with what you're looking for
<div id="dialogbox">
<select id="s1"></select>
<select id="s2"></select>
<select id="s3"></select>
</div>
<script type="text/javascript">
$(document).ready( function() {
$( "#dialogbox" ).dialog({
open: function(event, ui) {
var s1 = $("#s1").empty();
var s2 = $("#s2").empty();
var s3 = $("#s3").empty();
s1[0].enabled = false;
s2[0].enabled = false;
s3[0].enabled = false;
//load first dropdown from the database
var data = "coll=dropdown1&val=&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s1.html(html);
s1[0].enabled = true;
}
});
//load the second DD when the first changes
s1.change( function() {
s2[0].enabled = false; //disable until after ajax load
s3[0].enabled = false;
data = "coll=dropdown2&val=" + s1.text() + "&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s2.empty().html(html);
s2[0].enabled = true;
}
});
});
s2.change( function() {
if (s2[0].enabled) { //test for enabled to prevent some unnessecary loads
s3[0].enabled = false;
data = "coll=dropdown3&val=" + s2.text() + "&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s3.empty().html(html);
s3[0].enabled = true;
}
});
}
});
}
});
});
</script>
UPDATE
Here is an example with change functions in their own functions
<div id="dialogbox">
<select id="s1"></select>
<select id="s2"></select>
<select id="s3"></select>
</div>
<script type="text/javascript">
var s1, s2, s3, data;
$(document).ready( function() {
s1 = $("#s1").empty();
s2 = $("#s2").empty();
s3 = $("#s3").empty();
$( "#dialogbox" ).dialog({
open: function(event, ui) {
s1[0].enabled = false;
s2[0].enabled = false;
s3[0].enabled = false;
//load first dropdown from the database
data = "coll=dropdown1&val=&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s1.html(html);
s1[0].enabled = true;
}
});
//load the second DD when the first changes
s1.change( changeDD1 );
//load the third DD when the second changes
s2.change( changeDD2 );
}
});
});
function changeDD1() {
s2[0].enabled = false; //disable until after ajax load
s3[0].enabled = false;
data = "coll=dropdown2&val=" + s1.text() + "&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s2.empty().html(html);
s2[0].enabled = true;
}
});
}
function changeDD2() {
if (s2[0].enabled) { //test for enabled to prevent some unnessecary loads
s3[0].enabled = false;
data = "coll=dropdown3&val=" + s2.text() + "&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s3.empty().html(html);
s3[0].enabled = true;
}
});
}
}
</script>
Related
I have the following code where I wanna remove and add an element back to the DOM in jQuery:
var pm_container = $(document).find('.pm-container');
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this), pm_container);
});
function displayPrice(elem, pm_container){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').remove();
} else {
$(document).find('.save-listing').prev(pm_container);
}
}
});
}
For some reason, when the value of amount_field is not equal to zero, my element .pm-container is not added back into my page.
Any idea why?
Thanks for any help.
When you remove the element, it is gone. there is no way to get it back. one solution is to clone the element into a variable and be able to re-use it later:
var pm_container = $(document).find('.pm-container').clone();
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this), pm_container); });
function displayPrice(elem, pm_container){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').remove();
} else {
$(document).find('.save-listing').prepend(pm_container);
}
}
}); }
However, for your case, Best way could be hiding and showing back the element:
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this)); });
function displayPrice(elem){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').hide();
} else {
$(document).find('. pm-container').show();
}
}
}); }
First create a variable for your Clone .pm-container outside ajax function
Note*: When you use .remove() you cannot take it back.
var container = $(".pm-container").clone();
then inside your ajax function
if (amount_field.val() == 0) {
$(".pm-container").detach();
} else {
container.insertBefore($(".save-listing"));
}
jsfiddle: https://jsfiddle.net/marksalvania/3h7eLgp1/
I have a JS script doing multiple AJAX requests. First I'm requesting a product by ID and then I'm requesting every single variant of this product. I can't do any form of backend coding since the environment I'm working in is closed.
My requests works fine, but right now I'm appending every single variant to a div, and my client don't really like this, so I was thinking is it possible to load all data into a variable and then fade in the parent div of all variants at the very end?
My script looks like this:
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
variants.find('.variant').fadeIn(300);
}
});
});
}
});
Some fast and dirty solution, but idea and concept of solution is clear. It is bad solution, but works for you in your case when you have no access to backend code.
var all_load_interval;
var is_all_data_ready = false;
var all_data_count = 0;
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
var data_count = $(data).find('Combinations Combination').length;
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
// make div with class variant hidden
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
// count every variant
all_data_count += 1
if (all_data_count == data_count) {
// when all data got and created, lets trigger our interval - all_load_interval
is_all_data_ready = true;
}
}
});
});
}
all_load_interval = setInterval(function() {
// Check does all data load every second
if (is_all_data_ready) {
// show all div.variant
variants.find('.variant').fadeIn(300);
clearInterval(all_load_interval);
}
}, 1000);
});
hey guys i'm trying to make changes in my blade template using ajax , when i press the button it changes the value of data in database and i want to display this data at once on my blade template .
that's my java script code :
(function($){
$('.wishlistForm').on('submit', function(){
var form = $(this);
$.ajax({
url: form.attr('action'),
data: form.serialize(),
method: 'post',
dataType: 'json',
success: function(response){
var wishlistButton = form.find("button[type='submit']");
var x = parseInt($('.wish-btn-count').text());
if(response.actiondone == 'added') {
$('.wish-btn-count').text(x++);
console.log(x);
wishlistButton.text(response.message);
} else if(response.actiondone == 'removed') {
$('.wish-btn-count').text(x--);
console.log(x);
wishlistButton.text(response.message);
}
}
});
return false;
});
})(jQuery);
and here is the part i want to change in my template :
<div class="wish-btn-count" id="wishlist">
{{$wishlistcount}}
</div>
so how can i do it ? and for record it returns the value right in the console but don't show it in my view
Prevent the default submit event, so you can trigger the ajax
$('.wishlistForm').on('submit', function(e){
e.preventDefault();
This may be the solution.
If you are receiving json object response from the ajax call,first you have to parse that object and then use it.
Try this,
(function($){
$('.wishlistForm').on('submit', function(){
var form = $(this);
$.ajax({
url: form.attr('action'),
data: form.serialize(),
method: 'post',
dataType: 'json',
success: function(response){
/*Add this in your code*/
var response = JSON.parse(response.trim());
var wishlistButton = form.find("button[type='submit']");
var x = parseInt($('.wish-btn-count').text());
if(response.actiondone == 'added') {
$('.wish-btn-count').text(x++);
console.log(x);
wishlistButton.text(response.message);
} else if(response.actiondone == 'removed') {
$('.wish-btn-count').text(x--);
console.log(x);
wishlistButton.text(response.message);
}
}
});
return false;
});
})(jQuery);
I am trying to make an ajax call for two separate click events. The difference is for the second click event the variable testOne should not be part of the call and instead there would be a new variable. How should I approach this?
var varOne = '';
var varTwo = '';
var varThree = '';
function testAjax(){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: {
testOne: varOne,
testTwo: varOne
}
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
varOne = 'xyz123';
varTwo = '123hbz';
testAjax();
});
$('.clickTwo').click(function(){
//varOne = 'xyz123'; // I dont need this for this click
varTwo = '123hbz';
varThree = 'kjsddfag'; // this gets added
testAjax();
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
Make some like this
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
var data= {
varOne: 'xyz123',
varTwo: '123hbz',
}
testAjax(data);
});
$('.clickTwo').click(function(){
var data= {
varThree : 'kjsddfag',
varTwo: '123hbz',
}
testAjax(data);
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
You can also do the same in other way with minimum line of code, you can call the ajax on click event and pass the data based on the element triggered the click event.
like this:
$('.ajax').click(function(e){
if($(this).hasClass('clickOne')){
var data= { varOne: 'xyz123'; varTwo: '123hbz'; }
}else{
var data= { varThree : 'kjsddfag'; varTwo: '123hbz'; }
}
$.ajax({
type: "POST",
dataType: 'json',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
e.preventDefault();
});
<div class="ajax clickOne"></div>
<div class="ajax clickTwo"></div>
In this way you can put as many conditions for different data variable.
You should be doing it like this:
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
var data {
varOne = 'xyz123',
varTwo = '123hbz'
}
testAjax(data);
});
$('.clickTwo').click(function(){
var data = {
varTwo = '123hbz',
varThree = 'kjsddfag'
}
testAjax(data);
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
This way you absolute control over which variables are added to which ajax call. You should not use global variables unless you really need them to be global, which doesn't seem to be the case.
You can pass whatever JavaScript object to the data parameter of the ajax method.
I just wanted to add something. I often hide value inside the value attribute of the button tags to produce something like this.
I haven't been able to test this of course but I thought it was worth mentioning.
jquery:
var fields = '';
function testAjax(){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: fields
}).done(function(data) {
$('.result').html(data);
});
}
$('#btn').click(function(){
var varCount = 0;
var vars = $(this).val().split('|');
$.each( vars, function( key, value ) {
varCount++;
fields = fields + 'var' + varCount + '=' + value + '&';
});
fields = fields.slice(0,-1);
$(this).val('123hbz|kjsddfag');
testAjax();
});
html:
<button id="btn" value="xyz123|123hbz"></button>
A more optimized and cleaner version -
var varTwo='junk1'
var varOne='junk2'
var varThree='junk3'
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
}
$('.ajaxClick').click(function(){
var data={};
if(this.classList.contains('clickOne')){
data.varOne=varOne;
data.varTwo=varTwo;
}else{
data.varThree=varThree;
data.varTwo=varTwo;
}
testAjax(data);
});
<div class="ajaxClick clickOne"></div>
<div class="ajaxClick clickTwo"></div>
Hi i have jquery request like below ,
$('#filterForm').submit(function(e){
e.preventDefault();
var dataString = $('#filterForm').serialize();
var class2011 = document.getElementById("2011").className;
//var validate = validateFilter();
alert(dataString);
if(class2011=='yearOn')
{
dataString+='&year=2011';
document.getElementById("2011").className='yearOff';
}
else
{
document.getElementById("2011").className='yearOn';
}
alert (dataString);
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
});
and my Form is like ,
<form method="post" name="filterForm" id="filterForm">
<!-- some input elements -->
</form>
Well, I am triggering jquery submit on submit event of a form ,(it's working fine)
I want pass one extra parameter inside form which is not in above form content but it's outside in page
it's like below
[Check this image link for code preview][1]
So how can i trigger above event , on click of , element with class yearOn ( check above html snippet ) and class yearOff , with additional parameter of year set to either 2011 or 2010
$(document).ready(function () {
$('#filterForm').submit(function (e) {
e.preventDefault();
var dataString = $('#filterForm').serialize();
if ($("#2011").hasClass('yearOn')) {
dataString += '&year=2011';
$("#2011").removeClass('yearOn').addClass('yearOff');
}
else {
$("#2011").removeClass('yearOff').addClass('yearOn');
}
$.ajax({
url: "/myServlet",
type: "POST",
data: dataString,
success: function (data) {
/*var a = data;
alert(data);*/
}
});
});
});
1.) If you are using jQuery already, you can use the $.post() function provided by jquery. It will make your life easier in most cases.
2.) I have always had a successful post with extra parameters this way:
Build you extra parameters here
commands={
year:'2011'
};
Combine it with your form serialize
var dataString=$.param(commands)+'&'+$("#filterForm").serialize();
Perform your post here
$.post("myServlet",data,
function(data) {
/*var a = data;
alert(data);*/
}
);
OR use $.ajax if you really love it
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
In the end, here is the full code the way you are doing it now
$('#filterForm').submit(function(e){
e.preventDefault();
var class2011 = document.getElementById("2011").className;
//var validate = validateFilter();
alert(dataString);
if(class2011=='yearOn') {
dataString+='&year=2011';
document.getElementById("2011").className='yearOff';
} else {
document.getElementById("2011").className='yearOn';
}
commands={
year:'2011'
};
var dataString=$.param(commands)+'&'+$("#filterForm").serialize();
alert (dataString);
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
});