Call a function within the .done of a Jquery.post call - javascript

I am confused on this one.
I am trying to call another defined function within the AJAX done and i get the function cannot be found error.
I have also tried to declare this as a variable and use that still get the same issue, cannot find the function.
var self = this
...
$.post.done(function(respose) {
self.init_customer_dropdown();
})
If i call the function outside of the AJAX request works fine
Here is the full code block
$('.save-client-modal').on('click', function(e) {
e.preventDefault();
//Save Cutomer to Database
var url = admin_url + "clients/create_client_ajax";
var data = {};
...
$.post(url, data).done(function (response){
response = JSON.parse(response);
if(response.success == true || response.success == "true")
{
init_customer_dropdown(); <-- will not run this function
}
else
{
alert_float('warning', response.message);
}
});
});
function init_customer_dropdown()
{
alert("Customer Dropdown");
}
Thanks in Advance
Mike

Related

Set variable from function with possible ajax-load inside?

I have made my own script for loading content with AJAX if nor already loaded. Here it is:
/*
* AJAX Load Content
*/
var loaded_content_urls = {};
function get_content_from_url(url)
{
if (loaded_content_urls[url] === undefined)
{
$.ajax({url: url}).done(function(data)
{
loaded_content_urls[url] = data;
return data;
});
}
else
{
return loaded_content_urls[url];
}
}
And I wanna use it like this:
var loaded_html = get_content_from_url($(this).attr('href') + '?ajax');
But that won't work great since it can take a while for the content to be loaded and the variable above needs the value directly. So how should I do this?
I did a search about the issue but only found solutions where you always loads the content with AJAX. My code is special in that way that it first checks if the content already have been loaded. So I can't just have the AJAX function as return of the function.
Try using https://api.jquery.com/deferred.promise/
Your example code should like below:
var urlData = ''
function get_content_from_url (url) {
var _defer = jQuery.Deferred();
if( urlData === undefined){
$.ajax({url: url}).done(function(data){
urlData = data;
_defer.resolve(urlData);
});
} else{
_defer.resolve(urlData);
}
return _defer.promise();
};
$.when(get_content_from_url(url)).then( function( data) {
var loaded_html = data;
});
I will also suggest to use reject and fail method to handle error scenarios

multiple calls to ajax simultaneously

I'm trying to make multiple calls to Ajax, i have fields like time intervals and no of calls to ajax under that time period. Now the problem is, while making multiple calls to same Ajax, there may be chances of merging of data with the other data that were send to Ajax earlier. I am not sure that it will happen.
Here my Ajax call.
callAjax = function () {
var dataIn = inObj.data || {};
var successFunc = inObj.success || function () {};
var passOn = inObj.passOn || {};
var myParams = {drape:1,type:'GET'};
myParams.url = this.homeComingUrl;
$.extend(myParams,params);
var data = this.fillAction(action,dataIn);
if (myParams.drape) { vidteq.utils.drapeSheer(action); }
var that = this;
var magicCall = $.ajax({
url:myParams.url,
type:myParams.type,
data:data,
success: function (response) {
// TBD we need better error handling
if (myParams.drape) { vidteq.utils.undrapeCurtain(action); }
successFunc(response,passOn);
},
error:function(response) {
if (myParams.drape) { vidteq.utils.undrapeCurtain(action); }
that.gui.io.handleError(response);
}
});
}
saveEvents = function () {
this.commitEditingEvent();
var dataEvents = this.collectEventsToSave();
//$('#calendar').fullCalendar('removeEvents');
var that = this;
if (vidteq.eTrainer==1) {
dataEvents = arguments[0];
}
if (!dataEvents.length) { alert("Nothing to save");return; }
this.callAjax('updateEvents',{
data : { events : JSON.stringify(dataEvents) },
success : function (response,passOn) {
that.handleGetEvent(response,passOn);
}
},{type:'POST'});
}
This may not be required for understanding the problem.
If any body can explain how Ajax handles multiple calls, then it'll really helpful.
First line, your anonymous function isn't saved and isn't ran. Then. In each function, what does this refer to ? What is this context ? Is this window or do you call your function like saveEvents.apply( jQuery ) ?
JavaScript is powerful, when your want to run XMLHttpRequest (Ajax uses it), scripts are called when an event happen, like "server is found", "request is send", "file is reading", "file loaded"... for each state of your request. Ajax by jQuery help you to request asynchronous. You can request as many Ajax request as you would like in the same time. The important is to create a function happen in success case.
In this success function, you receive data, you compute it, then this function may call another Ajax request, and so on. When you chain requests like this to get the same file, we call it Ressource.
Ressource uses Ajax which uses XMLHttpRequest.
you need to do asynic :false in your ajax method
function isLoggedIn() {
var isLoggedIn;
$.ajax({
async: false,
// ...
success: function(jsonData) {
isLoggedIn = jsonData.LoggedIn
}
});
return isLoggedIn
}

how to pass json parameters btween 2 files using module

i am trying to call function in other js file using require.all these the parameters
> Login = require("LoginRequest");
Create = require("CreateView");
var params = { username : username.value , password : password.value};
var type ="POST";
var URL = "https://localhost/post_auth.php";
var Result; </li>
and here the call funcion from LoginScreen.js
b2.addEventListener('click',function(e)
{
alert(params.username);
if (username.value != '' && password.value != '')
{
Result=Login.Request(params,type,URL);
}
else
{
// warning alert
alert("Username/Password are required");
}
if (Result.logged == true)
{
alert("Welcome " + Result.name + ", Please answer the following question");
Create();
}
else
{
alert(Result.message);
}
});
when i try to pass the parameters to LoginRequest.
function Request(params,type,url){
var Result;
var loginReq = Titanium.Network.createHTTPClient();
loginReq.open(type,url);
loginReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
//send parameters
loginReq.send(JSON.stringify(params));
loginReq.onload = function()
{
var json = this.responseText;
Result = JSON.parse(json);
alert (Result.logged);
alert (Result.name);
};
return Result;
};
exports.Request = Request;
the calling return undifiend object , where is my wrong here ?
That's because you are making an async call.
when you call loginReq.send() the call will be made and it will continue executing the rest of the code without waiting for the async call to be finished, that's why the function returns undefined.
To fix this you can make a sync call instead of an async call (this is a bad bad bad idea) or you could restructure your code, maybe LoginRequest could return the loginReq instance instead of the result

Asynchronous Ajax Logic

$("#container").on("change", "#control1", function() {
if ($("#checkData").val()) {
$.get("/Controller/CheckData/" + $("#control2").val(), function(data1) {
if(!data1.Success) {
alert("Unable to do POST.");
return;
});
};
formData = $("#form").serialize();
$.post("/Controller/PostData", formData, function(data2) {
// Do something...
});
}
If checkData is false, the form should post. If checkData is true, the form should only post if the get returns true.
This doesn't seem to work because the form gets posted while the alert dialog is still open. I think it may be due to the asynchronous nature of AJAX. Is this correct?
Yes. When you call the $.get() method, the code continues executing. That means that it immediately goes to the declaration and $.post() call that follow. If you want to wait to execute those until after the $.get() call completes, you'll need to put them in the callback function.
yes, the post will always happen because you haven't done anything to prevent it. If you want the post to be sent or not sent based on the outcome of the $.get, you'll need to move it to the get callback fn.
Additionally, your code was riddled with syntax errors, though I suspect many of them were copy paste errors otherwise you wouldn't have even been getting the alert.
$("#container").on("change", "#control1", function () {
if ($("#checkData").val()) {
$.get("/Controller/CheckData/" + $("#control2").val(), function (data1) {
if (!data1.Success) {
alert("Unable to do POST.");
} else {
var formData = $("#form").serialize();
$.post("/Controller/PostData", formData, function (data2) {
// Do something...
});
}
});
}
});
Yes, you'll allways get to $.post...
Yes. And you cannot return from a callback. You will need to do
$("#container").on("change", "#control1", function () {
if ($("#checkData").val()) {
var formData = $("#form").serialize();
$.get("/Controller/CheckData/" + $("#control2").val(), function (data1) {
if (!data1.Success)
alert("Unable to do POST.");
else
$.post("/Controller/PostData", formData, function (data2) {
// Do something...
});
});
}
});
Btw, it might be unsafe to rely on a client-side check of the data (even if by ajaxing /CheckData/) before "allowing" a POST request. If you want a two-step process, you should return a "safety" token from the GET request.
Please note that these two lines are reversed in your code (and therefore don't match up):
$("#container").on("change", "#control1", function() {
if ($("#checkData").val()) {
var c2 = $("#control2").val();
$.get("/Controller/CheckData/" + c2, function(data1) {
if(!data1.Success) {
alert("Unable to do POST.");
return;
} <=== HERE
}); <=== HERE
};
formData = $("#form").serialize();
$.post("/Controller/PostData", formData, function(data2) {
// Do something...
});
}
I extracted var c2 from the $.get line only to see the braces more easily, not for any other reason.

Let the $.post function return the response in the parent function

I got this code:
function server_request(module,section,action,data) {
data['module'] = module;
data['section'] = section;
data['action'] = action;
var responsetxt = null;
$.post('../application/server.php', data, function(data) {
responsetxt = data;
});
return responsetxt;
}
And it return's null ?
What i want is let the server_request function return the responseText?
But at some way it doesn't work, why? And how to let it work?
You're providing a callback function to $.post, which will be run when the request is returned. The server_request function returns immediately (i.e. before the response is available) so responsetxt will still be null.
To get around this you could add a callback parameter to server_request, then execute it in the anonymous function you provide to the $.post call:
function server_request(module,section,action,data,callback) {
data['module'] = module;
data['section'] = section;
data['action'] = action;
$.post('../application/server.php', data, function(data) {
callback(data);
});
}
You could then use this like:
$(function() {
var module = x, section = y, data = z;
server_request(module, section, data, function(response) {
$('#result').html(response); // do stuff with your response
});
});
Check out continuation passing style for more information ( http://en.wikipedia.org/wiki/Continuation-passing_style and http://matt.might.net/articles/by-example-continuation-passing-style/).
You could get the return value, but only when doing a synchronous call instead of an asynchronous one:
function server_request(module,section,action,data,callback) {
data['module'] = module;
data['section'] = section;
data['action'] = action;
responsetxt = $.ajax({
"url": '../application/server.php',
"async": false,
"type": "POST",
"data": data
}).responseText;
return responsetxt;
}
Remember that a synchronous call like this freezes the browser until the server responds.

Categories

Resources