I have two functions that are very similar and I would like if possible to combine them. The only issue that I have is one function is accepting 2 arguments and the other one is accepting 3. Is there a way to do this or these two functions have to stay separated by design?
function getClientData(id, command) {
var formData = {
'method': command,
'id': id
};
getEntityData(formData);
}
function getLocation(id, clientid, command) {
var formData = {
'method': command,
'locationid': id,
'clientbrandid': clientid
};
getEntityData(formData);
}
Update
function getEntityData(data) {
var url = '/../admin/miscellaneous/components/global.cfc?wsdl';
var ajaxResponse = $.ajax({
url: url,
dataType: 'json',
data: data,
global: false,
async:false,
cache: false,
success: function(apiResponse){
return apiResponse;
}
}).responseJSON;
var response = ajaxResponse[0];
for (var i in response) {
if (response.hasOwnProperty(i)){
$("#edit"+i).val(response[i].trim());
}
}
}
yes you can, I prefer instead of passing each parameter you can pass a js object, and decide wich params it contains for example:
function getLocation(options) {
getEntityData(options);
}
and your call should be:
getLocation({'method': command,'id': id})
Update
or you can just avoid getLocation function and just call getEntityData
getEntityData({
'method': command,
'id': id
});
I would go with:
function getWhatever(id, command, clientId) {
var formData = { method: command };
if (typeof clientId === 'undefined') {
formData.id = id;
} else {
formData.locationid = id;
formData.clientbrandid = clientId;
}
getEntityData(formData);
}
function getLocation(id, clientid, command) {
var formData = {
'method': command,
'locationid': id
};
if (clientid) {
formData['clientbrandid'] = clientid;
}
getEntityData(formData);
}
// With
getLocation(1, 2, 'doStuff');
// Without
getLocation(1, '', 'doStuff');
Maybe a more rational order of arguments:
function getLocation(id, command, clientid) {
var formData = {
'method': command,
'locationid': id
};
if (clientid) {
formData['clientbrandid'] = clientid;
}
getEntityData(formData);
}
// With
getLocation(1, 'doStuff', 2);
// Without
getLocation(1, 'doStuff');
And if locationid and id are different:
function getLocation(id, command, clientid) {
if (clientid) {
var formData = {
'method': command,
'locationid': id,
'clientbrandid': clientid
};
} else {
var formData = {
'method': command,
'id': id,
};
}
getEntityData(formData);
}
// With
getLocation(1, 'doStuff', 2);
// Without
getLocation(1, 'doStuff');
I guess it really depends on what your arguments actually are, but this is also a solution. (Assuming that client id is an object).
function getLocation(id, command, clientid) {
var _clientId = clientid || {};
var formData = {
'method': command,
'locationid': id,
'clientbrandid': _clientid
};
getEntityData(formData);
}
Related
I have a function get_dish() which makes an AJAX-request to my back-end to retrieve a Dish-object with the requested ID.
function get_dish(id) {
let url = "/api/dishes/" + id;
let r;
$.ajax({
type: 'GET',
url: url,
async: false,
success: function(response) {
r = response;
}
});
return r;
}
The problem I had is that when get_dish() is called a lot my page would slow down because of all the HTTP-requests.
So I came up with the idea to cache the objects I request in localStorage. So when get_dish() is called, the returned Dish-object gets stored in localStorage. To achieve this I made the following caching-system:
// system to cache objects requested from API.
class ApiCache {
constructor(dishes) {
this.dishes = dishes;
}
}
// intialize ApiCache
if (localStorage.getItem("apicache") == null) {
localStorage.setItem("apicache", JSON.stringify(new ApiCache([])));
}
function apicache_add_dish(dish) {
let apicache = JSON.parse(localStorage.getItem("apicache"));
if (apicache_get_dish(dish.id) != null) {
return;
}
apicache.dishes.push(dish);
localStorage.setItem("apicache", JSON.stringify(apicache));
}
function apicache_get_dish(id) {
let apicache = JSON.parse(localStorage.getItem("apicache"));
return apicache.dishes.find(dish => dish.id == id);
}
The updated get_dish() looks like this:
function get_dish(id) {
if (apicache_get_dish(id) != null) {
return apicache_get_dish(id);
}
let url = "/api/dishes/" + id;
let r;
$.ajax({
type: 'GET',
url: url,
async: false,
success: function(response) {
r = response;
if (apicache_get_dish(id) == null) {
return apicache_add_dish(r);
}
}
});
return r;
}
This way, when the same dish is requested multiple times no HTTP-requests needs to be made, but it can just be retrieved from the cache instead. I'd but an expiration on the localStorage to belittle the chance of data inconsistency.
Is this a good idea? What are the pro's and cons? Can this be improved?
I have a button in my view that calls a jQuery Ajax function passing in parameters from my model
<input type="button" value="Run Check" onclick="runCheck('#actionItem.StepID', '#Model.Client.DatabaseConnectionString', '#Model.Client.ClientID')" />
The jQuery function
<script type="text/javascript">
function runCheck(x, y, z) {
$.ajax({
url: '#Url.Action("ProcessFeedbackHasRows", "Client")',
type: 'POST',
contentType: 'application/json;',
data: { stepId: x, databaseConnectionString: y, clientId: z },
success: function (data) {
if (data.IsValid) {
//alert('true');
var url = '#Url.Action("ViewProcessingFeedBackPartial", "Client")';
$("#processingFeedbackPartialDiv").load(url, { stepId, databaseConnectionString, clientId },
function () {
$("#confirmButton").removeAttr("style");
});
} else {
//alert('false');
var newUrl = '#Url.Action("Processing", "Client")';
window.location = newUrl;
}
}
});
};
</script>
And finally my controller action
public JsonResult ProcessFeedbackHasRows(int StepId, string DatabaseConnectionString, int ClientID)
{
bool isValid = true;
FeedbackDetails feedbackDetails = new FeedbackDetails();
feedbackDetails.Data = _clientProcessingService.GetProcessingFeedbackDetails(StepId, DatabaseConnectionString);
if (feedbackDetails.Data.Rows.Count == 0)
{
_clientProcessingService.RunProcessStepConfirmation(DatabaseConnectionString, StepId, ClientID, "No information returned, automatically proceeding to next step.");
isValid = false;
}
return Json(new { IsValid = isValid });
}
The logic in the ajax function works when I hard code specific values in the controller to represent the appropriate step, client & database but when I debug I see the two integers as 0 and the string as null.
How can I pass these values to the controller? I considered just storing them in ViewBag or ViewData but that seems clunky and not really a good practice.
Try this,
var req={ stepId: x, databaseConnectionString: y, clientId: z }
function runCheck(x, y, z) {
$.ajax({
url: '#Url.Action("ProcessFeedbackHasRows", "Client")',
type: 'POST',
contentType: 'application/json;',
data: JSON.stringify(req),
success: function (data) {
if (data.IsValid) {
//alert('true');
var url = '#Url.Action("ViewProcessingFeedBackPartial", "Client")';
$("#processingFeedbackPartialDiv").load(url, { stepId, databaseConnectionString, clientId },
function () {
$("#confirmButton").removeAttr("style");
});
} else {
//alert('false');
var newUrl = '#Url.Action("Processing", "Client")';
window.location = newUrl;
}
}
});
};
As per this question, I had to remove my contentType property and the values were passed successfully.
<script type="text/javascript">
function runCheck(x, y, z) {
$.ajax({
url: '#Url.Action("ProcessFeedbackHasRows", "Client")',
type: 'POST',
data: { stepId: x, databaseConnectionString: y, clientId: z },
success: function (result) {
if (result.IsValid) {
alert('true');
var url = '#Url.Action("ViewProcessingFeedBackPartial", "Client")';
$("#processingFeedbackPartialDiv").load(url, { stepId, databaseConnectionString, clientId },
function () {
$("#confirmButton").removeAttr("style");
});
} else {
alert('false');
var newUrl = '#Url.Action("Processing", "Client")';
window.location = newUrl;
}
}
});
};
I have web application in ASP.NET MVC C#. I want to call Controller Action method with parameters from javascript but I get always null for parameters.
In .js I have:
$.ajax({
cache: false,
url: this.saveUrl,
type: 'post',
success: this.nextStep,
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
nextStep: function (response) {
if (response.error) {
if ((typeof response.message) == 'string') {
alert(response.message);
} else {
alert(response.message.join("\n"));
}
return false;
}
if (response.redirect) {
ConfirmOrder.isSuccess = true;
location.href = response.redirect;
return;
}
if (response.success) {
ConfirmOrder.isSuccess = true;
window.location = ConfirmOrder.successUrl;
//window.location.href = #Url.Action("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" });
//window.location.href = '#Html.GetUrl("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" })';
}
Checkout.setStepResponse(response);
}
in RouteProvider.cs I have:
routes.MapLocalizedRoute("CheckoutCompleted",
"checkout/completed/{orderId}/{customerComment}/{customerDate}",
new { controller = "Checkout", action = "Completed", orderId = UrlParameter.Optional, customerComment = UrlParameter.Optional, customerDate = UrlParameter.Optional },
new { orderId = #"\d+", customerComment = #"\w+", customerDate = #"\w+" },
new[] { "Nop.Web.Controllers" });
And finaly in Controller I have:
public virtual ActionResult Completed(int? orderId, string customerComment, string customerDate)
{
//some code here
}
I always get parameters value null and I don't know why. I try to call this Action with parameters on several diferent way like I saw on this forum but no success.
Did you add httpPost wrapper to your controller ?
[HttpPost]
public virtual ActionResult Completed(MyClass MyClassObj )
{
//some code here
}
in your Ajax code u didn't mention your Data type And Data try This Ajax
function Save () {
try {
var req = {
DeliveryCode: value,
}
$.ajax({
url: URL,
type: 'POST',
data: req,
dataType: "json",
async: true,
success: function (result) {
resetLoadWaiting()
},
error: function (e) {
}
});
}
catch (e) {
}
}
Mistake was in url string. Correct one is
ConfirmOrder.successUrl = "http://localhost:8079/checkout/completed/?customerComment=eee&customerEstimateShippingDate=2017-11-14"
I found this solution in this answer: Routing with Multiple Parameters using ASP.NET MVC
I dont need to update RouteProvider with new parameters. It is enough to put in in Controller Action method. Other things happen automatically.
I have scenario that first onload page i put data into one pouchdb and with same pouchdb with other event of click it have to go server and fetch data in same pouch but it create two id ,but i need is second time it have into same pouch with first time create id how can i do this??
out put:
first time:
ressss---->:{"rows":[{"value":{"existing":[{"pattano":1843,"surveyNo":"156 ","subdivNo":"3B","ownerDetails":[{"relNo":1,"ownerNo":1,"RelationCode":"3","status":"Existing","udsRatio":"0","MaxOwnNumb":"1","relation":"மகள்","owner":"த்ஃப்க்","surveyNo":"156 ","statofown":"E","relative":"த்ஃப்க்","subDivNo":"3B"}]}],"_id":"6163ED1A-B1E8-4A90-8EEF-BF4B1A1E6132","_rev":"1-dea5c55e64c7543a26f24192ec5e94a5"}}]}
second time:
ressss---->:{"rows":[{"value":{"existing":[{"pattano":1843,"surveyNo":"156 ","subdivNo":"3B","ownerDetails":[{"relNo":1,"ownerNo":1,"RelationCode":"3","status":"Existing","udsRatio":"0","MaxOwnNumb":"1","relation":"மகள்","owner":"த்ஃப்க்","surveyNo":"156 ","statofown":"E","relative":"த்ஃப்க்","subDivNo":"3B"}]}],"_id":"6163ED1A-B1E8-4A90-8EEF-BF4B1A1E6132","_rev":"1-dea5c55e64c7543a26f24192ec5e94a5"}},{"value":{"existing":[{"pattano":457,"surveyNo":"111","subdivNo":"4","ownerDetails":[{"relNo":2,"ownerNo":1,"RelationCode":"1","status":"Existing","udsRatio":"0","MaxOwnNumb":"4","relation":"மகன்","owner":"மணிவேல்","surveyNo":"111","statofown":"E","relative":"ஆலப்பன்","subDivNo":"4"}]}],"_id":"E421B84D-2481-4ED1-ABDD-0C0B24BAEB91","_rev":"4-6713d5be5336f69b0f6c776b5c343d49"}}]}
my function is:
function fetchOwners(existingOwnersObj)
{
//alert("in fetch owners");
var inputVal = JSON.stringify(existingOwnersObj);
//alert("inputVal===> "+inputVal);
var hash1 = cal_hmac(inputVal);
var m = "";
document.getElementById('imgdiv')
.style.display = 'block';
$
.ajax(
{
url: urlService + serviceName + '/getPattaOwnersforJoint?jsoncallback=?',
headers:
{
"emp_value": ses,
"signature": hash,
"roleId": roleId,
"timestamp": t,
},
type: 'POST',
dataType: 'jsonp',
data: inputVal.toString(),
// jsonpCallback:"aaa",
contentType: "application/json",
success: function(data)
{
// alert("im in success===>"+JSON.stringify(data));
existown = {};
existown.existing = data;
//existown.slNno=slNno++;
str = JSON.stringify(existown);
//alert("str----->"+str);
var str1 = JSON.parse(str);
//new Pouch('idb://tamilNilamExist', function(err, db)
Pouch(puch, function(err, db)
{
var doc = existown;
db.put(doc, function(err, doc)
{
if (err)
{
return console.error(err);
}
else
{
//alert("Data Locally Stored Successfully adkkdd exizthhh");
$("#imgdiv")
.hide();
}
});
});
// getexist();
//
},
error: function(jqXHR, exception)
{
// alert("Error:"+JSON.stringify(jqXHR));
alert("Error Occured");
document.getElementById('imgdiv')
.style.display = 'none';
}
});
}
It looks like you are using a very old version of PouchDB. If you update to 3.4.0, you should be able to easily do something like:
// only need to instantiate the PouchDB once
var db = new PouchDB('mydb');
// inside of asynchronous functions, just call the db directly
function asyncSomething() {
function asyncSomethingElse() {
db.put(...)
}
}
I hava a common ajax.post method which accepts data from function parameter. Now i want to trim the properties of data. Below is the code.
function PostToServer(options) {
var defaults = {
'url': null,
'data': null,
'onSuccess': null,
'onError': null
};
var parameters = $.extend(defaults, options);
$.ajax({
url: parameters.url,
type: "POST",
data: JSON.stringify(parameters.data),
contentType: "application/json",
success: function (res) {
if ($.isFunction(parameters.onSuccess)) {
parameters.onSuccess(res);
}
},
error: function (xhr, status, error) {
if ($.isFunction(parameters.onError)) {
parameters.onError(xhr, status, error);
}
}
});
}
Now in this function i want to trim the 'parameters.data' object so that it removes whitespace from both ends. but i dont know what comes in 'parameters.data' so i can not access its properties and use trim function.
Please help.
Try this:
$.each(res, function(index) {
var that = this;
$.each(that, function(key, value) {
var newKey = $.trim(key);
if (typeof value === 'string')
{
that[newKey] = $.trim(value);
}
if (newKey !== key) {
delete that[key];
}
});
});