Create function inside deprecated javascript function - javascript

Currently I have a javascript file structure which seems deprecated to me, inside this function there's an ajax call, and after the ajax call giving response I want to add ajax function, but if I have to define it 1 by 1 for every ajax response type, it will consume a lot of space so I need to make a function which will call this ajax function, but I don't know where to place this function that I will make. here's my code
return Component.extend({
defaults: {
template: 'Icube_Snap/payment/snap'
},
redirectAfterPlaceOrder: false,
afterPlaceOrder: function() {
$.getScript(js, function() {
$.ajax({
type: 'post',
url: url.build('snap/payment/redirect'),
cache: false,
success: function(data) {
var token = data;
var methods = [];
var methodSnap = $('input[name=snap-method]:checked').val();
snap.pay(token, {
enabledPayments: methods,
onSuccess: function(result) {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: resut.id,
message: result.message
}
success: function(data) {
}
});
},
onPending: function(result) {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: resut.id,
message: result.message
}
success: function(data) {
}
});
},
onError: function(result) {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: resut.id,
message: result.message
}
success: function(data) {
}
});
},
onClose: function() {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: resut.id,
message: result.message
}
success: function(data) {
}
});
}
});
}
});
});
}
});

I just added a successcallback and an errorcallback to the POST function. But if you want you can ignore those functions and implement the success and error functionality inside the function itself without using callbacks.
return Component.extend({
defaults: {
template: 'Icube_Snap/payment/snap'
},
redirectAfterPlaceOrder: false,
afterPlaceOrder: function() {
$.getScript(js, function() {
$.ajax({
type: 'post',
url: url.build('snap/payment/redirect'),
cache: false,
success: function(data) {
var token = data;
var methods = [];
var methodSnap = $('input[name=snap-method]:checked').val();
//Define a function to send the POST request here.
//////////////////////////////////////////////////
var sendPayment = function(param, successcallback, errorcallback) {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: param.id,
message: param.message
}
success: function(data) {
successcallback(data);
},
error: function(error) {
errorcallback(error);
}
});
};
snap.pay(token, {
enabledPayments: methods,
onSuccess: function(result) {
//Call sendPayment method and you can
//pass whatever you want.
sendPayment(result, function() {
//Call when success
}, function() {
//Call when error
});
},
onPending: function(result) {
sendPayment(result, function() {
//Call when success
}, function() {
//Call when error
});
},
onError: function(result) {
sendPayment(result, function() {
//Call when success
}, function() {
//Call when error
});
},
onClose: function() {
sendPayment(result, function() {
//Call when success
}, function() {
//Call when error
});
}
});
}
});
});
}
});

Related

How can I use callback function from ajax in another function

How can I use callback function from ajax in another function
I've got function with ajax:
function correct_date(raw_date){
return $.ajax({
method: "GET",
url: "../date/correct.php",
data: {
method: 'correct_date',
date: raw_date
},
cache: false,
dataType: 'json',
success: function(result) {
console.log(result.DATE_NEW);
showTheValue(result);
}
});
}
var showTheValue = function(correct_day_value) {
console.log(new Date(correct_day_value.DATE_NEW).toLocaleDateString('de-DE'));
return correct_day_value;
};
And I want to have the response/data value from ajax in another function like that:
function correct_start_date() {
document.getElementsByTagName("INPUT")[1].value = showTheValue();
}
How can I use response data from ajax in another function ?
You can you the JavaScript Promise.
http://www.html5rocks.com/en/tutorials/es6/promises/
function get(url) {
// Return a new promise.
return new Promise(function(resolve, reject) {
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};
// Make the request
req.send();
});
}
function correct_date(raw_date, callback){
return $.ajax({
method: "GET",
url: "../date/correct.php",
data: {
method: 'correct_date',
date: raw_date
},
cache: false,
dataType: 'json',
success: function(result) {
console.log(result.DATE_NEW);
return callback(result);
}
});
}
function showTheValue() {
correct_date(raw_date, function(correct_day_value) {
document.getElementsByTagName("INPUT")[1].value = correct_day_value;
});
}
You must use those two functions like:
function correct_date(raw_date){
return $.ajax({
method: "GET",
url: "../date/correct.php",
data: {
method: 'correct_date',
date: raw_date
},
cache: false,
dataType: 'json',
success: function(result) {
console.log(result.DATE_NEW);
correct_start_date(showTheValue(result));//***
}
});
}
var showTheValue = function(correct_day_value) {
console.log(new Date(correct_day_value.DATE_NEW).toLocaleDateString('de-DE'));
return correct_day_value;
};
function correct_start_date(correct_day_value) {
document.getElementsByTagName("INPUT")[1].value = correct_day_value;
}
Or if the "correct_start_date" is used according to a case:
function correct_date(raw_date){
return $.ajax({
method: "GET",
url: "../date/correct.php",
data: {
method: 'correct_date',
date: raw_date
},
cache: false,
dataType: 'json',
success: function(result) {
console.log(result.DATE_NEW);
var correct_day_value = showTheValue(result);
if (/* some case */) {
correct_start_date(correct_day_value);//***
}
}
});
}
Or wait until the value is set by the Ajax:
var globalVar = null;
function correct_date(raw_date){
return $.ajax({
method: "GET",
url: "../date/correct.php",
data: {
method: 'correct_date',
date: raw_date
},
cache: false,
dataType: 'json',
success: function(result) {
console.log(result.DATE_NEW);
globalVar = showTheValue(result);
//correct_start_date(globalVar);
}
});
}
var showTheValue = function(correct_day_value) {
console.log(new Date(correct_day_value.DATE_NEW).toLocaleDateString('de-DE'));
return correct_day_value;
};
function getGlobalVar() {
if(globalVar == null) {
window.setTimeout(getGlobalVar, 50);
} else {
return globalVar;
}
}
function correct_start_date() {
if (
document.getElementsByTagName("INPUT")[1].value = getGlobalVar();
}
This code worked for me:
function correct_date(raw_date){
return $.ajax({
method: "GET",
url: "../date/correct.php",
data: {
method: 'correct_date',
date: raw_date
},
cache: false,
dataType: 'json'
});
}
And then I can insert it wherever I want like this:
function parse_correct_day() {
.
.
.
.
var parse_correctday_value = correct_date("12.1.2016");
parse_correctday_value.success(function (data) {
var corrected_date = new Date(data.DATE_NEW);
document.getElementsByTagName("INPUT")[1].value = corrected_date.toLocaleDateString('de-DE');
});
}
Instead of calling 2 functions you should return the result from the function showTheValue and then show the response in the desired elements :
function correct_date(raw_date){
return $.ajax({
method: "GET",
url: "../date/correct.php",
data: {
method: 'correct_date',
date: raw_date
},
cache: false,
dataType: 'json',
success: function(result) {
console.log(result.DATE_NEW);
//You need to check the return value of your function and add the value accordingly
document.getElementsByTagName("INPUT")[1].value = showTheValue(result);
}
});
}
function showTheValue(correct_day_value) {
var localDate = new Date(correct_day_value.DATE_NEW).toLocaleDateString('de-DE');
console.log(localDate);
return localDate;
};

Passing into ajax success function [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
I have developed following code, I need to pass exact 'this' value ( because lot of items with this class)in to ajax success function. How to do that.
$(document).on('click', '.address_remove_link', function(e) {
var id = $(this).attr("data-id");
$.ajax({
type: 'POST',
url: 'inc/controlllers/detele_shipping_addr.php',
data: {
internalId: id
},
success: function(response, this) {
$(this).parent().closest('div').hide(200);
},
error: function(data) {
console.log("error");
}
});
});
The issue is because the scope of this changes within the success handler function. You can store the outer scope in the click handler function instead. Try this:
$(document).on('click', '.address_remove_link', function(e) {
var $link = $(this); // store reference here
var id = $link.attr("data-id");
$.ajax({
type: 'POST',
url: 'inc/controlllers/detele_shipping_addr.php',
data: {
internalId: id
},
success: function(response) {
$link.parent().closest('div').hide(200); // to use here
},
error: function(data) {
console.log("error");
}
});
});
One simple way is to use a variable the function closes over:
$(document).on('click', '.address_remove_link', function(e) {
var $this = $(this); // ***
var id = $this.attr("data-id"); // ***
$.ajax({
type: 'POST',
url: 'inc/controlllers/detele_shipping_addr.php',
data: {
internalId: id
},
success: function(response) {
$this.parent().closest('div').hide(200); // ***
},
error: function(data) {
console.log("error");
}
});
});
Alternately you could use Function#bind (MDN, spec):
$(document).on('click', '.address_remove_link', function(e) {
var id = $(this).attr("data-id");
$.ajax({
type: 'POST',
url: 'inc/controlllers/detele_shipping_addr.php',
data: {
internalId: id
},
success: function(response) {
$(this).parent().closest('div').hide(200);
}.bind(this), // ***
error: function(data) {
console.log("error");
}
});
});
You are working on the scope of the click event handler function, so you can create a self variable and use it like this:
$(document).on('click', '.address_remove_link', function(e) {
var self = $(this),
id = self.attr('data-id');
$.ajax({
type: 'POST',
url: 'inc/controlllers/detele_shipping_addr.php',
data: {
internalId: id
},
success: function(response) {
// Do something with "response"
self.parent().closest('div').hide(200);
},
error: function(data) {
console.log('error');
}
});
});

requirejs get value of returned function

I have defined a module called "checkout" which returns different functions like this:
define('checkOut',['jquery','require'],function ($,require) {
return {
getCheckout: function() {
return $.ajax({
url: '/rest/checkout/',
dataType: 'json',
type: 'GET',
success: function(res) {
if(!!res) {
checkout = res.data;
} else {
// throwCustomError
}
}
});
},
setCheckout: function() {
return $.ajax({
url: '/rest/checkout/',
data: JSON.stringify(checkout),
dataType: 'json',
type: 'PUT',
success: function(res) {
if(!!res) {
checkout = res.data;
} else {
// throwCustomError
}
}
});
}
});
If I require the module by:
require(['checkOut'], function(checkOut) {
checkOut.getCheckout();
});
...the getCheckout() function returns an object. But I need the variable "checkout", which should be an object of my response.
The point is, that I need this object in some other modules by calling somthings like:
var someVar = checkOut.checkout;
or better
define('newModule',['jquery','checkOut','require'],function ($,checkOut,require) {
return {
checkOut.checkout;
}
});

Set Delay within ajax call not working

I need a 5 seconds delay before setting success HTML to the div. I have tried below but it doesn't work. Any one has ideas?
$("#glyphicon-chevron-left-daily").click(function () {
var endDate = $("#DailyViewButtonOk1").data("date");
var previousButtonHtml = $(this).html();
$(this).html("<span class=\"glyphicon glyphicon-refresh\"></span>");
$(function () {
callAjax();
});
function callAjax() {
$.ajax({
url: loadUrl,
type: 'POST',
load: "<img src='img/load.gif' alt='loading...' />",
data: { startDate: startDate, endDate: endDate },
success: function (response) {
$("#_DailyViewResults").html(response);
$("#_DailyViewResults").show();
setTimeout(callAjax, 5000);
},
error: function () {
}
});
}
$(this).html(previousButtonHtml);
});
So the code below now works. The problem now id that the original span within button is not restored.
$("#glyphicon-chevron-left-daily").click(function () {
var endDate = $("#DailyViewButtonOk1").data("date");
var previousButtonHtml = $(this).html();
$(this).html("<span class=\"glyphicon glyphicon-refresh\"></span>");
$.ajax({
url: loadUrl,
type: 'POST',
data: { startDate: startDate, endDate: endDate },
success: function (response) {
setTimeout(function (response) {
$("#_DailyViewResults").html(response);
$("#_DailyViewResults").show();
$(this).html(previousButtonHtml);
}, 1000, response);
},
error: function () {
}
});
});
$("#glyphicon-chevron-left-daily").click(function () {
var endDate = $("#DailyViewButtonOk1").data("date");
var previousButtonHtml = $(this).html();
$(this).html("<span class=\"glyphicon glyphicon-refresh\"></span>");
var that = this;
$.ajax({
url: loadUrl,
type: 'POST',
load: "<img src='img/load.gif' alt='loading...' />",
data: { startDate: startDate, endDate: endDate },
success: function (response) {
var params = [];
params['response'] = response;
params['previousButtonHtml'] = previousButtonHtml;
params['that'] = that;
setTimeout(function(params) {
$("#_DailyViewResults").html(params['response']);
$("#_DailyViewResults").show();
$(params['that']).html(params['previousButtonHtml']);
}, 5000, params);
},
error: function () {
}
});
});
I think the case is ajax, which is executing success function, has no callAjax in it's context, therefore callAjax is exaluated to undefined.
success: function (response) {
$("#_DailyViewResults").html(response);
$("#_DailyViewResults").show();
console.log('callAjax=', callAjax);
setTimeout(callAjax, 5000);
},
You can easily check thing by logging to console value of callAjax from ajax's callback.
Solution is to preserve callAjax function within context, like that:
//in ajax call's properties object
success: (function(callAjax) { return function (response) {
$("#_DailyViewResults").html(response);
$("#_DailyViewResults").show();
setTimeout(callAjax, 5000);
}})(callAjax),
error: //...

double calls ajax using jquery

two calls:
$('#add').live('click', function() {
$('.simplebox').slideUp(200, function() {
$('html, body').animate({scrollTop:140}, 350, function() {
$('#loading-add').slideDown(300, function() {
$.ajax({
type: "POST",
url: "..",
data: getDataToPost(),
cache: false,
success: function(data){
alert(data);
$('#loading-add').delay(1000).fadeOut(200, function() {
$('#successfull-add').fadeIn(200);
});
}
});
});
});
});
})
But if i call to the ajax immediately after the live event, it calls on time (as it should be):
$('#add').live('click', function() {
$.ajax({
type: "POST",
url: "..",
data: getDataToPost(),
cache: false,
success: function(data){
alert(data);
$('#loading-add').delay(1000).fadeOut(200, function() {
$('#successfull-add').fadeIn(200);
});
}
});
})
There are any ideas why it happens? really strange..
Thank you.
Try using queue():
$('.simplebox').slideUp(200);
$('.simplebox').queue(function() {
$('body').animate({scrollTop:140}, 350);
$('body').queue(function() {
$('#loading-add').slideDown(300);
$('#loading-add').queue(function() {
//ajax call
});
});
})

Categories

Resources