Conditionally adding option to jQuery Ajax call - javascript

I have the following working Ajax call -
$.ajax({
url: ajaxUrl,
type: sendHttpVerb,
dataType: 'json',
processData: false,
contentType: 'application/json; charset=utf-8',
complete: function () {
setTimeout($.unblockUI, 2000);
},
success: function (response, status, xml) {
clearTimeout(delayLoadingMsg);
$.unblockUI();
callbackFunction(response);
},
error: function (jqXHR, textStatus, errorThrown) {
clearTimeout(delayLoadingMsg);
$.unblockUI();
dcfForm.ajaxErrorDisplay(jqXHR, textStatus, errorThrown)
}
});
My problem is the I conditionally want to add an option when I invoke the Ajax call. For example, adding data: sendRequest before I issue the Ajax request.
My problem I cannot find an example for the syntax on how to do this without completely duplicating the entire function.

what about a ternary operation:
$.ajax({
data: condition ? sendRequest : undefined,
... the rest
});
If that's not your taste, some people seem to forget $.ajax doesn't take a long group of paramters, but an object:
var ajax = {};
ajax.success = function (data) { ... };
ajax.type = 'GET';
if (myCondition) {
ajax.data = sendRequest;
}
$.ajax(ajax);

Related

Access post data from inside ajax error function

I have the below javascript function that takes POST data and sends post request to server using Ajax
function postData(post_data) {
console.log(post_data, "----------->");
var data = post_data;
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataTpe: "json",
success: function (data) {
debugger;
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
// Can we access the post_data inside this error function ?
},
}
);
};
So what my actual point is, because of some reason the server is sending a 500 response and so the execution point is coming to error: function (jqXHR, textStatus, errorThrown, data), here I want to access post_data to display something to the user.... So can we access the post_data inside ajax error function above?
In case someone looks for a generic way to do this, here is how i did it: In case your handler functions are defined where their scope don't allow you to access some variables, you can add them to the ajax object itself in the function beforeSend. You can then retreive it in the ajax object by using this.
$.ajax({
url:'/dummyUrl',
beforeSend: function(jqXHR, plainObject){
plainObject.originalUrl = 'myValue';
},
success: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
$('#myValue').html(this.originalUrl);
},
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output">waiting result</div>
<div id="myValue"></div>
function postData(post_data) {
console.log(post_data, "----------->");
// var data = post_data; // why ?
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataTpe: "json",
success: function (response) { // pay attention to args and vars naming as it makes the code easier to read
// use response
},
error: function (jqXHR, textStatus, errorThrown, data) {
// handle error
console.log(post_data); // and the magic happens
},
}
);
};
Above this issue you were having wrong key "dataType" i have modified it. Secondly, "post_data" is in your scope you can access it without any issue.
function postData(post_data) {
console.log(post_data, "----------->");
// var data = post_data; // why ?
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataType: "json",
success: function (response) { // pay attention to args and vars naming as it makes the code easier to read
// use response
},
error: function ( jqXHR jqXHR, textStatus, errorThrown) {
// post data is in your scope you can easily access it
console.log(post_data); // and the magic happens
},
}
);
};

ui-grid column definiton error

When I load data to Ui-grid, I have this error colDef.name or colDef.field property is required
I didn't find on the internet a solution to solve this.
This is my function to fill the grid :
$scope.ApiGet = function () {
$.ajax({
url: //an url,
async: false,
type: 'POST',
dataType: 'json',
success: function (data, textStatus, xhr) {
var token = data.access_token;
console.log(token);
$.ajax({
url: //an other url
async: false,
crossDomain: true,
type: "GET",
datatype: "json",
success: function (datas, textStatus, request) {
console.log(datas[0].previewContent);
angular.forEach(datas, function (value) {
console.log(value);
debugger;
if (value) {
$scope.rowCollection = $scope.rowCollection.concat(value.previewContent);
}
})
// console.log($scope.rowCollection);
},
error: function (jqXHR, textStatus, errorThrown) {
// $scope.addAlert(jqXHR.responseText != "" ? jqXHR.responseText : jqXHR.statusText);
}
})
And the Html
<div ng-controller="listCtrl" ng-init="ApiGet()">
<div ui-grid="{ data: rowCollection }" class="myGrid"></div>
</div>
since you are using jquery AJAX to send http requests, angular digest cycle might be stopped. so even though you assign $scope.rowCollection values, it will not bind to the html.
one thing you can do is start the digest cycle using $scope.$apply() after the http response
success: function(datas, textStatus, request) {
console.log(datas[0].previewContent);
angular.forEach(datas, function(value) {
console.log(value);
debugger;
if (value) {
$scope.rowCollection = $scope.rowCollection.concat(value.previewContent);
}
})
$scope.$apply();
},
OR
you can use $http instead of $.ajax to send http requests
I've found the solution :
define a
$scope.gridOptions {data:mydata,
columnDefs:[{field:'field1',displayName:'Field1", width:"*"},
{field:'field2',displayName:'Field2", width:"*"}]
Then in Html :
<div ng-controller="listCtrl" ng-init="ApiGet()">
<div ui-grid="gridOptions" class="myGrid"></div>
</div>

how to get the value from json object that have a similar id

im sending a ajax call that return a json like this
{"2":"/orangehrm/symfony/web/index.php/pim/viewPhoto/empNumber/1","3":"/orangehrm/symfony/web/index.php/pim/viewPhoto/empNumber/2","1":"/orangehrm/symfony/web/webres_552df88c832965.06437943/orangehrmMessengerPlugin/image/default-photo.png"}
the calling function have argument passed this is a integer
i want to get the value that correspond to given id for example 2 how to do this
is the way im using correct
function getUrl(sid){
$.ajax({
type: 'POST',
url: shortUrl + 'messenger/getImgUrls',
data: {suids: [sid]},
dataType: 'json',
async: false,
cache: true,
success: function (msg) {
conversationId = msg.sid;
},
error: function (xhr, textStatus, errorThrown) {
console.log(xhr.status);
console.log(errorThrown);
console.log(xhr.responseText);
}
});}
}
figured it out
have to use
conversationId = msg[sid];

Have JavaScript method return the result of jQuery AJAX call [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return the response from an AJAX call from a function?
function Run(someJsonObject) {
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
return true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
return false;
}
});
}
var result = Run({dummy:'dummy'});
If I'm not mistaken, the above function will not return true or false, but rather it will be undefined. I want to return the result of the AJAX call, I'd prefer to make it synchronous (I realize I'm using AJAX). How would I accomplish this?
You are backwards, let your ajax run first.
$(function () {
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
DoStuffWithResult(data.d);
return true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
return false;
}
});
});
function DoStuffWithResult(result){
//time to rock, i have my result
}
If you add the async option to your jquery call, it stops being asynchronous.
That being said, this is usually a bad idea and can probably be handled a better way. Usually, this is done by doing your ajax call first and working with your data in your success function.
If you are really adamant about doing it this way, though, this is what you want:
function Run(someJsonObject) {
var result;
$.ajax({
async: false,
type: "post",
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
result = true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
result = false;
}
});
return result;
}
var result = Run({dummy:'dummy'});
If you want to make an ajax request in jquery synchronous and have it be the return value of Run:
function Run(someJsonObject) {
var returnValue;
$.ajax({
type: "post",
async: false,
contentType: "application/json; charset=utf-8",
url: "/MyWebService",
data: JSON.stringify(someJsonObject),
dataType: "json",
success: function (data) {
var parsedJson = jQuery.parseJSON(data.d);
// Do some magic...
returnValue = true; // success!
},
error: function (jqXHR, textStatus, errorThrown) {
returnValue = false;
}
});
return returnValue;
}
I added async: false to the ajax options and used a local variable (accessible to the success and error handlers) as the return value.
You can't just return $.ajax(/* snip */) because that returns a promise object.
You can simplify
$.post('/MyWebService', JSON.stringify(someJsonObject), function(r) {
if(r.success) {
// do something (1)
} else {
// do else something (2)
}
},'json').error(function() {
alert('comunication error');
});
If you get any response like this
{ "success": true, data: "my_data" }
execute something (1)
else (2)
If not a valid json or timeout trigger .error()

jQuery: Calling a function from AJAX request

I'm trying to call a function when I get success from my ajax call, but it's not working. This is what I've tryed so far.
function dtMRPReasonCode(dt) {
var data = null;
jQuery.ajax({
type: "POST",
data: {},
url: "Index.aspx/getMRPReasonCodeReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d) {
console.log(dt);
console.log(msg.d);
buildTableBody(dt, msg.d);
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert("Error: dtMRPReasonCode");
}
});
return false;
}
function buildTableBody(dt, obj) {
dt.fnClearTable();
data = [];
$(obj).each(function(index, value) {
element = [];
element.push(value.Metric);
element.push(value.Region);
element.push(value.Plant);
element.push(value.Customer);
element.push(value.IMAC);
element.push(value.NotFilled);
element.push(value.Filled);
element.push(value.Total);
data.push(element);
});
dt.fnAddData(data);
}
Thanks in advance!
Edit #1
I used console.log in order to show you what I got from dt and msg.d (Image)
Edit #2
If I paste the commands from buildTableBody function in the success: handler instead of calling buildTableBody function in the success: handler it actually works:
function dtMRPReasonCode(dt) {
var data = null;
jQuery.ajax({
type: "POST",
data: {},
url: "Index.aspx/getMRPReasonCodeReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
dt.fnClearTable();
data = [];
$(msg.d).each(function(index, value) {
element = [];
element.push(value.Metric);
element.push(value.Region);
element.push(value.Plant);
element.push(value.Customer);
element.push(value.IMAC);
element.push(value.NotFilled);
element.push(value.Filled);
element.push(value.Total);
data.push(element);
});
dt.fnAddData(data);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("Error: dtMRPReasonCode");
}
});
return false;
}
But it makes no sense to me, since this actually should work in both ways.
Pretty sure you have a typo on your function call
buildTableBody(td, msg.d);
should be
buildTableBody(dt, msg.d);
Also what is the return type from Index.aspx/getMRPReasonCodeReport? If it is string, you've got to unescape the string before you can treat it as JSON.
Try removing contentType : "application/json utf-8" from your AJAX call. That is the type of the data sent to the server. It is likely that you want the default content type.
Unless your server-side resource was configured to accept json it likely accepts application/x-www-form-urlencoded
http://api.jquery.com/jQuery.ajax/

Categories

Resources