How can i fix my module pattern to work - javascript

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.

Related

Only one alert for multiple execution in Ajax

I am working rails application.i need to get status of the each selected device.I am able to achieve this but after executing i am putting alert "Successfully created execution record".For every mac selection it is showing alert message.I need to give one alert in end of execution.I am calling display_result in call_endpoint method.Since it is an Ajax call,it is giving alert for every execution.i don't how to limit to single alert for this.
function display_result() {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
alert('Successfully created execution record");
}
});
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 0; i < m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result();
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
Below is changed code..
Copy below code as it is.
function display_result(total,current) {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
if(total == current)
{
alert('Successfully created execution record");
}
}
});
}
}
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 1; i <= m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result(m,i);
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
}
result and mac is not defined in display_result function. result appears intended to be the resulting value of jQuery promise object returned from $.ajax(). Am not certain what mac is indented to be.
You can substitute $.when() and $.map() for for loop, return a jQuery promise object from call_endpoint(), include error handling, chain .then() to call_endpoint() call to execute alert() once.
function call_endpoint() {
return $.when.apply($, $.map(values, function(macAdd) {
return $.ajax().then(display_result)
}))
}
callEnpoint()
.then(function() {
alert('Successfully created execution record');
}, function(jqxhr, textStatus, errorThrown) {
console.error(errorThrown)
});
function display_result(reuslt) {
..
if (if (result["response"].status == "200")) {
return $.ajax() // remove `alert()` from `success`
}
return;
}

External method from an AJAX callback in JavaScript & jQuery

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.

Uncaught ReferenceError: _ is not defined at causesDataService.js:56 at causesDataService.js:64

A little background. I created an ASP.MVC web app using SQL database for users and "causes" which can be added to the web app. the following faults are coming up. I will faults and code.
Uncaught ReferenceError: _ is not defined
at causesDataService.js:56
at causesDataService.js:64
Uncaught ReferenceError: _ is not defined
at _mixins.js:2
at _mixins.js:7
Uncaught SyntaxError: Unexpected token )
Ok so now below code.....:::
MIXINS
var _mixIns = (function () {
_.mixin({
numberWithCommas: function (value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
});
}());
Cases Data Service::
var httpVerbs = {
POST:'POST',
PUT: 'PUT',
GET: 'GET',
DEL: 'DELETE'
};
var causesDataService = (function () {
var ds = {
commit: function (type, url, data) {
// Remove 'id' member to perpare for INSERT
if (type === httpVerbs.POST) {
delete data['id'];
}
return $.ajax({
type: type,
url: url,
data: data,
dataType: 'json'
});
},
del: function (data) {
return this.commit(httpVerbs.DEL, '/api/causes/' + data.id);
},
save: function (data) {
var
type = httpVerbs.POST,
url = '/api/causes';
if (data.id > 0) {
type = httpVerbs.PUT;
url += '/' + data.id;
}
return this.commit(type, url, data);
},
saveImage: function (data) {
return $.ajax({
type: httpVerbs.POST,
url: '/causes/uploadimage',
processData: false,
contentType: false,
data: data
});
},
};
_.bindAll(ds, 'del', 'save');
return {
save: ds.save,
saveLocal: ds.saveLocal,
saveImage: ds.saveImage,
}
})();

Getting a 500 internal server error thanks to some javascript in symfony

This is the code:
Controller:
public function isreadAction(Request $request) {
var_dump($request->get('sentValue'));
$em = $this->getDoctrine()->getEntityManager();
$pm = $this->getDoctrine()
->getRepository('LoginLoginBundle:Privatemessage')
->findBypmid($request->get('sentValue'));
$pm->setIsRead(true);
$em->flush();
return new Response();
}
js:
$(document).ready(function () {
$(".pmcontents").hide();
$(".pmbox").click(function () {
$(this).css("font-weight", "normal");
$(this).next().toggle();
var myValue = $('this').attr('id');
var DATA = 'sentValue=' + myValue;
$.ajax({
type: "POST",
url: Routing.generate('isread'),
data: DATA,
cache: false,
success: function (data) {
alert("database has been updated");
}
});
});
});
Routing:
isread:
path: /game/isread
defaults: { _controller: LoginLoginBundle:Default:isread }
requirements:
options:
expose: true
If i click on the error it says that the variable is undefined:
Parametersapplication/x-www-form-urlencodedNiet sorteren
sentValue undefined
Bron
sentValue=undefined
What is the problem? I have tried some things and it seems that the problem lies within the ajax part of the javascript, but i'm not sure.
Replace
var myValue = $('this').attr('id'); //<- notice quote around this
with
var myValue = $(this).attr('id');

Javascript Outerhtml error in IE

I have a script for show and hide some html content.my code like this
$(".head-text").live('click', function (event) {
var header = $(this);
var listid = header.find('strong').attr("data-id");
var list = "#" + listid;
var ajaxManager = $.manageAjax.create('cacheQueue', {
queue: true,
cacheResponse: false
});
if ($(list).length == 0) {
$("#ajax-loading-01").show();
ajaxManager.add({
type: 'GET', url: '/ajaxhandler', data: { showlist: "1", listid: listid }
, success: function (data) {
header.parent().append($(data).find(list)[0].outerHTML);
header.parent()._removeClass('show').addClass('hide');
}
, complete: function () {
$("#ajax-loading-01").hide();
}
, error: function (err) {
}
});
return false;
}
});
It is nice working in chrome and mozilla, but the outerHTML is not working in IE - header.parent().append($(data).find(list)[0].outerHTML)). How can I resolve this problem?

Categories

Resources