Passing parameters from function to its callback - javascript

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

Related

Return Value From AJAX Outside AJAX Call

I want the html value of AJAX in outside of AJAX Call or in the $('#username').blur(function() function.. Is this possible ?
<script>
$(document).ready(function() {
$('#username').blur(function() {
var username = $(this).val();
availibilityCheck(username);
})
function availibilityCheck(username) {
var result = "";
$.ajax({
url: "action.php",
method: "POST",
data: {
action: "availibilityCheck",
data: username
},
dataType: "text",
success: function(html) {
$('#usernameresponse').html(html);
}
})
}
});
</script>
<script>
$(document).ready(function() {
$('#username').blur(function() {
var username = $(this).val();
availibilityCheck(username);
var return_first;
function callback(response) {
return_first = response;
//use return_first variable here
}
})
function availibilityCheck(username) {
var result = "";
$.ajax({
url: "action.php",
method: "POST",
data: {
action: "availibilityCheck",
data: username
},
dataType: "text",
success: function(html) {
callback(html);
$('#usernameresponse').html(html);
}
})
}
});
</script>

AJAX live keyup messed up search

This particular code performs a live AJAX search of the student names. It works on the keyup function.
This script is performing AJAX while I press the Backspace key and loading the search.php file.
I don't want this function to work on any keys but only alphabet.
$(document).ready(function() {
load_data();
function load_data(query) {
$.ajax({
url: "search.php",
method: "POST",
data: {
query: query
},
success: function(data) {
$('#result').html(data);
}
});
}
$('#search_text').keyup(function() {
var search = $(this).val();
if (search != '') {
load_data(search);
} else {
load_data();
}
});
});
This is all I learned so far so if there's any other method to do this it will be helpful. Thank You.
Give this a try:
$(document).ready(function() {
load_data();
function load_data(query) {
$.ajax({
url: "search.php",
method: "POST",
data: {
query: query
},
success: function(data) {
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(ev) {
var searchString = $(this).val();
if (searchString != '') {
var letters = /^[A-Za-z]+$/;
if (searchString.match(letters)) {
load_data(searchString);
} else {
load_data();
}
}
});
});
-- Edit -- per your comment, the below code will return a sliced value; removing the last or invalid character from our search.
$(document).ready(function() {
load_data();
function load_data(query) {
$.ajax({
url: "search.php",
method: "POST",
data: {
query: query
},
success: function(data) {
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(ev) {
var searchString = $(this).val();
if (searchString != '') {
var letters = /^[A-Za-z]+$/;
if (searchString.match(letters)) {
load_data(searchString);
} else {
searchString = searchString.substring(0, searchString.length - 1);
$('#search_text').val(searchString);
}
}
});
});
-- Edit (3rd request) the below code will clear your result div is the last keyup has determined that the search input box is empty (contains no value).
$(document).ready(function() {
load_data();
function load_data(query) {
$.ajax({
url: "search.php",
method: "POST",
data: {
query: query
},
success: function(data) {
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(ev) {
var searchString = $(this).val();
if (searchString != '') {
var letters = /^[A-Za-z]+$/;
if (searchString.match(letters)) {
load_data(searchString);
} else {
searchString = searchString.substring(0, searchString.length - 1);
$('#search_text').val(searchString);
}
} else {
$('#result').html('');
}
});
});

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

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

Controller can give either json or html

The question is that the controller can give json or html piece. How to know what is it?
$(document).on("submit", "form.client-form", function () {
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function (result) {
if (result is json) {
...
} else if (result is html) {
$("#result").html(result);
}
}
});
});
Another solution...found here: jquery how to check response type for ajax call
$(document).on("form.client-form", "submit", function () {
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function(result, status, xhr){
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
//html here
$("#result").html(result);
}
if (ct.indexOf('json') > -1) {
//json here
}
}
});
});
How about using converters? Take a look at Using Converters on jquery ajax api: http://api.jquery.com/jQuery.ajax/
$(document).on("form.client-form", "submit", function () {
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function (result) {
try {
var response = $.parseJSON(result);
}
catch (ex){
//something else
$("#result").html(result);
}
}
});
});

Categories

Resources