Ajax on success of another ajax doesn't work in ie - javascript

I do an ajax call to get a list of all elements, say Products and populate them in a table with checkboxes. Then I make another ajax call to get which products were already selected and select them. This works in all browsers except ie. Am I doing something wrong?
$.ajax({
url : "${product_category_url}",
data : {"orgID":"${globalOrganisation.id}"},
dataType : "html",
statusCode: {
401: function() {
$('.ui-tabs-panel:visible').html("${ajax_session_expired}");
}
},
success : function(data) {
$("#productCategoryContainer").html(data);
$.ajax({
url: "${get_taggedProd_url}",
data: {"questionnaireId":_questionnaireId},
dataType: "json",
success: function(data){
var productIds = data.products;
$.each(productIds,function(index,value){
var obj = $('input[name="'+value+'"]');
obj[0].checked = true
selectRow(obj[0]);
});
}
});
}
});

This is due to caching by IE.
Please try this
$.ajax({
url : "${product_category_url}",
data : {"orgID":"${globalOrganisation.id}"},
dataType : "html",
statusCode: {
401: function() {
$('.ui-tabs-panel:visible').html("${ajax_session_expired}");
}
},
success : function(data) {
$("#productCategoryContainer").html(data);
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
$.ajax({
url: "${get_taggedProd_url}",
data: {"questionnaireId":_questionnaireId},
dataType: "json",
success: function(data){
var productIds = data.products;
$.each(productIds,function(index,value){
var obj = $('input[name="'+value+'"]');
obj[0].checked = true
selectRow(obj[0]);
});
}
});
}
});
and if you need more details please look into this

The thing in this code that always screws me up is trying to get the check box selected. Make sure obj[0].checked = true actually works.

Related

cart data not update in shopify using ajax

I have a Problem in Shopify.
I want update cart quantity on button click using ajax but it will give error like
{"status":404,"message":"Cart Error","description":"Cannot find variant"}
Here is my ajax code,
$('.adjust-plus').click(function(){
var qty = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').val();
var varient = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').attr('data-id');
jQuery.ajax({
type: 'POST',
async: false,
url: '/cart/update.js',
data: { updates: { varient : qty } },
dataType: 'json',
success: function() { location.href = '/cart'; }
});
});
currently in both variable value come so no any error in value.
but when id add code like:
$('.adjust-plus').click(function(){
var qty = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').val();
var varient = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').attr('data-id');
jQuery.ajax({
type: 'POST',
async: false,
url: '/cart/update.js',
data: { updates: { 15082896588867 : 2 } },
dataType: 'json',
success: function() { location.href = '/cart'; }
});
});
then cart updated successfully.
Firstly, remove async: false as it's very bad practice and not needed here as you're using the success callback properly.
The issue itself is because you cannot use variables as the keys of an object with the syntax you're using. To get around this you can use bracket notation, like this:
$('.adjust-plus').click(function() {
var $quantity = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity');
var qty = $quantity.val();
var varient = $quantity.data('id');
var data = { updates: {} };
data.updates[varient] = qty;
jQuery.ajax({
type: 'POST',
url: '/cart/update.js',
data: data,
dataType: 'json',
success: function() {
location.href = '/cart';
}
});
});

Executing javascript function on AJAX success in WP

I have a function in my Wordpress that regenerate Google Map.
What I want to achieve is to get some markers from my WP, then add them to DIV and generate from them map again.
For regenerating I'm using simple function with magic name "regenerate_map()" :) .
jQuery(".gmaps-button").click(function(){
jQuery.ajax({
type: "POST",
//contentType: "application/json; charset=utf-8",
dataType: "text",
url: myAjax.ajaxurl,
data : {action: "jv_get_map_data", ids : 1},
//data: dataString,
action: 'jv_get_map_data',
beforeSend: function() {
//jQuery('#contact-form #err2').html('').hide();
//jQuery(".submit").html("proszę czekać").addClass('loading');
},
success: function(text) {
jQuery('#gmaps-markers').html(text);
console.log(text);
regenerate_map();
}
});
return false;
});
The main problem is that function regenerate_map() is not working.
I get "ReferenceError: regenerate_map is not defined".
This is not true, because, I have other button, which is a trigger for click() and it uses this function also and it works.
I think that is something wrong with executing other function in AJAX request, but console.log and alert() works.
I thought that problem can be with what I get as "text" but I have checked that even if I get nothing, problem exists too.
Maybe some security issue?
Can somebody tell me why and what to do to achieve what I need?
your regenerate_map() function should be like this.
<script>
jQuery(document).ready(function() {
jQuery("#p_button").click ( function () {
console.log("button got clicked");
var donor_data= [ "12","13","14" ];
var damount = 1234;
var donor_obj = {
id : donor_data,
amnt : damount,
};
jQuery.ajax({
type:"POST",
//dataType : "json",
url: "<?php echo admin_url( 'admin-ajax.php' );?>",
data: { action : "ajx_add_donations",
'donors' : JSON.stringify(donor_obj),
},
success:function(response){
console.log("success " ,response);
//console.log("success " + JSON.parse(response));
//jQuery("#d_amount").val(donor_data[0]);
//jQuery("#p_button").text("brrr");
regenerate_map();
},
error: function(response) {
console.log("error" + response);
},
});
});
});
function regenerate_map(){
alert("test");
}
</script>

Ajax code working in some parts and not working in others

I have a problem with my Ajax request to download some data from a database.
There are two codes down below: one that works and one that doesn't, even though they are basically the same. I've also set up later down my code to display the variable (console.log(location)) but it just reads undefined.
I know the php part of it is working because I also do another console.log(data) on success of the ajax call and that returns with the data I entered on my database. What's going on and how do I fix it?
Code that doesn't work:
var location;
function downloadCoords() {
$.ajax({
type: 'GET',
url: 'transformerthing.php',
dataType: "json",
success: function(data) {
console.log(data);
location = data.location;
},
error: function(data) {
console.log(data);
}
});
}
Code that does work:
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
dataType: "json",
success: function(data) {
console.log(data);
mapCode = data.mapCode;
used = data.used;
active = data.active;
},
error: function(data) {
console.log(data);
}
});
}
//shorthand deferred way
$.getJSON( "transformerthing.php")
.done(function(data){
console.log(data);
}).fail(function(msg){
console.log(msg)
});
var location;
function downloadCoords() {
$.ajax({
type: 'GET',
url: 'transformerthing.php',
dataType: "json",
success: function(data) {
console.log(data);
location = data.location;
console.log(location);
},
error: function(data) {
console.log(data);
}
});
}
Try it again.

Not refreshing data each time

I have weired problem in my project.I have 2 tabs and in one tab i have chekboxes and submit button and user will select from checkboxes and on button click he will get what he has selected from checkboxes in another tab.It runs perfectly.But sometimes it does not refresh the data from ajax ,jquery and i have to complete refresh my page.I am not able to identify the problem as i am not getting any error. Atleast i have to click for more than 15 times then it will not refresh the data otherwise it works fine.
Here is my js code:
function getFahrzeuge() {
var opts = [];
$("#fahrzeuge input[type='checkbox']").each(function () {
if ($(this).is(':checked'))
{
opts.push($(this).attr("id"));
}
});
return opts;
}
function saveFahrzeugeWidget(opts){
if(opts.length == 0) return false;
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {'filterOpts' :opts, 'aktion' : 'save-widget-vehicle'},
success: function(data){
//getFahrzeugeWidget();
$('#fahrzeuge').html(data['html']);
},
error: function(data){
console.log(data);
}
});
}
function getFahrzeugeWidget(opts){
if(!opts || !opts.length){
opts = allFahrzeuge;
}
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {filterOpts:opts, 'aktion' : 'get-widget-vehicle'},
success: function(data){
$('#fahrzeuge').html(data.html);
},
error: function(data){
console.log(data);
}
});
}
function getFahrzeugeWidgetEdit(opts){
if(!opts || !opts.length){
opts = allFahrzeuge;
}
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {filterOpts:opts, 'aktion' : 'get-widget-vehicle-edit'},
success: function(data){
$('#fahrzeuge').html(data.html);
},
error: function(data){
alert('error' + data);
}
});
}
$('#fahrzeuge .butt-rahmen').live('click', function(){
var opts = getFahrzeuge();
if($(this).attr('id') == 'saveId')
{
saveFahrzeugeWidget(opts);
if($('#fahrzeuge input[type="checkbox"]:checked').length <=0) {
alert('überprüfen Sie bitte atleast ein fahrzeuge');
//getFahrzeugeWidgetEdit(opts);
}
}
});
The answer is getting cached. And you are receiving the same answer. Try to add a new parameter to data as timestamp.
So your data should look like this.
data: {'filterOpts' :opts, 'aktion' : 'save-widget-vehicle', 'timestamp': new Date().getTime()},

JavaScript/jQuery Variable Scope Issue with Nested .ajax() calls

I'm having a difficult time passing the variable postData which is a serialized jQuery array object to a nested child .ajax() call. postData is passed successfully to the first .ajax() call, but when I attempt to use it in the second .ajax() call, it does not post any form elements, as the variable is undefined at that level:
$(".myForm").submit(function () {
var postData=$(this).serializeArray();
$.ajax({
type : "POST",
async : false,
cache : false,
url : "./insertComment.php",
data : postData,
success: function() {
$.ajax({
type : "POST",
async : false,
cache : false,
url : "./getComments.php",
data : postData,
success: function(comments) {
$(".Comments").html(comments);
}
});
}
});
return false;
});
I tried creating a second variable _postData attempting to perpetuate the variable on to the next .ajax() call, but it was unsuccessful (also tried var _postData=$(this).parent().serializeArray(); but I still wasn't able to perpetuate the variable):
$(".myForm").submit(function () {
var postData=$(this).serializeArray();
$.ajax({
type : "POST",
async : false,
cache : false,
url : "./insertComment.php",
data : postData,
success: function() {
var _postData=$(this).serializeArray();
$.ajax({
type : "POST",
async : false,
cache : false,
url : "./getComments.php",
data : _postData,
success: function(comments) {
$(".Comments").html(comments);
}
});
}
});
return false;
});
I tried implementing so-called JavaScript closure (something I still don't fully grok), but that led to more undefined variables and more failure:
$(".myForm").submit(function () {
var postData = function() {
$(this).serializeArray();
}();
$.ajax({
type : "POST",
async : false,
cache : false,
url : "./insertComment.php",
data : postData,
success: function() {
$.ajax({
type : "POST",
async : false,
cache : false,
url : "./getComments.php",
data : postData,
success: function(comments) {
$(".Comments").html(comments);
}
});
}
});
return false;
});
I tried searching around and tried implementing several other techniques, including jQuery traversal (.parent(), .filter(), etc.), but was unsuccessful. I know this is a common problem for a lot of folks, but so far I have not found a simple, understandable solution. Any suggestions would be greatly appreciated. Thanks!
Try this:
$(".myForm").submit(function ()
{
var postData=$(this).serializeArray();
$.ajax({ type : "POST",
async : false,
cache : false,
url : "./insertComment.php",
data : postData,
success: (function(pData)
{
// capture the posted data in a closure
var _postData = pData;
return function()
{
$.ajax({ type: "POST",
async: false,
cache: false,
url: "./getComments.php",
data: _postData,
success: function(comments)
{
$(".Comments").html(comments);
}
});
}
})(postData) // execute the outer function to produce the colsure
});
return false;
});
Here's what I ended up doing:
$(".myForm").submit(function () {
var postData = $(this).serializeArray(); // Gets all of the form elements
var myID = $(this.ID).val(); // Takes only a single value from the form input named ID
$.ajaxSetup({
data : "ID=" + myID // Sets the default data for all subsequent .ajax calls
});
$.ajax({
type : "POST",
async : false,
cache : false,
url : "./insertComment.php",
data : postData, // Overwrites the default form data for this one instance only, including all form elements
success: function() {
$.ajax({
type : "POST",
async : false,
cache : false,
url : "./loadComments.php", // Notice there is no data: field here as we are using the default as defined above
success: function(comments) {
$(".Comments").html(comments);
}
});
}
});
return false;
});

Categories