How to create log-out script - Parse (JavaScript) - javascript

I'm having a problem with logging out on my website. I have looked at the documentation on the parse website but it does not really provide much detail on how to log out the user, also does not help when I am not proficient with JavaScript.
When I click my log out button, it just refreshes the page and nothing more but I would like to take it back to the sign in screen.
My current script file that I have written is shown below (for obvious reasons I have removed my parse unique ids):
$(function() {
Parse.$ = jQuery;
Parse.initialize("MY CODE HERE", "MY CODE HERE");
$('.form-logout').on('submit', function(e) {
// Prevent Default Submit Event
e.preventDefault();
//logout current user
var currentUser = Parse.User.current();
if (currentUser) {
Parse.User.logout();
window.location="Sign_In.html";
} else {
window.location="Sign_In.html";
}
});
});
The section where I create the button is located here in my html file:
<form class="form-logout" role="form">
<input type="submit" value="Logout" id="logout" class="btn btn-primary btn-lg">
</form>

Add
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://www.parsecdn.com/js/parse-1.4.2.min.js"></script>
to your page.
Then use this script:
jQuery(document).ready(function() {
Parse.$ = jQuery;
Parse.initialize("...", "...");
$('.form-logout').on('submit', function (e) {
// Prevent Default Submit Event
e.preventDefault();
console.log("Performing submit");
//logout current user
if ( Parse.User.current() ) {
Parse.User.logOut();
// check if really logged out
if (Parse.User.current())
console.log("Failed to log out!");
}
// do redirect
//window.location.replace("Sign_In.html");
// or
window.location.href = "/Sign_In.html";
});
});

create a function
const handleLogout = () => {
window.localStorage.clear();
window.location.reload(true);
window.location.replace('/');
};
then call it in this way
<Button className="button" onClick={() => handleLogout()}>
<i className="fas fa-power-off"></i>
</Button>

You can self-execute a custom callback function on the logout() object.
That is you first wrap your logout() function within an anonymous function, a syntax like:
function(){logout()}
You self execute it:
(function(){
logout()
})()
and you pass your callback as parameter!
(function(aFunctionIsToBePassedHere){
logout()
})(myCallbackFunction())
All of this become:
function logout() {
(function(myCallbackGoesHereAsVariable) {
Parse.User.logOut();
})(myFunctionToShowTheLoginScreen())
}
and then you bind the logout() function to your form.

Related

Add if and else in javascript function based on other jquery function

I have a jQuery function that will be run when user click a submit button of form is submitted
FUNCTION #1
jQuery(function($){
$('#filter').submit(function() {
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('button').text('Filtering...'); // changing the button label
},
success:function(data){
filter.find('button').text('Filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
I have other script with javascript that run when user click on link with id "link-id".
FUNCTION #2
$div1 = $(".div1");
$div2 = $(".div2");
$div1.hide()
$div2.hide()
function showDiv(){
if(document.getElementById('chk1').checked){
$div1.show()
} else {
$div1.hide()
}
if(document.getElementById('chk2').checked){
$div2.show()
} else {
$div2.hide()
}
}
$('#link-id').on('click', showDiv)
<a id="link-id" class="btn btn-primary" href="javascript: void(0)">Go ahead</a>
I'd like to add and if and else in the FUNCTION #2 that:
if jQuery 'FUNCTION #1' is not submitted (run), javascript 'FUNCTION #2' do something (current code);
if user has already click one time on button to run 'FUNCTION #1', the 'FUNCTION #2' shall do other thing.
I'm not expert with javascript code.
Is there a way to made this check?
If I'm understanding you correctly the two functions are called from different event which means at different times.
If the scripts are linked (by integrating both in the html) or in one:
Then you could add a global variable that changes in function 1 and is being checked in function 2.
Declaration:
let functionOneWasExectuted = false;
In function 1:
functionOneWasExectuted = true;
In function 2:
if (functionOneWasExectuted) {
// code function 1 has been executed before
} else {
// code function 1 has not been executed before
}
If the 2 scripts are not linked in any way let me know and I'll post a different solution :)

Firebase Auth createUserWithEmailAndPassword returns "There is no user record corresponding to this identifier. The user may have been deleted."

Whenever I try to sign up a new user from the UI by calling createUserWithEmailAndPassword method, it returns "E {code: "auth/user-not-found", message: "There is no user record corresponding to this identifier. The user may have been deleted.", a: null}".
Not sure if it tries to sign in instead or if there is some other issue.
Here is my code for the Submit button on the UI:
submit = () => {
const un = document.getElementById('email-input').value;
const pw = document.getElementById('password-input').value;
if (this.pageType === 'login') {
firebase.auth().signInWithEmailAndPassword(un, pw).then(res => {
window.location.href = 'loggedin.html';
console.log(res);
})
} else if (this.pageType === 'signup'){
firebase.auth().createUserWithEmailAndPassword(un, pw).then(un, pw => {
console.log(res);
})
}
Does anyone have any clues?
Thank you!
It seems that the pageType variable is equal to 'login' even at the signup page because the auth/user-not-found error code belongs to the signInWithEmailAndPassword() method. Add a console.log() statement before the if statement to detect this.
submit = () => {
const un = document.getElementById('email-input').value;
const pw = document.getElementById('password-input').value;
// displays 'login' even at sign-up page.
console.log(pageType);
if (this.pageType === 'login') {
firebase.auth().signInWithEmailAndPassword(un, pw).then(res => {
window.location.href = 'loggedin.html';
console.log(res);
})
} else if (this.pageType === 'signup'){
firebase.auth().createUserWithEmailAndPassword(un, pw).then(un, pw => {
console.log(res);
})
}
A more common approach is to have two buttons in the same login page: "Sign Up" and "Sign In" and attach different handler to each button.
e.g. call firebase.auth().createUserWithEmailAndPassword in "Sign Up" button handler and call firebase.auth().signInWithEmailAndPassword in "Sign In" button handler.
Having two pages (login and signup) doesn't simplify your UI. You would still need to link these two pages together in case a user has landed on the wrong page.

How to run a script when a user authenticates Laravel?

I would like to know how to run a function when a user authenticates,
This is my function for log
public function redirectPath()
{
if (Auth::user()->hasRole('admin')){
$bitacora = TblBitacora::create([
'accion' => 'Inicio de Sesión Admin Exitoso',
'user_id' => Auth::id(),
'ip' => \Request::ip(),
]);
return '/';
}
}
I would like to run this script
#if(Auth::user()->??????????????????????????????????????????
<script>
$(function() {
$('#mostrarmodal').modal('show');
});
</script>
#endif
Laravel has Authentication Directives
The #auth and #guest directives may be used to quickly determine if
the current user is authenticated or is a guest:
#auth
// The user is authenticated...
#endauth
#guest
// The user is not authenticated...
#endguest
More information available at https://laravel.com/docs/5.8/blade
Also I wouldn't recommend to log in redirectPath method in your controller. You can use events, an similar to what you want to achieve is provided as an example on Laravel docs. https://laravel.com/docs/5.7/events#event-subscribers
First Question Answer :
You can check is user login in your blade file and add javascript or something like this in your view file :
#if(\Auth::check())
<script>
$(function() {
$('#mostrarmodal').modal('show');
});
</script>
#endif
If Authenticate user is an Admin
#if (auth()->check())
#if (auth()->user()->Admin())
// Put your js files here
#else
// this is for others role
#endif
#endif
Second Question Answer :
If you want to run a function if user is authenticate then you can do it like that :
public function check() {
if(Auth::check()){
$this->secondFunc(); // This will run if user is authenticate.
}
else{
return redirect('auth/login');
}
}
public function secondFunc() {
echo "This is second function";
}
You can use JS localStorage to help you to do it:
#if(\Auth::check())
<script>
if (localStorage.getItem('already_connected') !== '1') {
$('#mostrarmodal').modal('show');
localStorage.setItem('already_connected', 1);
}
</script>
#endif
Now, if you refresh the page, unless you clear localStorage data, it will not show
run this function again.
Hope it helps.

Firebase Update Method Does Not Update Value When Called Multiple Times On Different Nodes But Return OnComplete Successfully

I am Trying To Update the status of Order In My App. When Page Refreshes and I try to Update it, It successfully Update. But When I try to Update Some Other Order, Update Method Return Success on OnComplete Method But Does Not Update Data On Real Time Database.
Its causing me headaches, I have Already Tried All Possible Solutions but nothing worked.
var dbRef = firebase.database();
var requestsRef = dbRef.ref('requests');
var onComplete = function (error) {
if (error) {
console.log('Synchronization failed');
} else {
console.log('Synchronization succeeded');
}
};
function sendToProcessing(e) {
var confirmation = confirm("Really Wanna Send To Processing?");
if (confirmation) {
var key = parseInt($(e).data("key"));
requestsRef.child(key).update({
'status': "Processing"
}, onComplete);
$('#orderDetailsModel').modal("hide")
} else {
return false;
}
}
HTML Part:
<button type="button" class="btn m-2 btn-outline-success " onclick="sendToProcessing(this)" id="btn-processing"><i class="fas fa-utensils"></i></button>
Image Display:
Image Model When Clicked On Eye Button
your are trying to retrieve key using $(e).data("Key"). And in your case e is the button element. The button element doesn't have any attribute called data-key.
Try adding your key to the button as below.
<button type="button" class="btn m-2 btn-outline-success " data-key="keyvalue "onclick="sendToProcessing(this)" id="btn-processing"><i class="fas fa-utensils"></i></button>
Also try debugging your sendToProcessing Method, and try to console.log(key) which might be a null.

how to open view result from action call from javascript

i'm developing using ASP.Net mvc 4. I have a delete function in my Index view. Before user proceed to delete an item, this is the steps to go through
pop-up a confirm dialog to get the 'yes' or 'no' answer using javascript.
If the user say 'yes', I call the delete action from my controller
the delete action remove the item from database
the delete action return 'RedirectToAction ("Index");'
.. suppose the view will be updated with latest update
Step 5 is my problem.. its not working
Here is my code
The delete button
<a href="#Url.Action("DeleteFile", new { id = #item.Id })"
onclick = "return confirm2delete(this);"
class="btn btn-danger btn-sm"
data-toggle="tooltip" title="Delete File">
<i class="fa fa-trash-o"></i>
</a>
The javascript
function confirm2delete(obj)
{
deleteLinkObj = $(this);
w2confirm("Are sure to delete this file ?")
.yes(function () {
$.get(obj.href, function (data) {
alert(data); // i checked ..this return the html page created from the delete action
window.open (data); // not the right approach ???
});
})
.no(function () {
alert("no");
result = false;
});
return false;
}
The delete action in my controller
public ActionResult DeleteFile(int id)
{
FileUpload f = db.FileUploads.Find(id);
try
{
FileInfo dfile = new FileInfo(f.fileUrl);
if (dfile.Exists) { dfile.Delete(); }
fileUrl = f.FileUrl.Replace("Images/Uploads", "Images/Thumbnails");
FileInfo thumbnail= new FileInfo(fileUrl);
if (thumbnail.Exists) { thumbnail.Delete(); }
db.FileUploads.Remove(f);
db.SaveChanges();
}
catch (Exception ex)
{
}
return RedirectToAction("Index"); // or may i should return something else to make it work in javascript ???
}
Hope you guys can help me. I've been searching and trying for days to come to this level and I feel its time get some help. Just a little bit more. Almost there.
Ajax calls stay in the same page, so calling return RedirectToAction("Index"); is pointless (it will not redirect). In any case it is unnecessary to return the new view. Instead you can just remove the existing elements from the DOM if the controller successfully deleted the item. You have not shown your view, but assuming you have a table where a row might be something like
<tr>
<td>the name of the file</td>
<td>the delete link</td>
</td>
Then you can use the following where the 'delete' link is
<td><button type="button" class="delete" data-id="#item.Id">Delete</button></td>
The key points are the class and the data-id attributes - modify the rest to suit your display but remove the onclick attribute (stop polluting you markup with behavior and use unobtrusive javascript - its the 21st century!)
Then the script
var url = '#Url.Action("DeleteFile")';
$('.delete').click(function() {
var id = $(this).data('id');
var row = $(this).closest('tr'); // modify if the containing element is not a <tr>
w2confirm("Are sure to delete this file ?")
.yes(function () {
$.post(url, { id: id }, function(response) { // its a POST, not a GET!
if (response) {
row.remove(); // remove the row
} else {
// Oops, something went wrong
}
}).fail(function (response) {
// Oops, something went wrong
});
})
.no(function() {
alert("no");
});
});
Note if your using jquery version 1.9+ then the else block in the $.post() functuion is not required since return Json(null); in the method below will go to the .fail() callback
Then in the controller, return json to indicate the item was successfully deleted
[HttpPost]
public ActionResult DeleteFile(int id)
{
FileUpload f = db.FileUploads.Find(id);
try
{
....
db.SaveChanges();
return Json(true); // signal success
}
catch (Exception ex)
{
return Json(null); // signal failure
}
}

Categories