Use an objects method as the call back to an AJAX call - javascript

I have a javascript Object called Company, which may be instantiated multiple times.
I want each Company to handle its own communication with the server, so that its ajax calls will be contained within the class.
So far I have:
Company = new Object();
Company.SendData = function(){
$.ajax({
type: "POST",
url: "<some url>",
data: <some data>,
dataType: "json",
success: this.ReceiveData,
error: ErrorFunc
});
}
Company.ReceiveData = function(data){
alert("Received some data");
}
The Ajax works fine, and the server correctly receives the data and returns the response, but the call back function does not trigger.
My guess would be because it no longer has any frame of reference to what "this" is.
Is there a way that I can keep the functions attached to an individual instance of the class?

There are several different choices for how to solve this issue. The crux of the problem is that you need to get the value of this set properly when your callback is called as it won't be correct by default.
In modern browsers, you can use the broadly useful .bind():
Company = new Object();
Company.SendData = function(){
$.ajax({
type: "POST",
url: "<some url>",
data: <some data>,
dataType: "json",
success: this.ReceiveData.bind(this),
error: ErrorFunc
});
}
Company.ReceiveData = function(data){
alert("Received some data");
}
Or, you can instruct jQuery to do the work for you with the context option to $.ajax():
Company = new Object();
Company.SendData = function(){
$.ajax({
type: "POST",
url: "<some url>",
data: <some data>,
dataType: "json",
context: this,
success: this.ReceiveData,
error: ErrorFunc
});
}
Company.ReceiveData = function(data){
alert("Received some data");
}
Or you can create your own stub function using a saved value of this (this is my least favorite option):
Company = new Object();
Company.SendData = function(){
var self = this;
$.ajax({
type: "POST",
url: "<some url>",
data: <some data>,
dataType: "json",
success: function(result) {return self.ReceiveData(result);},
error: ErrorFunc
});
}
Company.ReceiveData = function(data){
alert("Received some data");
}

Try this:
Company.SendData = function(){
var self = this;
$.ajax({
type: "POST",
url: "<some url>",
data: <some data>,
dataType: "json",
success: function(res) {self.ReceiveData(res);},
error: ErrorFunc
});
}
This SO post might help to understand.
Update
Fixed the example by encapsulating the function.

Related

Cant get value from ajax request to be save in variable outside the success

Once again I've been beating my head against the wall, trying to pull this part of returned data from ajax to a variable outside the function.
When I return the value it always comes up undefined when I alert() inside it shows the proper values.
function getItemInfo(itemHashPass) {
$.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
success: function(data){
return data.Response.data.inventoryItem.itemName;
}
});
}
I've also tried
function getItemInfo(itemHashPass) {
var tmp = null;
$.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
success: function(data){
tmp = data.Response.data.inventoryItem.itemName;
}
});
return tmp;
}
Like Jonathan said you should write your business logic in the callback or you can try Deferred syntax. In this case it will looks like
function yourBusinnesLogicFunction() {
...
getItemInfo("password_hash_value").done(
function(data){
alert(data.Response.data.inventoryItem.itemName);
}
)
}
function getItemInfo(itemHashPass) {
var tmp = null;
return $.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
})
}

Display page only if ajax call succeeds?

I have a subdomain protected by a service similar to cloudflare. It checks if a visitor is human or not. To save bandwidth usage I want only one file to be loaded from this subdomain as indicator if the visitor is a bot or not. If it is not loaded, the service has blocked it as bot, and nothing should be shown.
I already thought of an ajax request before the page loads to check this.
var success = 0;
function myCall() {
var request = $.ajax({
url: "sub.example.com/hello.php",
type: "GET",
dataType: "html"
});
request.done(function() {
// Load page, because the request was successfull
$.ajax({
url: 'content.php', //This is the current file
type: "POST",
dataType:'json', // add json datatype to get json
data: ({load: true}),
success: function(data){
console.log(data);
}
})
});
Is there a better way to do this?
You may try this:
var success = 0;
function myCall() {
var request = $.ajax({
url: "sub.example.com/hello.php",
type: "GET",
dataType: "html",
success: function(){
$.ajax({
url: 'content.php', //This is the current file
type: "POST",
data: dat,
success: function(data){
console.log(data);
},
error: function(data){
console.log('Error!');
}
});
},
error: function(data){
console.log('Error!');
}
});
}

Send data from a javascript ajax function to a jsp

This is what I am trying to do. On a home page.. say /home.jsp, a user clicks on a link. I read value of the link and on the basis of which I call a RESTful resource which in turn manipulates database and returns a response. Interaction with REST as expected happens with use of JavaScript. I have been able to get information from REST resource but now I want to send that data to another JSP.. say /info.jsp. I am unable to do this.
I was trying to make another ajax call within success function of parent Ajax call but nothing is happening. For example:
function dealInfo(aparameter){
var requestData = {
"dataType": "json",
"type" : "GET",
"url" : REST resource URL+aparameter,
};
var request = $.ajax(requestData);
request.success(function(data){
alert(something from data); //this is a success
//I cannot get into the below AJAX call
$.ajax({
"type": "post",
"url": "info.jsp"
success: function(data){
alert("here");
("#someDiv").html(data[0].deviceModel);
}
});
How do I go about achieving this? Should I use some other approach rather than two Ajax calls? Any help is appreciated. Thank You.
You can use the following function:
function dealInfo(aparameter) {
$.ajax({
url: 'thePage.jsp',
type: "GET",
cache: false,
dataType: 'json',
data: {'aparameter': aparameter},
success: function (data) {
alert(data); //or you can use console.log(data);
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': data},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
});
}
Or make the AJAX call synchronous:
function dealInfo(aparameter) {
var request = $.ajax({
async: false, //It's very important
cache: false,
url: 'thePage.jsp',
type: "GET",
dataType: 'json',
data: {'aparameter': aparameter}
}).responseText;
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': request},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
In this way I'm using.
"type": "post" instead of type: 'post'
Maybe it will help. Try it please. For Example;
$.ajax({
url: "yourURL",
type: 'GET',
data: form_data,
success: function (data) {
...
}
});

jQuery placing .each() functions inside a .click() function

The .each() functions inside the .click() are not running. I do not know how to structure them to make it syntactically correct so jQuery will recognize and run them.
I tried tacking them on before the closing }); but I either didn't do it right or that isn't how it's done. I tried Googling but other than my topic title I was at a loss for what to search. I did try jquery function inside function but that turned out to be a lost cause.
EDIT: I have managed to get the first one to fire properly (//POST specials) however, the second one still isn't working. I even tried to put the extras POST inside the .ajax() of the specials and it didn't work.
$('.class').find('#button').click(function() {
//all kinds of variables here
var dataString = {//variables:variables}
console.log(dataString);
$.ajax({
type: "POST",
url: "classes/reserve.php",
data: dataString,
cache: false,
success: function(html)
{
//POST specials
$('#specialscheck input:checked').each(function() {
var reservation = $('#reservation').val();
var special = parseInt($(this).attr('id'));
dataString = {reservation:reservation, special:special};
console.log(dataString);
$.ajax({
type: "POST",
url: "classes/insert_specials.php",
data: dataString,
cache: false,
success: function(html)
{
//$('.unitinfolist').html(html);
}
});
});
//POST extras
$('#extrascheck input:checked').each(function() {
var reservation = $('#reservation').val();
var extra = parseInt($(this).attr('id'));
dataString = {reservation:reservation, extra:extra};
console.log(dataString);
$.ajax({
type: "POST",
url: "classes/insert_extras.php",
data: dataString,
cache: false,
success: function(html)
{
//$('.unitinfolist').html(html);
}
});
});
}
});
});
You should move the .each up into the success function of the jquery post, or set its async: false, to follow this pattern.
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType,
async:false
});

Accessing Ajax Response Data

I have this code that works well:
{"livre":"empty_name"}
$.ajax({
url: "sent.php",
type: "post",
dataType: "json",
data: formdata,
success: function (data) {
switch (data.livre) {
case 'empty_name':
break;
}
});
but when i try this code (i need the id), the case "empty name" didn't works. The option selected will be the default case:
{"id":"","livre":"empty_name"}
$.ajax({
url: "sent.php",
type: "post",
dataType: "json",
data: formdata,
success: function (id, data) {
switch (data.livre) {
case 'empty_name':
break;
}
});
Why? and how can be solved? thanks
If I understand correctly with the object up top being the JSON response, I think you want this...
{"id":"","livre":"empty_name"}
$.ajax({
url: "sent.php",
type: "post",
dataType: "json",
data: formdata,
success: function (data) {
var jsonId = data.id;
}
});
The data parameter of the success callback contains your response (in this case, JSON data). You access your JSON content there.
You just need to understand how the data is being returned. In this case data is the object containing all the fields. Your success callback would continue to look like success: function(data) the code you need to change is in the method block itself.
$.ajax({
url: "sent.php",
type: "post",
dataType: "json",
data: formdata,
success: function (data) {
var id = data.id; //ID lives in data.
switch (data.livre) {
}
});
Since you redefined the function, the switch will fail because in the example posted livre will reside in the id object and not in the data object.

Categories

Resources