How can I use callback function from ajax in another function - javascript

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

Related

Html for response when i want a string

I have the function below:
function getHtmlFromMarkdown(markdownFormat, requestUrl) {
const dataValue = { "markdownFormat": markdownFormat }
$.ajax({
type: "POST",
url: requestUrl,
data: dataValue,
contentType: "application/json: charset = utf8",
dataType: "text",
success: function (response) {
alert(response);
document.getElementById("generatedPreview").innerHTML = response;
},
fail: function () {
alert('Failed')
}
});
}
And i have this on my server:
[WebMethod]
public static string GenerateHtmlFromMarkdown(string markdownFormat)
{
string htmlFormat = "Some text";
return htmlFormat;
}
I have on response html code, not the string that i want. What am I doing wrong?
And if i change the "dataType: json" it doesn't even enter either the success nor fail functions
Your data type of ajax must be json like this
function getHtmlFromMarkdown(markdownFormat, requestUrl) {
var dataValue = { "markdownFormat": markdownFormat }
$.ajax({
type: "POST",
url: requestUrl,
data: JSON.stringify(dataValue),
dataType: "json",
success: function (response) {
alert(response);
document.getElementById("generatedPreview").innerHTML = response;
},
error: function () { alert("Failed"); }
});
}
try with this.
function getHtmlFromMarkdown(markdownFormat, requestUrl) {
var obj={};
obj.markdownFormat=markdownFormat;
$.ajax({
type: "POST",
url: requestUrl,
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
document.getElementById("generatedPreview").innerHTML = response.d;
},
failure: function () {
alert('Failed')
}
});
}

Create function inside deprecated javascript function

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

Ajax to call another Ajax function upon done

var App = {
actionRequest: function (url,data,callback){
var that = this;
$('#menu').panel('close');
$.mobile.loading('show');
$.when(
$.ajax({
method: 'POST',
url: url + '?' + new Date().getTime(),
data: data
})
).done(function(data,html) {
that.refreshCart();
$.mobile.loading('hide');
}
);
}
refreshCart: function(){
App.loadExternalContent('content','scripts/data_ajax.php','action=getCart','templates/cart.htm');
}
}
I need to call refreshCart in ".done". How can i write a callback function in ".done" to do so? Sorry i am new with Ajax.
var object = {
actionRequest: function(url, data, callback) {
$('#menu').panel('close');
$.mobile.loading('show');
$.ajax({
method: 'POST',
url: url + '?' + new Date().getTime(),
data: data
}).done(function(data, html) {
if ($.isFunction(callback)) {
callback();
}
$.mobile.loading('hide');
}
);
}
}
usage:
if refreshCart is function in the object you can also do this:
var object = {
actionRequest: function(url, data, callback) {
var that = this;
$('#menu').panel('close');
$.mobile.loading('show');
$.ajax({
method: 'POST',
url: url + '?' + new Date().getTime(),
data: data
}).done(function(data, html) {
// without using a callback
that.refreshCart();
$.mobile.loading('hide');
}
);
},
refreshCart: function() {
App.loadExternalContent('content', 'scripts/data_ajax.php', 'action=getCart', 'templates/cart.htm');
}
}
Here is an example of how to use ajax requests
$.ajax({
url: 'http://echo.jsontest.com/title/ipsum/content/blah',
method: 'GET'
})
.done(function(response) {
console.log(response);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am assuming you are referring this code in class.
actionRequest: function (url,data,callback){
var self = this; //keep reference of current instance for more info read closures in JS
$('#menu').panel('close');
$.mobile.loading('show');
$.when(
$.ajax({
method: 'POST',
url: url + '?' + new Date().getTime(),
data: data
})
).done(function(data,html) {
self.refreshCart();
$.mobile.loading('hide');
}
);
}
refreshCart: function(){
App.loadExternalContent('content','scripts/data_ajax.php','action=getCart','templates/cart.htm');
}
Ajax function:
actionRequest: function (url,data,callback){
$('#menu').panel('close');
$.mobile.loading('show');
$.when(
$.ajax({
method: 'POST',
url: url + '?' + new Date().getTime(),
data: data
})
).done(function(data,html) {
callback();
$.mobile.loading('hide');
}
);
}
call function:
actionRequest(url, data, refreshCart);

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

Passing parameters from function to its callback

Here's my code:
First the execution of the program comes here:
refreshTree(function() {
$.ajax({
type: "POST",
url: "/ControllerName/MethodName1",
success: function (data) {
refresh();
}
});
});
Here's the definition of refreshTree():
function refreshTree(callback) {
var isOk = true;
$.ajax({
type: "GET",
url: "/ControllerName/MethodName2",
success: function(data) {
if (data == 'True') {
isOk = false;
}
callback();
}
});
}
And here's the refresh() method:
function refresh() {
if (isOk) {
//do something
}
}
The problem is, I don't know how to get the isOk variable in refresh(). Is there some way to send the variable to refresh(), without it being a global variable?
You capture it in a closure here:
refreshTree(function(isOk) {
$.ajax({
type: "POST",
url: "/ControllerName/MethodName1",
success: function (data) {
refresh(isOk);
}
});
});
And pass it in here:
function refreshTree(callback) {
var isOk = true;
$.ajax({
type: "GET",
url: "/ControllerName/MethodName2",
success: function(data) {
if (data == 'True') {
isOk = false;
}
callback(isOk);
}
});
}
and here:
function refresh(isOk) {
if (isOk) {
//do something
}
}
Simply Pass it as parameter:
refreshTree(function(status) {
$.ajax({
type: "POST",
url: "/ControllerName/MethodName1",
success: function (data) {
refresh(status);
}
});
});
refreshTree() function:
function refreshTree(callback) {
var isOk = true;
$.ajax({
type: "GET",
url: "/ControllerName/MethodName2",
success: function(data) {
var isOk=true;
if (data == 'True') {
isOk = false;
}
callback(isOk);
}
});
}
Refresh() method:
function refresh(status) {
if (status) {
//do something
}
}

Categories

Resources