Returning function content after AJAX call - javascript

I'm using webuiPopover plugin, to set popover content, i'm using a function
$('.blob a').webuiPopover({
template: template,
trigger: 'hover',
type: 'async',
url: '/ajax/getprofileinfo.php?user=433',
content: function(requestData) {
//executed after successful ajax request.
//How I can make another ajax call and then return everything to content?
}
});
Now... I can do any kind of things inside this callback. But what if I want to make another AJAX request inside this function (in this case i want to download Mustache template so i can render it with requestData and THEN return its output from the function
I tried something like this
content: function(requestData) {
var template = '';
$.get('/tpl/usertemplate.mustache').done(function(templateData) {
template = Mustache.render(templateData, requestData);
});
return template;
}
Without any luck. How to do it correctly? I know i could just set async to false, but it isn't "the right way".

Looking at this plugin API, I can't see the way to do what you want. There is async.before and async.after properties. You can try to use them, also you can try to call setContent mannually after second request is done, like
content: function(requestData) {
vat that = this;
$.get(url).done(function (data){
that.setContent(Mustache.render(templateData, data));
});
}
But i'm not sure if it will work.

Newbie mistake :) Javascript is asynchronous!
What's wrong with your code :
$.get('/tpl/usertemplate.mustache').done(function(templateData) { // This is done FIRST
template = Mustache.render(templateData, requestData); // This is done whenever the GET is finished, so... THIRD
});
return template; // This is done SECOND - At this point, template is empty.
What you should do :
$.get('/tpl/usertemplate.mustache').done(function(templateData) {
template = Mustache.render(templateData, requestData);
return template;
});
Or even simpler :
$.get('/tpl/usertemplate.mustache').done(function(templateData) {
return Mustache.render(templateData, requestData);
});

Related

Passing variable from a onload promise in jQuery

I'm trying to pass a parameter from a onload GET method call to a POST method. The GET method is being loaded on window.onload and the POST function is not in the onload call otherwise the POST function will trigger once the window has loaded. I only want to trigger POST function when I click a button.
How can I pass a variable from a onload AJAX call to my POST function?
The only way I could think of is using a global variable however I don't think that's a good way of passing it to another function.
window.onload = function () {
function firstCallBack() {
$.get('http://website.com/API/docs/v1').then(function(data1){
var passThis = "PassMeToPOST"
}).then(function (data2) {
})
}
}
POST function
function saveSettings(passThatVar) {
var urlVal = window.__env.url+ "Preview/TypeDefinition";
var xslSettingVal = $('#PreviewXml').val().replace(/\n/g, "");
var allData = {
'ObjectName': passThatVar,
'DisplayDefinition': setting,
}
$.ajax({
url: urlVal,
type: "POST",
data: JSON.stringify(allData),
success: function (data) {
console.log('success');
}
});
}
Button HTML:
<button onclick="saveSetting()"> Save Setting </button>
Try this:
Your button:
<button id="save-settings"> Save Setting </button>
After your get request, set a data-attribute to your button:
function firstCallBack() {
$.get('http://website.com/API/docs/v1').then(function(data1){
$("#save-settings").data("passMe", "PassMeToPOST");
}).then(function (data2) {
})
}
Bind the click event(its a best practice than using inline events):
$("#save-settings").on("click", saveSetting);
On your saveSetting() function:
function saveSetting() {
var allData = {
'ObjectName': $(this).data("passMe"),
'DisplayDefinition': setting,
}
//... your post request
}
You can also check if the get request has finished before starting the post request(to avoid a bug in an extreme scenario):
if (!$(this).data("passMe")) {
return;
}
You're basically asking how to keep a variable out of the global scope. This is called encapsulation. It is a good instinct but a large topic. Here is a post that I like on the topic: http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/
One low budget way of doing this is instead of making a global variable for your value, make a global namespace for your own use.
var MyUniquelyNamedThing = {};
...
// get response:
MyUniquelyNamedThing.ThatValueINeed = data;
...
// posting:
data = { val1: MyUniquelyNamedThing.ThatValueINeed , etc. };

Synchronous call

I have a web application where my app's front-end uses angular js. I have a method in the angular js controller which is called on-click of a button. And in that method, I call the angular service to send a request to the Java controller. The logic looks like this
var submitted= true;
submitted= sampleService.sampleMethod(sampleParam);
alert(submitted);
if(!submitted){
//some action
}
The service will return true if the request was successful, false if it failed.
The issue that i'm having is that I get the alert before the request is sent (the alert says undefined). So regardless the response, the if condition fails.
Is there a solution for this issue?
edit :
The sample method
this.sampleMethod = function (sampleServiceMethod, obj){
var modalInstance = $modal.open({
templateUrl: 'example.html',
controller: 'anotherController',
resolve: {
modalServiceMethod: function () {
return sampleServiceMethod;
}
}
});
modalInstance.result.then(function (modalServiceMethod) {
modalServiceMethod(obj).then(function(response){
$window.location = response.sampleUrl;
}, function(err) {
$log.error("error occured", err);
});
}, function () {
$log.debug('error on: ' + new Date());
}).finally(function() {
return false;
});
};
Basically if the request is successful, the page will be redirected. But I need the return value of false during failure to make necessary changes.
** Update #1 **
I could help better if you organize and rename the code a bit. Hard to follow with all the names when they don't mean anything.
As a first thing try adding this return statement before the modalInstance::
return modalInstance.result.then(function (modalServiceMethod) {
modalServiceMethod(obj).then(function(response){
$window.location = response.sampleUrl;
}, function(err) {
$log.error("error occured", err);
});
}, function () {
$log.debug('error on: ' + new Date());
}).finally(function() {
return false;
});
** Original answer **
Why do you declare submitted as true and then run run the function on it?
It looks like this function:
sampleService.sampleMethod(sampleParam);
return undefined.
Add the code of that function so we can look into it.
If that function sends a request to the server to fetch data, it will be returned as a promise. in that case your code should be:
sampleService.sampleMethod(sampleParam).then(function(response){
submitted = response.data;
conole.log(submitted)
});
but the fact you get undefined in your alert and not a promise object, indicates you probably missed a "return" statement in your sampleService.sampleMethod(sampleParam) method. that method should look something like this:
function sampleMethod(param) {
return $http.get('url', param)
}

Ajax with external parameter Angular

I am new to angular and what I am willing to do is replace a piece of code I wrote in the past in jquery to angularjs.
The goal is to take a string from a span element, split it in two and pass the two strings as parameters in a GET request.
I am trying to learn best coding pratices and improving myself so any comments of any kind are always welcome.
Working Code in jquery:
//Get Song and Artists
setInterval(function () {
var data = $('#songPlaying').text();
var arr = data.split('-');
var artist = arr[0];
var songTitle = arr[1];
//Request Lyrics
$.get('lyricsRequester.php', { "song_author": artist, "song_name" : songTitle},
function(returnedData){
console.log(returnedData);
$('#refreshLyrics').html(returnedData);
});
},10000);
Code in Angular
var app = angular.module("myApp", []);
app.factory('lyricService', function($http) {
return {
getLyrics: function($scope) {
//$scope.songArr = $scope.currentSong.split('-'); <-- **undefined currentSong**
//$scope.artist = $scope.songArr[0];
//$scope.songTitle = $scope.songArr[1];
return
$http.get('/lyricsRequester.php', {
params: {
song_author: $scope.artist,
song_name: $scope.songTitle
}
}).then(function(result) {
return result.data;
});
}
}
});
app.controller('lyricsController', function($scope, lyricService, $interval) {
$interval(function(){
lyricService.getLyrics().then(function(lyrics) {
$scope.lyrics = lyrics; <-- **TypeError: Cannot read property 'then' of undefined**
console.log($scope.lyrics);
});
}, 10000);
});
index.html (just a part)
<div class="col-md-4" ng-controller="lyricsController">{{lyrics}}</div>
<div class="col-md-4"><h3><span id="currentSong" ng-model="currentSong"></span></h3><div>
You need to be careful with your return statement when used in conjunction with newlines, in these lines:
return
$http.get('/lyricsRequester.php',
If you don't, JS will automatically add a semicolon after your return, and the function will return undefined.
Move the $http.get statement to the same line as your return statement.
return $http.get('/lyricsRequester.php', ...
Refer to the following docs:
MDN return statement
Automatic Semicolon Insertion
As for your second issue, you $scope is not really something you inject into your services (like $http). Scopes are available for use in controllers.
You need to refactor your code a bit to make things work.
eg. Your getLyrics function can take a song as a parameter. Then in your controller, you call lyricsService.getLyrics(someSong). Scope access and manipulation are only done in your controller.
app.factory('lyricService', function($http) {
return {
getLyrics: function(song) {
var songArr = song.split('-');
var artist = songArr[0];
var songTitle = songArr[1];
return $http.get('/lyricsRequester.php', {
params: {
song_author: artist,
song_name: songTitle
}
}).then(function(result) {
return result.data;
});
}
}
});
app.controller('lyricsController', function($scope, lyricService) {
$scope.currentSong = 'Judas Priest - A Touch of Evil';
$interval(function(){
lyricService.getLyrics($scope.currentSong).then(function(lyrics) {
$scope.lyrics = lyrics;
console.log($scope.lyrics);
});
}, 10000);
});
You also have some other issues, like using ng-model on your span. ng-model is an angular directive that is used in conjunction with form elements (input, select etc.), not a span as you have. So you might want to change that into an input field.
$http does not use .then, it uses .success and .error. the line that you have where it says then is undefined, should be replaced with a success and error handler instead. Below is a sample from the docs:
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
See Link:
https://docs.angularjs.org/api/ng/service/$http

making ajax request in meteor helpers

How can i wait until the ajax request finishes when returning data to a meteor helpers method.
For example,
Template.item.helpers({
itemName:function () {
var user = Meteor.user();
$.when(reallyLongAjaxRequest()).done(function (a1) {
//tried using jquery when
return "Item Name should have this because it waited";
});
return " Doesnt wait at all";
}
});
I have a reallyLongAjaxRequest() running and i would like it to finish before continuing on with my itemName helper. The log statement to console always shows undefined but that's because the ajax request hasn't finished. I tried using the jquery when with no luck. Any ideas
Edit:
I should mention that i am inside the helper function for a reason. I need the item 'id' being rendered so that i can run the ajax request with that paramater. Using reactive sessions would be perfect but i don't know of a way to get currently rendering items outside of the helpers method definition?
An unnamed collection is one where null is passed for the name. It is an in-memory data structure, not saved to the database. (http://docs.meteor.com/#meteor_collection)
OK, given a Meteor collection called "items" and wanting to do an ajax request for each item based on the item _id, and then being able to reference the ajax result in a template, this is what I'd do:
(roughly)
var Items = new Meteor.Collection('items');
var Results = new Meteor.Collection(null);
Items.find().observeChanges({
added: function (id) {
$.get(url, {id: id}, function (data) {
if (Results.findOne(id))
Results.update(id, {$set: {result: data}});
else
Results.insert({_id: id, result: data});
});
}
});
Template.item.itemName = function (id) {
var doc = Results.findOne(id);
if (doc)
return doc.result;
else
return "";
};
inside your html you'll need to pass in the id to the helper:
{{itemName _id}}
Is there no way to just timeout for a few seconds when defining the helper so that my ajax request finishes without immediately returning.
No, with reactive programming things happen immediately, but you update when you have new stuff.
Make your ajax request separately, and when it completes, have it store the result in a Session variable. Then have your template helper return the value of the Session variable. Roughly...
$.get(url, function (data) {
Session.set('result', data);
});
Template.item.itemName = function () {
return Session.get('result');
};
Session is a reactive data source, so your template will automatically updated when the result of the ajax call comes in. (Naturally you can choose to call the Session variable anything you like, I just used "result" as an example).
This works and tested in MeteorJS > 1.3.x
Add the http package from the console meteor add http
Example POST call with data elements being sent to server and with custom headers.
HTTP.call('POST', tokenUri, {
data: {
"type": 'authorization_code',
//"client_id": clientId,
"code": code,
"redirect_uri" : redirectUri,
},
headers: {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : "true",
"Access-Control-Allow-Methods" : "GET,HEAD,OPTIONS,POST,PUT",
"Access-Control-Allow-Headers" : "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers",
}
},function(error, response) {
if ( error ) {
console.log( error );
} else {
console.log( response );
}
});

How to wait to render view in backbone.js until fetch is complete?

I'm trying to understand how a portion of backbone.js works. I have to fetch a collection of models once the app begins. I need to wait until fetch is complete to render each view.
I'm not 100% sure the best approach to take in this instance.
var AppRouter = Backbone.Router.extend({
routes: {
"": "home",
"customer/:id": "customer"
},
home: function () {
console.log("Home");
},
customer: function (id) {
if (this.custromers == null)
this.init();
var customer = this.customers.at(2); //This is undefined until fetch is complete. Log always says undefined.
console.log(customer);
},
init: function () {
console.log("init");
this.customers = new CustomerCollection();
this.customers.fetch({
success: function () {
console.log("success");
// I need to be able to render view on success.
}
});
console.log(this.customers);
}
});
The method I use is the jQuery complete callback like this:
var self = this;
this.model.fetch().done(function(){
self.render();
});
This was recommended in a Backbone bug report. Although the bug report recommends using complete, that callback method has since been deprecated in favor of done.
You can also do this with jquery 1.5+
$.when(something1.fetch(), something2.fetch()...all your fetches).then(function() {
initialize your views here
});
You can send your own options.success to the collections fetch method which runs only when the fetch is complete
EDIT (super late!)
From the backbone source (starting line 624 in 0.9.1)
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === undefined) options.parse = true;
var collection = this;
var success = options.success;
options.success = function(resp, status, xhr) {
collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
if (success) success(collection, resp);
};
Note the second to last line. If you've passed in a function in the options object as the success key it will call it after the collection has been parsed into models and added to the collection.
So, if you do:
this.collection.fetch({success: this.do_something});
(assuming the initialize method is binding this.do_something to this...), it will call that method AFTER the whole shebang, allowing you trigger actions to occur immediately following fetch/parse/attach
Another useful way might be to bootstrap in the data directly on page load. This if from the
FAQ:
Loading Bootstrapped Models
When your app first loads, it's common to have a set of initial models that you know you're going to need, in order to render the page. Instead of firing an extra AJAX request to fetch them, a nicer pattern is to have their data already bootstrapped into the page. You can then use reset to populate your collections with the initial data. At DocumentCloud, in the ERB template for the workspace, we do something along these lines:
<script>
var Accounts = new Backbone.Collection;
Accounts.reset(<%= #accounts.to_json %>);
var Projects = new Backbone.Collection;
Projects.reset(<%= #projects.to_json(:collaborators => true) %>);
</script>
Another option is to add the following inside of your collections initialize method:
this.listenTo(this.collection, 'change add remove update', this.render);
This will fire off the render method whenever the fetch is complete and/or the collection is updated programmatically.
You Can Use on and Off Methods
if you want to add trigger method like suppose if you want on success you want to call render method so please follow below example.
_this.companyList.on("reset", _this.render, _this);
_this.companyList.fetchCompanyList({firstIndex: 1, maxResult: 10}, _this.options);
in Model js please use like
fetchCompanyList: function(data, options) {
UIUtils.showWait();
var collection = this;
var condition = "firstIndex=" + data.firstIndex + "&maxResult=" + data.maxResult;
if (notBlank(options)) {
if (notBlank(options.status)) {
condition += "&status=" + options.status;
}
}
$.ajax({
url: "webservices/company/list?" + condition,
type: 'GET',
dataType: 'json',
success: function(objModel, response) {
UIUtils.hideWait();
collection.reset(objModel);
if (notBlank(options) && notBlank(options.triggerEvent)) {
_this.trigger(options.triggerEvent, _this);
}
}
});
}

Categories