On my Polymer-Page I try to login to my google-plus page and retrieve my name and cover-photo url.
For that purpose I use a google-signin element that runs the following function when login finishes:
loginSuccess: function(e){
console.log("Success!");
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get( {'userId' : 'me'} );
request.execute(function(retr){
console.log("Data Loaded");
console.log(retr);
this.myFunction(retr);
});
});
}
Up to "Data Loaded" everything works great, also the console prints out the whole result object from google plus. But I am not able to execute functions (this.myFunction) or access data from polymer there. How do I store the result data from the gapi-request into my polymer variables???
Thanks, Malte
Inside the Ajax result, the this context is different. You need to setup a variable before your ajax request, or before your function to access it, like so :
self: this,
loginSuccess: function(e){
console.log("Success!");
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get( {'userId' : 'me'} );
request.execute(function(retr){
console.log("Data Loaded");
console.log(retr);
self.myFunction(retr);
});
});
}
I just found out, that i chose the wrong way to get my profile-data.
There is a polymer element to get data from the google-api called google-api-loader (http://googlewebcomponents.github.io/google-apis/components/google-apis/#google-api-loader). I use that element the following way additionally to the google-signin element:
<google-api-loader id="plus" name="plus" version="v1"
on-google-api-load="{{displayProfile}}">
</google-api-loader>
Here the function displayProfile
displayProfile: function(){
if (this.signedIn && this.$.plus.api) {
var request = this.$.plus.api.people.get({"userId": "me"});
request.execute(function (resp) {
this.userData = resp;
}.bind(this));
}
}
It works awesome and I get access to the data via this.userData. Here it another example: https://github.com/Scarygami/google-signin-samples/blob/master/elements/google-signin-status.html
Related
I am trying to get the pasted contents of a form text field to trigger an AJAX action which connects to a php script to deal with the data and then sends the relevant response.
The php script is working perfectly so I know the problem isn't there.
The jQuery function also works perfectly, by alerting whatever is pasted into the text field if I do this
$(document).ready(function(){
$('input').on('paste', function () {
var capture = this;
setTimeout(function () {
var url = $(capture).val();
alert (url);
}, 100);
});
});
But when I try to add the AJAX business it all fails.
I'm obviously doing it wrong but I don't know the correct way to do it.
The way I'm calling AJAX is the same method I use in a whole bunch of other scripts and it works fine in those so it must be to do with where it's being called.
I've tried (left off the doc ready to save clutter) :
$('input').on('paste', function () {
var capture = this;
setTimeout(function () {
var url = $(capture).val();
}, 100);
var data = {
'action': 'myAction',
'security': $( '#my-nonce' ).val(),
'url' : url,
'check' : check
};
$.post(myajax.ajaxurl, data, function(response) {
alert(response);
}
});
And also tried :
$('input').on('paste', function () {
var capture = this;
setTimeout(function () {
var url = $(capture).val();
var data = {
'action': 'myAction',
'security': $( '#my-nonce' ).val(),
'url' : url,
'check' : check
};
$.post(myajax.ajaxurl, data, function(response) {
alert(response);
}
}, 100);
});
And I've also tried setting the url var directly in the data var :
var data = {
'action': 'myAction',
'security': $( '#my-nonce' ).val(),
'url' : $(capture).val(),
'check' : check
};
But nothing is working.
I suspect this is to do with the setTimeout function.
Is there a specific way of firing an AJAX call when also using setTimeout?
Just for clarity. I'm trying to trigger an AJAX call on paste event.
try to increase the time, I mean
setTimeout(function(){...
,1000}
try experimenting with different times.
If you get the answer then your post call is eating up the time.
I have this code Ext.get('book').setValue('1');
Note: Loads the page and book value is set to 1. Not after page load
and book value change to 1.
It sets the book to value 1. But it does not trigger a change event. Is there a way to trigger the change event after page loads?
Edit:
In html script,
<script..>
$(document).ready(function () {
$("book").on("blur", function() {
//calls other function
}); // not called as blur is not invoked
});
</script>
<input id="book" type="book" value="" /><br />
In extjs,
var panel = Ext.create('Ext.grid.Panel', {
id: 'panel',
columns: [
var bookid = "new book";
Ext.Ajax.request({
params: { bookid: bookid},
function: function (response) {
Ext.get('book').setValue(bookid);
// after setValue, book will receive a change event(e.g .blur in html) and changes other functions
}
});
]
});
Your ajax request seems to be malformed, the function: function statement would be the place where you put normally success: function like in the following statement:
Ext.Ajax.request({
url: 'insert-your-http-endpoint-here',
params: {
bookid: bookid
},
success: function(response){
debugger; // -> setting this statement will show that you enter the success statement
Ext.get('book').setValue(bookid);
},
failure: function(response, opts) {
// something went wrong with your request
console.log('server-side failure with status code ' + response.status);
}
});
more info about how to use ExtJS or the specific function, you could find in the documentation (check if you have the correct version, ofcourse) which can be found here
From the above code, you don't need the debugger statement, but it could help if you want to check if you actually get into this code block or not, and what happens when you try to set the value.
Also, don't forget to check your console output when something is not working, maybe there was a problem that would be clearly indicated in the console log
I have 2 problems with $http in function in this code.
$scope.buttonClick = function(){
// Send input data
$.post('lib/add_contact.php', $scope.contact, function(data){
data = angular.fromJson(data);
if(!data.error){
$scope.contact = "";
console.log('success');
}else{
console.log('error');
}
});
// Next Code
console.log('Next Code');
}
First problem is, when I want to clear a contact, it dont work immediately but only after I press key into input.
If I put
$scope.contact = "";
outside of POST, It works well.
Second problem is, why is POST called last? Output of code is
Code Next
success
but i would like that output be
success
Code Next
Thanks for ideas and answers.
You are using jQuery for the ajax call which is happening outside the angular world. You need to trigger a digest cycle for the scope to update so the change is reflected in your view.
To fix the issue:
$scope.buttonClick = function(){
// Send input data
$.post('lib/add_contact.php', $scope.contact, function(data){
data = angular.fromJson(data);
if(!data.error){
$scope.$apply(function(){ //<-- calling $apply()
$scope.contact = "";
});
console.log('success');
}else{
console.log('error');
}
});
// Next Code
console.log('Next Code');
}
However the preferred approach would to use the built in $http service included inside of angular which knows about angular and triggers the digest automatically.
Using $http (don't forget to add as a dependency to your controller)
$scope.buttonClick = function() {
$http.post('lib/add_contact.php', $scope.contact).success(function(data) {
data = angular.fromJson(data);
if (!data.error) {
$scope.$apply(function() { //<-- calling $apply()
$scope.contact = "";
});
console.log('success');
} else {
console.log('error');
}
});
}
The following code gives me an error like this when I request a page and it comes back 404. Instead it should bring up an alert. What is strange is it only does this on links that have been ajaxed in, on links that don't update/change it works fine.
('.page-wrap').append('<img src="img/graphics/ajax-loader.gif" class="ajax-loader" />');
var target = $('section.content'),
siteURL = 'http://' + top.location.host.toString(),
internalLinks = $("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']"),
links = $('a'),
URL,
el,
mainContent,
headContent,
headClasses,
pageName,
ajaxSpinner = $('.ajax-loader');
internalLinks.click(function(e) {
el = $(this);
URL = el.attr('href');
$('.current_page_item').removeClass('current_page_item');
el.addClass("current_link").parent().addClass("current_page_item");
ajaxLoader(URL, false);
e.preventDefault();
});
function ajaxLoader(location, isHistory) {
$("html, body").animate({ scrollTop: "0px" });
ajaxSpinner.show();
$('.page-wrap').css('opacity', '0.5}');
// Load New Page
$.get(location, function(data) {
mainContent = $('section.content', data).html();
headContent = $('.feature-content', data).html();
pageName = $('.page-name', data).html();
headClasses = $('header', data).attr('class');
$('section.content').html(mainContent);
$('.page-name').html(pageName);
$('.feature-content').html(headContent);
if (headClasses) {
$('header').attr('class', headClasses);
} else {
$('header').removeClass();
}
if (!isHistory) {
history.pushState(location, '', location);
}
$(resizeHeader);
ajaxSpinner.fadeOut();
}).error(function() {
alert('woops'); // or whatever
});
}
w.bind('popstate', function(event) {
if (event.originalEvent.state !== null ) {
ajaxLoader(event.originalEvent.state, true);
}
});
First thoughts
Is it perhaps the case that something in your success handler code is causing an error of some kind? Like maybe the injection of whatever html that comes back the first successful time is causing the script to fail a second time?
What do you see playing out in your your Fiddler/Firebug/F12 developer tool of choice - you are using one of these, right? :) Keep an eye on any console errors...
Second thought
What jQuery version are you using?
I have tested this with jq 1.8.2 and the error handler works just fine for me, but if this is a JSONP request it won't trigger the error() function. I took the gist of your code:
$.get(
"404MeBaby.html", function (data) {
$(".result").html(data);
console.log(data);
}
).error(
function (x) {
console.log("well that didn't go so well...");
});
From the API:
As of jQuery 1.5, the success callback function is also passed a
"jqXHR" object (in jQuery 1.4, it was passed the XMLHttpRequest
object). However, since JSONP and cross-domain GET requests do not use
XHR, in those cases the jqXHR and textStatus parameters passed to the
success callback are undefined.
You could try using $.ajax instead as it gives a lot more control. Or, you can set the jQuery global ajax options as shown here that will affect all $.get calls, but remember the curse of JSONP, if relevant!
In my angular code, I load some data in ajax which fill my template, so far so good...
Then, once the data are loaded, I want to call a javascript function.
I couldn't find a way to have callback once the template is rendered. I have try several events but none are working.
My solution is to call the javascript method after a timeout:
$http.post('url').success(function (data) {
$timeout(function () {/* process data */ }, 200);
});
It seems to work, but that's a timeout, nothing guarantee me that at the end of the timeout everything is rendered. Maybe it is working only because my PC is fast...
Is there an event based solution? Or any solution better than this one...
The jsfiddle of my solution : http://jsfiddle.net/ZCT4K/5/
You need to $watch() your data. So you could try the following:
$http.post('url')
.success(function (data) {
$scope.postData = data;
});
//Watch the value of postData
$scope.$watch('postData', function () {
if ($scope.postData === undefined || $scope.postData === null || $scope.postData === "") {
return;
}
/*Else process your data*/
});