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

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;
});

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>

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()},

How to include variable inside AJAX data

I am trying to send an Ajax request but I wanted to include variables that I have already defined in the data that is sent to the server.
I'm not quite sure how I can escape the data part and put a variable where I have stated...
$.ajax({
url: './json/delete.php',
type: 'POST',
async: false,
data: { SD_FieldDisplayName : <VARIABLE HERE>,
SD_FieldSeq : <VARIABLE HERE>,
SD_TableSeq : <VARIABLE HERE>,
SD_ViewName : <VARIABLE HERE> }
dataType: 'json',
success: function(result)
{
You forgot a comma after your data object.
$.ajax({
url: './json/delete.php',
type: 'POST',
async: false,
data: { SD_FieldDisplayName : <VARIABLE HERE>,
SD_FieldSeq : <VARIABLE HERE>,
SD_TableSeq : <VARIABLE HERE>,
SD_ViewName : <VARIABLE HERE> },
// You need a comma here ^
dataType: 'json',
success: function(result)
{
}
});
You can just reference the variable in the value of the key:
var someVar = 3;
data: { SD_FieldDisplayName : someVar }
You're almost there. You need to include in the variables you want to send through your AJAX request. Here's a stripped example. I've used $.post but $.ajax is essentially the same. It takes the data from a form with the class .formclicked (which other code labels with the class .formclicked. It sends through a 'relations' data with $_POST['relations'] and a method flag $_POST['method']. The first is defined by the form, the second is defined y the submit button in the form, that's not sent by serialise. The serialise function converts the form data in #an_id into a form suitable for AJAX.
// Comments
jQuery(document).on('submit','#an_id' ,function(){
$data = jQuery(this).serialize();
var selector = jQuery(this);
$method = jQuery(this).find(".formclicked").attr('value'); // Get clicked form
jQuery.post('your_ajax_form.php', {action:'hook_update',relations:$data, method:$method},
function(answer){
if(jQuery.isNumeric(answer)){
if(answer) {
// Response Code Based on Condition
}
else {
// Handle failures
jQuery(selector).find(".formclicked").removeClass('.formclicked');
}
}
else {
}
return true;
}
);
return false; // Prevent the page from refreshing
});
Please use this one :
var val1;
var val2;
var val3;
var val4;
$.ajax({
url: './json/delete.php',
type: 'POST',
async: false,
data: { SD_FieldDisplayName : val1 , SD_FieldSeq : val2 , SD_TableSeq : val3 , SD_ViewName : val4 },
dataType: 'json',
success: function(result)
{
}
});
please define variable inside of the function where you want call this ajxa call or global

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

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.

Categories