Google API Signout Not working - google-api

I integrate google login api and It works fine but there is an error in logout.The sign out process is not working.The logged user will not sign out after click the sign out link function.
This is my code:
<meta name="google-signin-client_id" content="here my api .apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
<div class="g-signin2" data-onsuccess="onSignIn"></div>
Sign Out
<script>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
if(profile.getEmail()!="") {
var myKeyVals = { token : googleUser.getAuthResponse().id_token }
$.ajax({
type: "POST",
url: "validate.php",
data: myKeyVals,
dataType: "text",
success : function(data) {
window.location = "page";
}
});
}
}
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
});
}
</script>
Here signOut js function is not working and the page will auto reload and go to adminpage.
This is my document.
Thanks in advance.

this works for me instead of http://localhost/application-name/logoutUser you can add your domain name
document.location.href = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://localhost/application-name/logoutUser";

This works for me,
Simply modify the signout function as follows,Here carefully note that reload() method is used to reload the current document soon after signout.
<button onclick="myFunction()">Sign Out</button>
<script>
function myFunction() {
gapi.auth2.getAuthInstance().signOut().then(function () {
console.log('User signed out.');
location.reload();
});
}
</script>

May be this will help.
const onGoogleSignOut = () => {
// using google logout redirect
//location.href = 'document.location.href = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=' + window.location.href;
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut()
.then(function () {
auth2.disconnect();
console.log('User signed out.');
//location.reload();
});
}

This worked for me. Full JS function code.
The asterisks are just an example of how to define the URL you want to redirect to after the logout is performed.
<button onclick="myFunction()">Sign Out</button>
<script>
function myFunction() {
location.href = 'https://accounts.google.com/Logout?&continue=http://******.com/';
}
</script>
Save this in a HTML file and access it from the browser where you are logged into the account you want to log out of. Can also be placed in a PHP file ETC. AS long as you dont place it in a manner that breaks the existing script.

Related

Vue JS Ajax Calls

I am trying to make the change from jQuery to Vue.js and am having some difficulty running an Ajax Call using vueresource. Below is a sample script I am using, with both jQuery and Vuejs. Both trying to access the same ajax call. The jQuery call works, the vuejs call doesn't. The sendAjax method is being called because the first 2 alerts show - then nothing.
Edit - this is only causing an error while running the Ajax call through Wordpress. Outside of WP, it does work. Any ideas??
<!DOCTYPE html>
<html>
<head>
<title>Vue Resource</title>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.2.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource#1.5.1"></script>
</head>
<body>
<button id="jQueryAjax">Jquery AJAX</button>
<div id="myvue">
<button #click.prevent="sendAjax()">AJAX</button>
</div>
<script>
let AjaxUrl = "http://localhost:8888/mySite/wp-admin/admin-ajax.php";
const postData = { action: 'my_ajaxcall', function: 'AjaxTest' };
Vue.use(VueResource);
const ajax_app = new Vue({
el: '#myvue',
methods: {
sendAjax() {
alert("VueAjax");
alert(JSON.stringify(postData));
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
});
}
}
});
$("#jQueryAjax").click(function() {
alert("jQueryAjax");
alert(JSON.stringify(postData));
alert(AjaxUrl);
$.ajax({
type: 'POST',
url: AjaxUrl,
data: postData,
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
}
});
});
</script>
</body>
</html>
You AJAX call probably encounters an error and you handle only the successful calls. Please extend your sendAjax function like this:
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
}, err => {
alert(err);
});
Now an error should be alerted.
BTW: It is better to use console.log() instead of alert(), it is much more readable and you won't have to confirm every alert.
After #mbuechmann pointing me to be able to see the actual error, I was able to determine that the issue I was having was actually to do with Wordpress. In order to use the Wordpress Ajax handler, you need to send an action to the REQUEST header. To do this, you need to send FormData, and without sending headers.
This code was found in this question : Custom Shortcode AJAX 400 Bad Request and enabled me to get my Fetch working with Wordpress.
var data = new FormData();
data.append( 'action', 'aj_ajax_demo' ); data.append( 'nonce', aj_ajax_demo.aj_demo_nonce );
fetch(aj_ajax_demo.ajax_url, {
method: 'POST',
body: data, }).then(response => {
if (response.ok) {
response.json().then(response => {
console.log(response);
});
} });

Issue with ajax call csfr token

I am trying to add an ajax call that changes the status of a listing, between listed and unlisted, when submitting the form I am having a 403 forbidden error in the console of the browser, I made some checking and it appears that Django is forbidding the form because of a lack of csrf token, however I am not good in javascript, so any help would be appreciated.
Here is my code in my view:
#require_POST
#ajax_required
#login_required
def unlist_ajax(request):
pk = request.POST.get('pk', None)
is_visible = request.POST.get('is_visible', None)
if pk and is_visible:
listing = get_object_or_404(Listing, pk=pk)
if is_visible == 'true':
listing.is_visible = False
listing.save()
messages.success(request, _("Listing unlisted"))
return JsonResponse({'status': 'ok'})
else:
listing.is_visible = True
listing.save()
messages.success(request, _("Listing re-listed"))
return JsonResponse({'status':'ok'})
and here is the template script:
in the top of the template, in the header:
<script>
function unlistPostAjax(listing_id, is_visible) {
var confirmation = confirm("{% trans 'are you sure you want to change the status of your listing?' %}");
if (confirmation) {
$.post("{% url 'dashboard:unlist_ajax' %}", {pk: listing_id, is_visible: is_visible}, function (response) {
console.log('sending delete query'); location.reload();
})
}
}
</script>
and in the bottom of the body:
<script src="{% static 'js/jquery.cookie.js' %}"> </script>
<script>
$(document).ready(function () {
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod (method) {
// These HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if(!csrfSafeMethod(settings.type) && !this.crossDomain) {
// Set X-CSRFToken HTTP Header
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
});
</script>
You can add this to the top of your <script> or if you have a base html template you can put this in there too.
{% csrf_token %}
<script type="text/javascript">
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
</script>
Believe you just need to add the csrf above the script you defined, but this is the whole implementation I currently use. I have no issues.

Yammer login display a 400 error page

I have both an embedded yammer login button and I tried through code to login and both return a 400 error page in the popup for the login. What can cause this?
yam.login(function (response) {
if (response.authResponse) {
postActivity();
}
you can use this
<span id="yammer-login"></span>
<script>
$(function(){
yam.connect.loginButton('#yammer-login', function (resp) {
if (resp.authResponse) {
//your code that
document.getElementById('yammer-login').innerHTML = 'Welcome to Yammer!';
}
});
});

Json call in js file returns NetworkError: 404 Not Found

I am using asp.net mvc 4, knockout-js within my application.
I would like to ask how can i make an call from js file to the controller?
it works when i write this code into the view (razor) page:
<script type="text/javascript">
$(document).ready(function () {
var url = '#Url.Action("GetTechnicians", "Ticket")';
$.post(url, null, function (data) {
alert("get data");
});
});
</script>
now I would like to make the call in *.js file.
the problem is that Url.Action is invalid within js file.
My url mapping in global.asax is: "{culture}/{controller}/{action}/{id}",
signature of my controller looks like: public JsonResult GetTechnicians()
When I use in js file:
var url = "/Ticket/Technicians";
I get an error: "NetworkError: 404 Not Found - http://localhost/Ticket/Technicians"
I would like to know how to complete the call from js file?
You could do the following...
In your JS file
var app = {
urls: {
getTechnicians: null
},
culture: "en",
getTechnicians: function () {
if (!app.urls.getTechnicians) {
throw new Error("getTechnicians URL not set");
}
$.post("/" + app.culture + app.urls.getTechnicians, null, function (data) {
alert("get data");
});
}
};
In your view
<script type="text/javascript" src="myscriptfile.js"></script>
<script type="text/javascript">
$(document).ready(function () {
app.urls.getTechnicians = '#Url.Action("GetTechnicians", "Ticket")';
app.culture = "en-us";
// Later on...
app.getTechnicians();
});
</script>

How to associate an event to Html.ActionLink in MVC3

I have made an Ajax function but i am getting a big prolem in that.
I was displaying the contents on click of the link..
The links are fetched from the database and also the url of the links are fetched from the datbase.
I have wriiten ajax to call the contents dynamically on click of the link
<script type="text/javascript">
$(document).ready(function () {
$('a').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
});
});
</script>
Now FetchUrlByHobbyName is the function called from the Controller thart returns the url
//Ajax routine to fetch the hobbyinfo by hobbyname
[HttpPost]
public ActionResult FetchUrlByHobbyName(string data)
{
HobbyMasters hobbymaster = new HobbyHomeService().FetchHobbyMasterByHobbyName(data);
string url = hobbymaster.InformationUrl;
if (HttpContext.Request.IsAjaxRequest())
return Json(url);
return View();
}
And in my View i have written the link like this:
#foreach (var item in Model)
{
<li >#Html.ActionLink(item.HobbyName, "Hobbies")
</li>
}
i tried this :
#Html.ActionLink(item.HobbyName, "Hobbies", null, new { id = "alink" })
and then calling Ajax on click of 'alink' but with this my ajax function doesnot get called.
Now the problem is the ajax function is getting called on click of every link on the page..
I want to assign a unique Id to it but i am not understanding how to do that
please Help me...
For that specific link, assign an id. E.g
<a id="someID" href="url">Link</a>
and than bind the click only with that link.
$('#someID').click(function (e)) ....
If I understood you correctly this helps you
The text of the link
<script type="text/javascript">
function myAjaxFunction(){
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
</script>
Try to give a css class selector to you action link like this...
#Html.ActionLink("some link", "Create", "Some_Controller", new { }, new { #class = "test" })
then User jquery for it..
<script type="text/javascript">
$(document).ready(function () {
$('.test').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
});
});
</script>

Resources