External method from an AJAX callback in JavaScript & jQuery - javascript

I have a function in JS & jQuery that fires an AJAX call and it has a callback block to let me know when it's finished:
function ajaxCall(url, type, dataType, dataToSend, callback) {
if (dataType == undefined) dataType = "json";
if (dataToSend == undefined) dataToSend = null;
$.ajax({
url: url,
type: type,
dataType: dataType,
contentType: "application/json",
data: dataToSend,
async: true,
success: function (result) {
callback(result);
},
error: function (data, status) {
console.error("Server Error: " + status);
}
});
}
I am accessing it like so, but using external functions like showAjaxLoader() just doesn't work! it says this function is undefined:
function registerUser(data) {
ajaxCall(pathServiceRegister, "POST", undefined, JSON.stringify(data), function (result) {
// SOME CODE THAT RUNS WHEN IT'S COMPLETE
// External method:
showAjaxLoader(false); // Doesn't work
});
});
function showAjaxLoader(show) {
var loader = $('.ajax-loader');
if (show) {
loader.fadeIn("fast");
} else {
loader.fadeOut("fast");
}
}
What am I doing wrong?
Thanks :)

Worked out some sample. this may be good practice. Try this :
$(document).ready(function() {
$("button").click(function() {registerUser();});
});
var Scallback = function(arg) {
alert("Success :"+arg);
showAjaxLoader(true);
}
var Ecallback = function(arg) {
alert("Err :"+arg);
showAjaxLoader(true);
}
function showAjaxLoader(show) {
var loader = $('.ajax-loader');
if (show) {
loader.fadeIn("fast");
} else {
loader.fadeOut("fast");
}
}
function ajaxCall(url, type, Scallback, Ecallback) {
$.ajax({
url : url,
type : type,
async : true,
success : function(result) {
Scallback(result);
},
error : function(data) {
Ecallback(data)
}
});
}
function registerUser()
{
ajaxCall(pathServiceRegister, "GET", Scallback, Ecallback);
}

Have you tried to do something like:
var that = this;
function registerUser(data) {
ajaxCall(pathServiceRegister, "POST", undefined, JSON.stringify(data), function (result) {
// SOME CODE THAT RUNS WHEN IT'S COMPLETE
// External method:
that.showAjaxLoader(false);
});
});

Declare your method like this
var obj = {
showAjaxLoader : function(show) {
var loader = $('.ajax-loader');
if (show) {
loader.fadeIn("fast");
} else {
loader.fadeOut("fast");
}
}
}
Then inside ajax, call obj.showAjaxLoader(false); This may work.

Related

How can I console "Sucess" present on $.ajax?

How can I show "success" up on Console screen? In a nutshell, I want to show on Console the erros that I forced to happen in a register formulary.
function getRoot() {
var root = "http://" + document.location.hostname + "/login_AMUBA/";
return root;
}
$("#formCadastro").on("submit", function (event) {
event.preventDefault();
var dados = $(this).serialize();
function response() {
return $.ajax({
url: getRoot() + 'controllers/controllerCadastro',
type: 'post',
dataType: 'json',
data: dados,
success: function (response) {
console.log(response);
}
});
}
if (response) {
console.log(success);<--Here
}
});
Finally, the final function (on a php file) should show the error(errors) on console screen, but only "else" works (when it is not commented)
public function validateFinalCad($arrVar)
{
if (count($this->getErro()) > 0) {
$arrResponse = [
"retorno" => "erro",
"erros" => $this->getErro()
];
} else {
/*$this->cadastro->insertCad($arrVar);*/
}
return json_encode($arrResponse);
}

How can i fix my module pattern to work

I have a module in a different file which should essentially carry out my ajax requests for me (this is in ajaxCall.js), I am trying to add this module to the global window object so that i can use it in another file called (basket-page.js), but I get an error stating
Uncaught TypeError: Cannot read property 'process' of undefined(…)
AjaxCall.js
"user strict";
window.ajaxCall = window.ajaxCall || {}
var ajaxCall = (function () {
var api = {
process: function (destinationUrl, dataToPost, callbackFunction) {
$.ajax({
url: destinationUrl,
data: dataToPost,
method: "POST",
dataType: "JSON",
success: function (data) {
if (element.length > 0) {
callbackFunction(data, element);
}
},
error: function (req, status, errorObj) {
console.log(status);
}
});
}
}
window.ajaxCall = api;
return api;
})();
basket-page.js
"use strict";
basket = basket || {};
var basket = (function (ajax) {
var api = {
init: function () {
$("#tblBasket").dataTable({
bFilter: false,
pageLength: 10,
paging: true,
autoWidth: true,
columns:
[
{ "orderDataType": "dom-text", type: "string" },
{ "orderDataType": "dom-text-numeric" },
null
],
fixedColumns: true
});
},
removeBasketProductRow: function (data, element) {
if (data === true) {
element.remove();
}
}
};
$("#btnRemoveBasketProduct").click(function() {
var product = $(this).closest("tr");
var productId = product.attr("id");
window.ajaxCall.process("/Products/RemoveBasketProduct", productId, api.removeBasketProductRow);
});
return api;
})(window);
$(document).ready(function () {
basket.init();
});
Remove all the function wrapping. It's unnecessary.
"user strict";
window.ajaxCall = {
process: function (destinationUrl, dataToPost, callbackFunction) {
$.ajax({
url: destinationUrl,
data: dataToPost,
method: "POST",
dataType: "JSON",
success: function (data) {
if (element.length > 0) {
callbackFunction(data, element);
}
},
error: function (req, status, errorObj) {
console.log(status);
}
});
}
}
The issue was making sure i had my other script file loaded already, since this is what adds object to the global window object.

Jquery $.Deferred Not Passing Parameters

I need to combine three methods:
An AJAX to check the existence of a code
If the code exists, confirm whether to overwrite
Overwrite
I've written three methods that return a $.Deferred in order to chain them together with .done(), which are below:
function checkFunction() {
var code = $("#code").val();
return $.ajax({
url: "${pageContext.request.contextPath}/dataManagement/codeMaintenance/check",
method: "POST",
async: false,
data: {
"reasonCode": code
},
success: function(response, textStatus, jqXHR) {
var exists = response.dataMap.exists;
console.log("Code exists: " + exists);
if (exists == true) {
return $.Deferred().resolve(true);
} else {
return $.Deferred().reject();
}
}, error: function() {
return $.Deferred().reject("AJAX ERROR");
}
});
};
var confirmFunction = function(codeExists) {
console.log("Confirming overwrite");
if (codeExists == true) {
var confirm = confirm("Code Exists: Do you wish to overwrite?");
if (confirm == true) {
return $.Deferred(true);
} else {
return $.Deferred(false);
}
} else {
return $.Deferred(true);
}
};
var saveFunction = function() {
console.log("Saving");
var code = $("#code").val();
return $.ajax({
url: "${pageContext.request.contextPath}/dataManagement/codeMaintenance/save",
method: "POST",
data: {
"reasonCode": code
},
success: function(response, textStatus, jqXHR) {
alert("test");
return $.Deferred(true);
}
});
};
I then attempt to execute via this line:
checkFunction().done(confirmFunction(codeExists)).done(saveFunction());
Unfortunately, the parameter I set on the $.Deferred from the first method does not get passed as a parameter to confirmFunction().
What am I doing wrong?
Jason
In short: plenty.
You try to use return inside of asynchronous functions in the success handlers of your $.ajax() calls.
Here you pass the result of the function call and not a reference of the function as callbacks:
checkFunction().done(confirmFunction(codeExists)).done(saveFunction());
This should be more like this:
checkFunction().done(confirmFunction).done(saveFunction);
In confirmFunction() you return a new Deferred object. What you should do is create a Deferred object, return the respective promise and then resolve/reject the Deferred object. So, e.g., your checkFunction() function should look like this:
function checkFunction() {
var code = $("#code").val();
// create deferred object
var result = $.Deferred();
return $.ajax({
url: "${pageContext.request.contextPath}/dataManagement/codeMaintenance/check",
method: "POST",
async: false,
data: {
"reasonCode": code
},
success: function(response, textStatus, jqXHR) {
var exists = response.dataMap.exists;
console.log("Code exists: " + exists);
if (exists == true) {
result.resolve(true);
} else {
result.reject();
}
}, error: function() {
result.reject("AJAX ERROR");
}
});
return result.promise();
}

Execute callback function inside javascript object

I want to execute a callback function inside an object. I don't know if there is something wrong in the way I'm doing this.
I've googled for a solution, also searched on stackoverflow but couldn't find anything similar to the way I'm coding this.
PHPGateway.js
var PHPGateway = {
opt_friendlyURL: true,
opt_folder: 'ajax/',
callback_function: null,
useFriendlyURL: function (bool) {
this.opt_friendlyURL = bool;
},
setFolder: function (folder) {
this.opt_folder = folder;
},
send: function (service, method, data, callback) {
var url,
json_data = {};
if (this.opt_friendlyURL) {
url = this.opt_folder + service + '/' + method;
} else {
url = this.opt_folder + 'gateway.php?c=' + service + '&m=' + method;
}
if (data != undefined) {
json_data = JSON.stringify(data);
}
this.callback_function = (callback == undefined) ? null : callback;
$.ajax({
method: 'POST',
url: url,
data: {data: json_data},
success: this.ajax_success,
error: this.ajax_error
});
},
ajax_success: function (returned_object) {
if (this.callback_function != null) {
this.callback_function(returned_object.error, returned_object.data);
}
},
ajax_error: function () {
this.callback_function.call(false, {});
}
};
Then inside the HTML file that loads PHPGateway.js, I've the following code:
<script>
function submit_handler(event) {
event.preventDefault();
form_submit();
}
function form_callback(error, data) {
if(error == null) {
alert(data.text);
}
}
function form_submit() {
var data = {
status: $('#inStatus').val(),
amount: $('#inAmount').val(),
id: $('#inBudgetID'). val()
}
PHPGateway.send('budget', 'status', data, form_callback);
}
$('form').one('submit', submit_handler);
</script>
I get an error on this.callback_function(returned_object.error, returned_object.data);, the error is Uncaught TypeError: Object # has no method 'callback_function'.
What am I doing wrong?
Is this the best way to do it?
Thank You!
Based on minitech answer, I've updated PHPGateway.js like this. I've omitted the parts that weren't updated.
var PHPGateway = {
// Omitted code
send: function (service, method, data, callback) {
var url,
json_data = {},
that = this;
if (this.opt_friendlyURL) {
url = this.opt_folder + service + '/' + method;
} else {
url = this.opt_folder + 'gateway.php?c=' + service + '&m=' + method;
}
if (data != undefined) {
json_data = JSON.stringify(data);
}
this.callback_function = (callback == undefined) ? null : callback;
$.ajax({
method: 'POST',
url: url,
data: {data: json_data},
success: function(data, textStatus, jqXHR) {
that.ajax_success(data, textStatus, jqXHR);
},
error: function(jqXHR, textStatus, errorThrown) {
that.ajax_error(jqXHR, textStatus, errorThrown);
}
});
},
ajax_success: function (data, textStatus, jqXHR) {
if (this.callback_function != null) {
this.callback_function(true, data.data);
}
},
ajax_error: function (jqXHR, textStatus, errorThrown) {
this.callback_function.call(false, {});
}
};
Now it works!!!
In your call to $.ajax, you need to add a context option:
$.ajax({
method: 'POST',
url: url,
data: {data: json_data},
context: this,
success: this.ajax_success,
error: this.ajax_error
});
Your this variable in your Ajax success and error handlers are not pointing to the object you think they are. The context option to $.ajax() sets which object this points to in the Ajax callbacks.
Here’s your problem:
$.ajax({
method: 'POST',
url: url,
data: {data: json_data},
success: this.ajax_success,
error: this.ajax_error
});
When you set success and error to methods on this, they don’t keep their this. When a JavaScript function is called, it gets bound a this:
someFunction(); // this is undefined or the global object, depending on strict
someObject.someFunction(); // this is someObject
The built-in .call, .apply, and .bind of Function objects help you override this.
In your case, I think jQuery binds this to the Ajax object – a good reason to both not use jQuery and always use strict mode.
If you can guarantee or shim ES5 support, bind is an easy fix:
$.ajax({
method: 'POST',
url: url,
data: {data: json_data},
success: this.ajax_success.bind(this),
error: this.ajax_error.bind(this)
});
Which is equivalent to this if you can’t:
var that = this;
$.ajax({
method: 'POST',
url: url,
data: {data: json_data},
success: function() {
that.ajax_success.apply(that, arguments);
},
error: function() {
that.ajax_error.apply(that, arguments);
}
});
And now, a tip for you: don’t namespace, and if you do, don’t use this. this is great for objects that are meant to be constructed. What would seem more appropriate is something like this, if you really have to:
var PHPGateway = (function() {
var callbackFunction;
var options = {
friendlyURL: true,
…
};
…
function send(service, method, data, callback) {
…
}
…
return { send: send };
})();

JavaScript functions not defined?

For some reason, Firefox is throwing "function not defined" errors at this piece of JS:
$(function() { // on document ready
function updateAlerts() {
$.ajax({
url : "/check.php",
type : "POST",
data : {
method : 'checkAlerts'
},
success : function(data, textStatus, XMLHttpRequest) {
var response = $.parseJSON(data);
// Update the DOM to show the new alerts!
if (response.friendRequests > 0) {
// update the number in the DOM and make sure it is visible...
$('#notifications').show().text(response.friendRequests);
}
else {
// Hide the number, since there are no pending friend requests or messages
var ablanknum = '0';
$('#notifications').show().text(ablanknum);
}
}
});
}
function friendRequestAlert() {
$.ajax({
url : "/check.php",
type : "POST",
data : {
method : 'sendFriendAlert'
},
success : function(data, textStatus, XMLHttpRequest) {
var response = $.parseJSON(data);
if (response.theFRAlert !== '0') {
// Display our fancy Javascript notification.
$.jgrowl('' + response.theFRAlert + '');
}
}
});
}
function messageAlert() {
$.ajax({
url : "/check.php",
type : "POST",
data : {
method : 'sendMessageAlert'
},
success : function(data, textStatus, XMLHttpRequest) {
var response = $.parseJSON(data);
if (response.theAlert !== '0') {
// Display our fancy Javascript notification.
$.jgrowl('' + response.theAlert + '');
$('#therearemessages').show().text(response.theAlert);
}
}
});
}
});
I checked through my code and nothing seems to be wrong.
There is no reason to wrap your 3 functions in the document ready wrapper--nothing inside those functions (which may rely on the doc being ready) is executed until they are called. Further, by wrapping them in doc ready, you're forcing them into the scope of that anon function and they cannot be used from outside of it.
Unrelated, you should set your dataType to 'json' on the $.ajax calls and stop making manual calls to $.parseJSON.
New code:
function updateAlerts()
{
$.ajax( {
url: '/check.php',
type: 'POST',
data: {
method: 'checkAlerts'
},
dataType: 'json',
success: function( response )
{
// Update the DOM to show the new alerts!
if( response.friendRequests > 0 )
{
// update the number in the DOM and make sure it is visible...
$( '#notifications' ).show().text( response.friendRequests );
}
else
{
// Hide the number, since there are no pending friend requests or messages
var ablanknum = '0';
$( '#notifications' ).show().text( ablanknum );
}
}
} );
}
function friendRequestAlert()
{
$.ajax( {
url: '/check.php',
type: 'POST',
data: {
method: 'sendFriendAlert'
},
dataType: 'json',
success: function( response )
{
if( response.theFRAlert !== '0' )
{
// Display our fancy Javascript notification.
$.jgrowl('' + response.theFRAlert + '');
}
}
} );
}
function messageAlert()
{
$.ajax( {
url: '/check.php',
type : 'POST',
data: {
method : 'sendMessageAlert'
},
dataType: 'json',
success: function( response )
{
if( response.theAlert !== '0' )
{
// Display our fancy Javascript notification.
$.jgrowl('' + response.theAlert + '');
$('#therearemessages').show().text(response.theAlert);
}
}
} );
}
Scope in javascript is function based.
Since you define the 3 functions inside a function that is run on DOMready and then goes out of scope, so does the funcitons.
In other words: the 3 functions only exist inside the DOmready function, and you cannot use them from anywhere else outside that function.

Categories

Resources