Problem when calling object's method from ajax.success in jQuery - javascript

function modifyDatabase(tabla, id, objData, callback, arrayCallback){
$.ajax({
url: 'modifyDatabase.php',
type: "POST",
dataType: "json",
data: 'tabla='+tabla+'&id='+id+strData,
success: function(data){
callback(data);
},
});
}
var obj = {
set: function (data){
alert(this.var1);
},
var1: 100
}
function modifyDatabase('', '', '', obj.set, '');
When running this, I get an error message telling me that this.var1 is not set or undefined. If I call the method from somewhere else (not from an asynchronic response) it works fine.
Seems as if the method 'set' is not inside 'obj'.
What is going on?

When you pass a reference to a function this way, it's actually not passing a reference to the object as well. A quick fix is to create an anonymous function that references the actual object via closures. Here's a good description of why it didn't work: http://bitstructures.com/2007/11/javascript-method-callbacks
In short, you need to do:
function modifyDatabase('', '', '', function(){obj.set();}, '');

Related

Creating a reusable function for deleting/confirming using callbacks

i'm not sure if this question has been asked before, i did check but i'm not sure how to actually search for it tbh.
I want to create a reusable function for deleting, confirming based on user decision. I created this simple function to edit element data with object values but i'm not able to run the callback that was set in the first function.
Or maybe it's even possible to somehow return a bool from that function based on user's decision?
Here's the logical example of what i want to achieve
function run(options, cb){
if(options['success']){
cb();
}
}
var options = {success: true};
var cbarray = new Array('id', 'token');
//calling the function and setting the callback
run(options, function(cbarray){
$.ajax({
url: 'blabla',
type: 'post',
data: {id: cbarray[0], token: cbarray[1]},
success: function(resp){
console.log(resp);
}, error: function(resp){
console.log(resp);
}
});
});
It's kinda hard to explain so i created this jsfiddle with my own code
https://jsfiddle.net/43zrqkvm/7/
Maybe i should actually use promises for that? I haven't yet had time to learn promises but maybe i should?
when you defining callback function you'r requesting argument that will be used in function body (in you'r case in ajax options) but in Run function you do not passing it
it must look like this
function run(options,arg, cb){
if(options['success']){
cb(arg);
}
}
var options = {success: true};
var cbarray = new Array('id', 'token');
//calling the function and setting the callback
run(options,cbarray, function(arg){
$.ajax({
url: 'blabla',
type: 'post',
data: {id: arg[0], token: arg[1]},
success: function(resp){
console.log(resp);
}, error: function(resp){
console.log(resp);
}
});
});

AJAX Call that Returns Javascript Variable

Struggling to return a AJAX Result Variable back to JavaScript
Note that the $.ajax call below is synchronous (async: false).
Ajax Call
function getState(callback) {
$.ajax({
url: 'getSearchState.php',
data: { "state": callback },
type: 'GET',
async: false,
success: function(result){
alert(result);
},
error: function(result) {
alert(result);
}
});
}
Ajax PHP
<?php
// Database Setup and Query
while ($row = $xxxxx->fetch(PDO::FETCH_ASSOC)) {
$StateVal = $row['State'];
}
return $StateVal;
?>
Javascript Calling the Function
var URL = District.trim();
var StateURL = getState(URL);
It gets the URL vairable from the function just fine, but doesnt return anything.
Any help would be great!
There are problems with that code both client-side and server-side.
Client-side:
Your getState is never returning anything, so it's no surprise that you don't see anything other than undefined for StateURL.
Don't use synchronous ajax. It makes for horrible UX. But if you really, really want to keep using it, here's how you would:
function getState(state) {
var result; // <=== Where we'll put our result
$.ajax({
url: 'getSearchState.php',
data: {"state": state},
type: 'GET',
async: false,
success: function(data) {
// Remember the result;
result = data;
},
error: function() {
result = /*...whatever you want to use to signal an error */;
}
});
// Return the result
return result;
}
Note that I changed the name of the argument to state, since it's not a callback.
But again, don't use synchronous ajax. Instead, use a callback or promises.
Promise: $.ajax already returns a promise, so just return that directly:
function getState(state) {
var result; // <=== Where we'll put our result
$.ajax({
url: 'getSearchState.php',
data: {"state": state},
type: 'GET',
async: false,
success: function(data) {
// Remember the result;
result = data;
},
error: function() {
result = /*...whatever you want to use to signal an error */;
}
});
// Return the result
return result;
}
Note that I changed the name of the argument to state, since it's not a callback.
But again, don't use synchronous ajax. Instead, use a callback or promises.
Promise:
function getState(state) {
return $.ajax({
url: 'getSearchState.php',
data: {"state": state},
type: 'GET'
});
}
Usage:
getState(URL)
.done(function(StateURL) {
// Use it
})
.fail(function() {
// Failed
});
Callback:
function getState(state, callback) {
$.ajax({
url: 'getSearchState.php',
data: {"state": state},
type: 'GET',
success: function(data) {
// Call the callbback with the result
callback(data);
},
error: function() {
// Call the callback with an error
callback(/*...whatever you want to use tosignal an error */);
}
});
}
Usage:
getState(URL, function(StateURL) {
// Use it, check for error
});
Server-side:
As RiggsFolly pointed out, you're returning a string from your PHP code. But that won't output it. To use it client-side, you need to output it (e.g., echo and similar). And to make it easily consumed by the JavaScript, you probably want to json_encode it to ensure that it's in a format JavaScript can understand:
echo json_encode($stateVal);
Then in your success (or done) function, use JSON.parse on it:
result = JSON.parse(data);
this is jQuery and in this case you can specify context and in success function set variables on that context.... a bit crude solution but it will works. Also take a look on arrow functions and promises from ES6, it can help you a lot and give you new perspective about whole problem.
And one main thing!! Ajax is async by default so you need somehow notify your StateURL when data will be ready (here again promise at you service)

Remake ajax function

Is there a way to make a function that converts default ajax function.
This is the ajax function i have
$.ajax({
type: "POST",
url: "http://" + document.location.host + '/userajax',
data: 'type=register&name=' + name,
beforeSend:function() {
},
success: function(response) {
}
});
This is what i want it to look like
ajax('url', {
method: 'get',
parameters: {
name: $('#name').val()
},
beforeSend: function() {
},
success: function(transport) {
}
});
Ive tried to search on the internet but did not find anything
Sure, you can create the function like this:
function ajax(url, params){
// everything is now available here
console.log( url ); // output: http://www.google.com
// you can get the data of the params object like this
console.log( params.method ); // output: get
// you can execute the beforeSend like this:
params.beforeSend();
// additionally you might want to check everything.
// maybe if the method is NOT set, you want it to always use GET
switch(arguments.length) {
case 1: url = throw new Error('Url should be set');
case 2: params.method = 'get';
case 3: break;
default: throw new Error('illegal argument count')
}
}
You would call this like:
ajax('http://www.google.com', {
method: 'get',
parameters: {
name: $('#name').val()
},
beforeSend: function() {
// some function
},
success: function(transport) {
// some function
}
});
This certainly is possible, it's just a bit of work. Some of the basics you need:
First of all, you need a good understanding of the XMLHTTPRequest API, you can find more info on that on MDN.
Next, finding out how to do a callback, that is actually quite simple, you can pass an anonymous function reference as an option or attribute for a function. That goes like this:
function doSomething(variable, callback){
variable = variable + ' something'; // just doing something with the variable
callback(variable);
}
// then call the function with a callback (anonymous function)
doSomething('doing', function(result){ alert(result); });
You should get an alert that says 'doing something'.
And finally you should know how to read an object, passed as 'options' in the ajax function. Say you have a function like this:
function foo(url, options){
console.log(url);
console.log(options.method);
console.log(options.parameters.name);
}
// call it like this
foo('https://google.com/', {
method: 'get',
parameters: {
name: 'myName'
}
});
That should log the url, method and parameters in the console.
Now from here, you should have all the pieces to put the puzzle together. Good luck!
I don't think so. but you can do this:
$(document).ready(function(){
var parameters = {
name: $("#name").val(),
desc: $("#desc").val()
};
$.ajax({
url: 'path/to/file',
data : parameters,
beforeSend: beforeSubmit,
dataType: "json",
type : 'POST',
})
.done(function(data) {
})
.fail(function() {
console.log("error");
})
})
Also note I don't set the function for the beforeSend directly in the call, I will create an externe function which gives me more freedom.
so I could do this:
function beforeSubmit(){
if(something !== 'somethingelse'){
return false; //ajax call will stop
}else{
return true; //ajax call
}
}

How to call external method from nested ajax (success) method?

I need to call onSuccessLogin method from ajax success method, or put response as argument into onSuccessLogin.
Thank you for answers.
submit: function (form) {
$.ajax({
type: "post",
url: "/login",
data: {
login: $(form).find('#login').val(),
password: $(form).find('#password').val(),
deviceType: environmentInfo.browser,
sdkVersion: environmentInfo.browserVersion,
osVersion: environmentInfo.OS
},
success: function(res) {
localStorage.setItem("languagesList", res);
//how to call onSuccessLogin method from here?
},
//Another implementation
// success: this.onSuccessLogin(res), - dosen't work, if I want put response from ajax into this method call
error: this.onErrorLogin
});
},
onSuccessLogin: function () {
//localStorage.setItem("languagesList", res); get response from second implementation
window.location = "/";
}
By creating a reference (that can be seen from the scope of AJAX success callback) to the object holding onSuccessLogin.
Inside the submit method (as a sibling of onSuccessLogin) that object is this.
Also see MDN reference on ES6 Arrow functions - abstraction for binding this to enclosing scope.
submit: function (form) {
var self = this;
$.ajax({
type: "post",
url: "/login",
data: {
login: $(form).find('#login').val(),
password: $(form).find('#password').val(),
deviceType: environmentInfo.browser,
sdkVersion: environmentInfo.browserVersion,
osVersion: environmentInfo.OS
},
success: function(res) {
localStorage.setItem("languagesList", res);
self.onSuccessLogin();
},
//Another implementation
// success: this.onSuccessLogin(res), - dosen't work, if I want put response from ajax into this method call
error: this.onErrorLogin
});
},
onSuccessLogin: function () {
//localStorage.setItem("languagesList", res); get response from second implementation
window.location = "/";
}
I don't know this logic is correct or not , if you place the function outside of ajax loop it will work .
$.ajax({
url: 'test',
success: function(data) {
alert("received contents="+data);
onSuccessLogin();
}
});
function onSuccessLogin() {
alert("Successfully logged!!!");
}

Declare one Ajax Function and fill it with different variables

I'm trying to make my page more efficient by using a separated ".js" file and trying to declare multilple used functions only one time. So I have to declare them in a way, that they caa be used for different situations. For Example passing different data.
Here is my Ajax Function in the "functions.js" file:
function CallAjax(type, url, data, div){
$.ajax({
type: type,
url: url,
data: data,
success: function (data) {
console.log(data);
$(div).html(data);
}
});
}
Here is my Code in my PHP File where I use this function and pass Parameters:
CallAjax('POST', 'about.php', '{ aufid : id }', '#con2');
My Problem is the "data" section. How can I declare it? The way I'm doing it doesn't work.
I don't want to use a new Ajax Function everytime when I need different data... I'm trying to trigger less functions as possible.
If you have any tips to make the page more efficient by trying to use less code, then it would be awesome if you mention them, too! Thank you!
you can do it like this:
var obj = {
aufid: 1
};
CallAjax('POST', 'about.php', obj, '#con2');
I propose js callback:
function CallAjax(type, url, data, div){
$.ajax({
type: type,
url: url,
data: data,
success: function (data) {
callback(data);
}
});
}
var obj = {
id:1
};
CallAjax('POST', 'about.php', obj, function(response){
$(div).html(response); //or other
});
or a more elegant way in promise:
function CallAjax(type, url, data){
return $.ajax({
type: type,
url: url,
data: data,
});
}
var obj = { id: 1 };
var jxhr = CallAjax('POST', 'about.php', obj);
jxhr.done(function(response){
//successful callback goes here...
}).fail(function(response){
//failure callback goes here...
}).always(function(response){
//always callback goes here...
});
: )

Categories