IE not calling $.ajaxSetup - javascript

The following call works great in every browser but IE. $.ajaxSetup doesn't get recognized. The error and complete functions won't be called unless I add them directly into the $.ajax call.
Any idea why?
function setupAjaxCalls() {
$.ajaxSetup({
type: 'GET',
dataType: "jsonp",
contentType: "application/json",
data: {
deviceIdentifier: deviceIdentifier,
deviceType: deviceType,
memberId: loggedInMemberId,
authToken: authToken,
cache: false,
responseFormat: 1
},
error: function (x, e) {
defaultError(x, e);
},
complete: function () {
apiCallInProgress = 'false';
//alert('complete!');
}
});
}
function logInForm(memLogin, memPassword, callback) {
apiCallInProgress = 'true';
$.ajax({
type: 'POST',
dataType: "json",
url: baseApiUrl + '/MembershipService/AuthLoginSecure',
data: {
login: memLogin,
password: memPassword,
responseFormat: 0
},
success: function (data) {
if (data.Success == false) {
apiError(data);
} else {
loggedInMemberId = data.Member.Id;
authToken = data.Token;
if (typeof (callback) != "undefined" || callback) {
callback(data);
}
}
}
});
}

Straight from the documentation:
http://api.jquery.com/jQuery.ajaxSetup/
Note: Global callback functions should be set with their respective global Ajax event
handler methods—.ajaxStart(), .ajaxStop(), .ajaxComplete(), .ajaxError(), .ajaxSuccess(),
.ajaxSend()—rather than within the options object for $.ajaxSetup().
You should move the error and complete properties into their own methods. :) Or, you can just put them into the $.ajax method. Whatever works best for your preferred code pattern!

Related

Call one ajax call after another - React on click function

I am trying to restart a service. For that I have to execute 2 API calls.
First cancel and then run.
I am trying to execute these 2 POST Ajax calls by binding the run inside the success of cancel call as a callback. But its giving me error and doesnt refresh the browser on success. When I execute only one call "run" it works fine and the page is reloaded as well.
FYI : These are POST Ajax calls.
onClickRestart(params, onSuccess, onFailure) {
var {
pipelineName,e
} = params;
const url1 = `/api/${params}/cancel`;
const url2 =`/api/${params}/run`
return $.ajax({
type: 'POST',
url1,
processData: false,
async:false,
contentType: 'application/json',
success: (response) => {
if(!response.error) {
$.ajax({
type: 'POST',
url2,
processData: false,
async:false,
contentType: 'application/json',
success: (response) => {
if(!response.error) {
location.reload(true);
}
},
error: (error) => {
console.log(error);
}
});
}
},
error: (error) => {
console.log(error);
}
});
}
What is my mistake ?

ajax jquery message show after the function completed

I think it is simple question. I've tried to search but still not found an answer yet.
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
messageBox(result.d);
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
I want to show message after success() performed.
That means the comment left already then show message.
Thanks anyway!
P/s: I read a topic about jQuery Callback Functions at https://www.w3schools.com/jquery/jquery_callback.asp.
Can we use it in here? If we can, how to use?
You can try like this
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
$.when(this).then(setTimeout(function(){ messageBox(result.d)}, 200));
// if you dont want use set timeout then use
// $.when(this).then(messageBox(result.d), 200));
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events.
Considering your implementation of var success = function() you may try with following approach:
Modify the success() to accept callback function as follows:
var success = function(callback) {
self.removeComment(commentId);
if(parentId)
self.reRenderCommentActionBar(parentId);
if(typeof callback == "function")
callback();
};
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
//passing the callback function to success function
success(function(){
messageBox(result.d);
});
}
},
error: error
});
},

Jquery Asynchronous call return undefined value

I have gone through many topics on stack overflow for jquery asynchronous AJAX requests. Here is my code.
funciton ajaxCall(path, method, params, obj, alerter) {
var resp = '';
$.ajax({
url: path,
type: method,
data: params,
async: false,
beforeSend: function() {
$('.black_overlay').show();
},
success: function(data){
console.log(data);
resp = callbackFunction(data, obj);
if(alerter==0){
if(obj==null) {
resp=data;
} else {
obj.innerHTML=data;
}
} else {
alert(data);
}
},
error : function(error) {
console.log(error);
},
complete: function() {
removeOverlay();
},
dataType: "html"
});
return resp;
}
The problem is, when I use asyn is false, then I get the proper value of resp. But beforeSend doesn't work.
In case, I put async is true, then its beforeSend works properly, but the resp value will not return properly, Its always blank.
Is there any way to solve both problems? I would get beforeSend function and resp value both.
Thanks
Use async:false and run the function you assigned to beforeSend manually before the $.ajax call:
var resp = '';
$('.black_overlay').show();
$.ajax({
...
Either that or learn how to use callback functions with asynchronous tasks. There are many nice tutorials on the web.
Take the resp variable out from the function
Create one extra function respHasChanged()
when you get the data successfully, use the code
resp = data;respHasChanged();
You can restructure on this way, (why no use it in async way?)
function ajaxCall(path, method, params) {
return $.ajax({
url: path,
type: method,
data: params,
beforeSend: function() {
$('.black_overlay').show();
},
dataType: "html"
});
}
Call in your javascript file
ajaxCall(YOUR_PATH, YOUR_METHOD, YOUR_PARAMS)
.done(function(data) {
console.log(data);
// DO WHAT YOU WANT TO DO
if (alerter == 0 && obj !== null) {
obj.innerHTML = data;
} else {
alert(data);
}
}).fail(function(error) {
console.log(error);
}).always(function() {
removeOverlay();
});

Web service receiving null with jQuery post JSON

The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}

Generic $.ajax() call function for resusability

I am creating a application where I have lot of ajax calls to a remote server and use them extensively. As the code is almost same in all calls, I want to create a new function which I can reuse. I am struck up in defining the parameter structure for the "data" parameter. I will explain below my problem.
Sample of my current ajax call is provided below.
Current Call Sample:
$.ajax({
beforeSend: function() {
$.mobile.loading('show');
},
complete: function() {
$.mobile.loading('hide');
},
type: 'GET',
url: 'http://localhost/test-url/',
crossDomain: true,
data: {appkey: '1234567', action: 'action1','name':'me'},
dataType: 'jsonp',
contentType: "application/javascript",
jsonp: 'callback',
jsonpCallback: 'mycallback',
async: false,
error: function() {
//some operations
},
success: function(data) {
//some operations
}
});
The re-usable function that I have created:
function newAjax(parm, successCallback, errorCallback) {
$.ajax({
beforeSend: function() {
$.mobile.loading('show');
},
complete: function() {
$.mobile.loading('hide');
},
type: 'GET',
url: 'http://localhost/test-url',
crossDomain: true,
data: {appkey: '1234567', parm: parm},
dataType: 'jsonp',
contentType: "application/javascript",
jsonp: 'callback',
jsonpCallback: 'mycallback',
async: false,
success: function() {
successCallback();
},
error: function() {
errorCallback();
}
});
}
Question:
I will be passing the the parameters for the ajax call via "parm" parameter. I want the data value to be directly added to the parent "data" parameter. And not as a sub-object of data. The appKey remains same across all calls and so I keep it in the actual function.
I want both the success and error callback functions to be optional. If not provided they should be ignored.
You can use the jQuery.extend method to combine two or more objects together.
data: jQuery.extend({appkey: '1234567'}, parm),
You can check that you were actually passed functions for successCallback and errorCallback using typeof var === 'function';
success: function () {
if (typeof successCallback === 'function') {
successCallback();
}
},
error: function () {
if (typeof errorCallback === 'function') {
errorCallback();
}
}
... although it might be nicer if you just returned the Promise created by the AJAX request, and let the caller add their success, error handlers if they wanted;
function newAjax(parm) {
return jQuery.ajax({
/* as before, but without success and error defined */
});
}
... then:
newAjax().done(function () {
// Handle done case
}).fail(function () {
// Handle error case.
});
If a caller doesn't want to add an error handler, they just don't call fail();
newAjax().done(function () {
// Handle done case
});

Categories

Resources