Jquery ajax: pass the scope to set it - javascript

I have this class with this ajax call:
Person = function () {
this.__type = "PersonDto:#Empower.Service.Common.Dto";
this.Name = undefined;
this.Surname = undefined;
this.GetById = function (id) {
return $.ajax({
type: "POST",
url: "/Services/PersonService.svc/GetPersonById",
data: JSON.stringify(id),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
...
this = data;
...
}
});
}
};
In success of ajax call i want to set the current instance of person, but "this" is not scope correct for setting.
There is a more elegant way than using a global variable?
Thank you in advance for your help, and I apologize for my bad English

The jQuery.ajax()[docs] method gives you a context property where you can set the value of this in the callbacks.
Just do:
context: this,
...in your call, as in:
this.GetById = function (id) {
return $.ajax({
type: "POST",
context: this, // <---- context property to set "this" in the callbacks
url: "/Services/PersonService.svc/GetPersonById",
data: JSON.stringify(id),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// in here, "this" will be the same as in your "getById" method
}
});
}

You don't need a global.
Just put:
var self = this;
immediately before the return $.ajax(...) line, and then use self to reference the current instance inside the AJAX callback function.
This variable will only be in scope within the GetById() funciton.

Sure, you can put this to a variable and then use that variable in your callback
var self = this;
this.GetById = function (id) {
return $.ajax({
type: "POST",
url: "/Services/PersonService.svc/GetPersonById",
data: JSON.stringify(id),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
...
self = data;
...
}
});
}

Related

Why does inner method's inside execute last?

At following method i'm trying to get grid selected row. By the way, i use syncfusion component library.
My question when i call the grid.rowSelected, function's inside works last. So i can't pass model in ajax.
What's the reason of it ?
function editPackage() {
var editPackageModel;
var grid = document.getElementById("Grid").ej2_instances[0];
grid.rowSelected = function(args) {
console.log(args.data);*// works last*
editPackageModel = args.data;*// works last*
}
$.ajax({
type: "GET",
url: "/Package/Edit",
contentType: "application/json; charset=utf-8",
datatype: "json",
data: editPackageModel,
success: function (result) {
$('#generalModal').html(result);
},
error: function () {
alert("Dynamic content load failed.");
}
});
}
I'm not sure exactly what is the situation with "grid", i assume you have that element ready before the function is called, so try this:
var grid = document.getElementById("Grid").ej2_instances[0];//Get node reference.
grid.rowSelected = function (args) {//Setup event listener.
editPackage(args.data);//Pass the data from the event to your function
}
function editPackage(editPackageModel) {//Get the "model" and send ajax
$.ajax({
type: "GET",
url: "/Package/Edit",
contentType: "application/json; charset=utf-8",
datatype: "json",
data: editPackageModel,
success: function (result) {
$('#generalModal').html(result);
},
error: function () {
alert("Dynamic content load failed.");
}
});
}

how to create a javascript rusable class to pass parameters to ajax

im new in JS,im looking for a way to create a class or function,reusable everywhere in my code,just pass it parameters and get the result,because currently I am doing like this:
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("power","Ranking")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "regionalManager": tmpString }),
success: function (result) {
})}
I write this every time I need, and im sick of it,
function sendAjaxCustom(DataType,Type,Url,Ctype,Data){
$.ajax({
dataType: DataType,
type: Type,
url: Url,
contentType: Ctype,
data: Data,
success: function (result) {
return result;
})}
}
You can call this function in JS like
var result = sendAjaxCustom("json","POST",'#Url.Action("power","Ranking")',"application/json; charset=utf-8",JSON.stringify({ "regionalManager": tmpString }));
you will have the result in result variable.
You can create a function like this
function ajax(url, data) {
$.ajax({
dataType: "json",
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: data,
success: function (result) {
})}
}
Pass the url if it's dynamic and the object data on the second parameter.
Just create a simple function with your variables that need to change between calls and return the $.ajax result from there.
function ajaxWrapper(url, data, callback) {
return $.ajax({
dataType: 'json',
type: 'POST',
url: url,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: callback
});
}
When you want to call it:
ajaxWrapper('http://www.google.com/', { hello: 'world' }, function(result) {
console.log(result);
});
With the callback it's much more reusable, since you can use this anywhere and change what you do on completion of the function wherever you use it.
A simple solution is to return an object and pass it to the ajax and if some change is required then you can update the properties of the object before calling the ajax service
function commonAjaxParams() {
return {
dataType: "json",
type: "POST",
url: "#Url.Action("power","Ranking")",
contentType: "application/json; charset=utf-8",
//and so on that are common properties
}
}
//now in your application first call the function to get the common props
var commonParams = commonAjaxParams();
//change or add an parameter to your liking
commonParams.type = 'GET';
commonParams.success = function(){...} //if this action is need
commonPramss.error = function(){...}
//now call you ajax action
$.ajax(commonParams)
There is another way in which you may call the ajax function and you may get success, fail response return.
The benefit is you manage success or fail response independently for each ajax request.
$(document).ready(function() {
function ajaxRequest(dataType, requestMethod, dataURL, jsonData) {
return $.ajax({
dataType: dataType,
type: requestMethod,
url: dataURL,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jsonData)
});
}
var jsonData = {
"regionalManager": "jason bourne"
};
ajaxRequest(
"json",
"POST"
"#Url.Action('power','Ranking')",
jsonData)
.success((data) {
console.log("success");
}).error((err) {
console.log("error");
}).done(() {
console.log("done");
});
});

React Js Call function from a function with same component

how startserver function will call searchaws info function
startserver : function(){
var self =this;
$.ajax({
type: "POST",
url: "",enter code here
data: JSON.stringify(amazonEc2ManagerBean),
contentType: "application/json",
dataType: 'json',
success: function() {
// i want to call searchawsinfo function.
self.searchawsinfo; // i want to call searchawsinfo function.
}
});
},
searchawsinfo : function(){
// it should be called from startserver function , i guess i am missing something
},
self.searchawsinfo(); will be used instead of self.searchawsinfo;
function(){
var self = this;
$.ajax({ type: "POST", url: "",enter code here
data: JSON.stringify(amazonEc2ManagerBean),
contentType: "application/json",
dataType: 'json',
success: function() {
self.searchawsinfo(); // i want to call searchawsinfo function.
}
});
},
searchawsinfo : function(){
// it should be called from startserver function
},

What is AJAX best practice?

I am trying to learn javascript best practices and I am a bit confused. I have red that best ajax practice is:
function doSomething(arg1, arg2) {
jQuery.ajax({
var urlink = resourceURL
url: urlink,
cache: false,
data : "testData"+arg1,
type: "POST"
}).done(function(data) {
var obj = jQuery.parseJSON(data);
updateHtml1(obj);
updateHtml2(obj);
});
}
and not this way:
function getSomething(arg1, arg2) {
jQuery.ajax({
var urlink = resourceURL
url: urlink,
cache: false,
data : "testData"+arg1,
type: "POST",
success: function(data) {
var obj = jQuery.parseJSON(data);
updateHtml1(obj);
updateHtml2(obj);
}
});
}
I am asking which practice is best and why?
Either way is fine, it's just a difference in using the success callback or a promise, and in this case there is no difference. If you would want to return the result from the function doSomething then you would use the first method so that you can return the promise, as the done method then can be bound outside the function.
Both examples are overly complicated, and the var urlink = resourceURL is placed inside an object literal, so neither would actually work. You should also specify the dataType in the call, then the data will be parsed automatically.
In the first example you don't need an extra function wrapper.
function doSomething(arg1, arg2) {
jQuery.ajax({
url: resourceURL,
cache: false,
data : "testData"+arg1,
type: "POST",
dataType: "json"
}).done(function(data) {
updateHtml1(data);
updateHtml2(data);
});
}
And the second should be:
function getSomething(arg1, arg2) {
jQuery.ajax({
url: resourceURL,
cache: false,
data : "testData"+arg1,
type: "POST",
dataType: "json",
success: function(data) {
updateHtml1(data);
updateHtml2(data);
}
});
}

Functions with Variable Arguments in javascript/jQuery

I need and advice.
This is my issue, I have "N" functions.
var FirstOne = function(){
return $.ajax({
type: "POST",
url: hrefUrl,
data: JSON2.stringify(option),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function(status){
},
success: function(data){
}
});
};
var SecondOne = function(){
return $.ajax({
type: "POST",
url: hrefUrl,
data: JSON2.stringify(option2),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function(status){
},
success: function(data){
}
});
};
.............
var NOne = function(){
return $.ajax({
type: "POST",
url: hrefUrl,
data: JSON2.stringify(optionn),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function(status){
},
success: function(data){
}
});
};
all these function arr pushed in an object which is this .
var funcObject= [FirstOne(), SecondOne(), ....... NOne() ];
after I am waiting when all Ajax functions are done with and and after I am fine.
$.when.apply($, funcObject).done(function (a1, a2, ...an) {
// ..... here already doesn't matter
});
my issue is here:
function (a1, a2, ...an)
I want to have instead function arguments an object because I do not know how many function is going to be.
So i can edit function object, which is cool $.when.apply($, fucArr), problem is to use variable numbers of arguments .
PS: Maybe I can use "apply" or "call" for these arguments as well?
Can someone give me an idea here. Thanks A lot guys!!!
You can access all arguments passed to a method using the arguments keyword eg:
function () {
Console.log(arguments); //arguments is an array
}
The apply method can be used to use these arguments in another function call:
function () {
someFunction.apply(this, arguments);
}

Categories