Get access to method on myclass into $.ajax() - javascript

I created two methods on a Javascript class:
this.saveData = function(){
var url_send = 'm1=1&m2=2'
$.ajax({
url: '/save.php',
dataType : "text",
data:url_send,
type:'POST',
success: function(data) {
// this is does not correct
this.showAcceptBox('error_msg_0');
}
});
};
this.showAcceptBox = function(msg_id){
$('#error_box').removeClass('alert-negative');
$('#error_box').html($('#'+msg_id).html());
$('#error_box').show();
setTimeout(function(){
$('#error_box').fadeOut('slow',function(){
$('#error_box').addClass('alert-negative');
});
},this.message_box_timeout);
};
How do I correct the call method from my class into jQuery .ajax()?

Try to capture this in a closure:
this.saveData = function() {
var url_send = { m1: 1, m2: 2 };
var _self = this;
$.ajax({
url: '/save.php',
dataType : 'text',
data: url_send,
type: 'POST',
success: function(data) {
_self.showAcceptBox('error_msg_0');
}
});
};
or pass it as parameter using the context switch:
this.saveData = function() {
var url_send = { m1: 1, m2: 2 };
$.ajax({
url: '/save.php',
dataType : 'text',
data: url_send,
context: this,
type: 'POST',
success: function(data) {
this.showAcceptBox('error_msg_0');
}
});
};
Quote from the documentation:
context
This object will be made the context of all Ajax-related callbacks. By
default, the context is an object that represents the ajax settings
used in the call ($.ajaxSettings merged with the settings passed to
$.ajax). For example specifying a DOM element as the context will make
that the context for the complete callback of a request, like so:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});

i don't see how you give your msg_id :
this.showAcceptBox = function(data){
$('#error_box').removeClass('alert-negative');
$('#error_box').html(data);
$('#error_box').show();
setTimeout(function(){
$('#error_box').fadeOut('slow',function(){
$('#error_box').addClass('alert-negative');
});
},this.message_box_timeout);
};
Or you can retrieve whatever you want in your ajax answer like $('#msg_id',data). Everything depends on what your call is returning.

Related

Pass a dynamic variable into an array

I want to add the value which I am getting from an AJAX call to an array I provide to countrySelect();
I want the cc variable in the following example to be passed in this array:
preferredCountries: ['pk','gb', 'us']
I tried this but it does not work for me.
$.ajax({
url: "https://geoip-db.com/jsonp",
jsonpCallback: "callback",
dataType: "jsonp",
success: function(location) {
var cc = location.country_code;
var ncc = cc.toLowerCase();
}
});
$("#country_selector").countrySelect({
preferredCountries: ['pk', 'gb', 'us']
});
Refactor your code to synchronize after you get the response.
var getGeoData = function (callback) {
$.ajax({
url: "https://geoip-db.com/jsonp",
jsonpCallback: "callback",
dataType: "jsonp",
success: callback
});
};
// Call the getGeoData function with callback
getGeoData(function (location) {
var cc = location.country_code;
var ncc = cc.toLowerCase();
sessionStorage.setItem('lastname', ncc);
$('#country_selector').attr('selected', true);
const countrySelectConfig = {
preferredCountries: ['pk', 'gb', 'us']
};
countrySelectConfig.preferredCountries.push(cc);
$("#country_selector").countrySelect(countrySelectConfig);
});

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
},

Span addClass not working ajax

I have a span like this <span class="join-event to-join">join event</span>.
I use this function to do something with the click via AJAX.
But in the success function I can't seem to add a class to that clicked span.
function accept() {
$(".to-join").click(function() {
var id = $(this).attr("data-event");
$.ajax({
type: "post",
url: "../assets/js/ajax/toggle-events.php",
data: { 'id': id },
success: function() {
alert("good job");
$(this).addClass("joined");
},
error: function () {
alert("fail");
}
});
});
}
Use context option of ajax method:
context: this,
context Type: PlainObject This object will be the context of all Ajax-related callbacks. By default, the context is an object that
represents the Ajax settings used in the call ($.ajaxSettings merged
with the settings passed to $.ajax).
You need to define $(this) as variable outside the ajax call, this inside ajax will refers to jqXHR object
function accept() {
$(".to-join").click(function() {
var id = $(this).attr("data-event"),
$this=$(this);
$.ajax({
type: "post",
url: "../assets/js/ajax/toggle-events.php",
data: { 'id': id },
success: function() {
alert("good job");
$this.addClass("joined");
},
error: function () {
alert("fail");
}
});
});
}
$(".to-join").click(function() {
var span = $(this);
var id = $(this).attr("data-event");
$.ajax({
type: "post",
url: "../assets/js/ajax/toggle-events.php",
data: { 'id': id },
success: function() {
alert("good job");
span.addClass("joined");
},
error: function () {
alert("fail");
}
});
});

Overriding the Jquery ajax success

Hi I have a base Model -
var BaseModel = Backbone.Model.extend({
initialize : function(input){
// Some base initialization implementation common for all Concrete Models
},
ajaxCall : function(input){
var dfd = new jQuery.Deferred();
$.ajax({
type: 'Get',
url: input.url,
success:function(data){
// Some on success implementation
dfd.resolve(data);
},
error:function(){
dfd.reject();
}
});
return dfd.promise();
}
});
Now, I want to create a ConcreteModel that extends the BaseModel's fetch function and just overrides the ajax success
var ConcreteModel = BaseModel.extend({
ajaxCall : function(input){
BaseModel.prototype.ajaxCall.call(this, input);
// How to override just the ajax success implementation
}
});
How do I just override the ajax success implementation in the ajaxCall function of ConcreteModel.
Thanks.
You can define ajax call successful callback as one of the Base Model method:
var BaseModel = Backbone.Model.extend({
initialize : function(input){
// Some base initialization implementation common for all Concrete Models
},
ajaxCall : function(input){
var dfd = new jQuery.Deferred();
$.ajax({
type: 'Get',
url: input.url,
success:this.onSuccess,
error:function(){
dfd.reject();
}
});
return dfd.promise();
},
onSuccess: function(data){
// Some on success implementation
dfd.resolve(data);
}
});
Then just override the implementation in the onSuccess function of ConcreteModel
var ConcreteModel = BaseModel.extend({
onSuccess: function(data){
alert("hello from concrete mode: "+data);
}
});
You could pass an option second parameter to ajaxCall(input, success) and then within the ajax call have:
$.ajax({
type: 'Get',
url: input.url,
success: $.isFunction(success) ? success : function(data){
// Some on success implementation
dfd.resolve(data);
},
error:function(){
dfd.reject();
}
});
Or you could store the ajax request
this.ajax = $.ajax({...});
And then overwrite it in the ConcreteModel
this.ajax.success(function(){});

Jquery ajax: pass the scope to set it

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;
...
}
});
}

Categories