Javascript confirm() still executes action when cancel is clicked. :( - javascript

<script type="text/javascript">
confirm("Delete user?.");
window.location.href = "users.php";
</script>
$qqq = mysql_query("DELETE from users WHERE panelistname='$theuser'") or die(mysql_error())
considering the code above, (inside a php file, so no worries with certain syntax errors you might notice) the problem here is that when click cancel on the confirm() dialog box that will show up. the delete action still executes. This question might be considered a double since, yeah, I found some questions relevant to this one but I just can't fixed this one myself.
the one I found codes it something like this:
"if (confirm('Are you...?')) commentDelete(1); return false"
I can't find a way to solve this problem, I don't know which part should I insert the SQL command(delete) in this format. Please someone show me how to do this right. :) thanks!

EDIT: I just saw that Nick Zuber posted a similar answer around 1 minute before I posted mine (actually, while I was writing it :P)
I don't clearly understand what you are trying to do.
You want to show the user a confirm window, and if they click Yes, delete some entry in the database, and if they click No, redirect them to the page 'users.php' ?
If it's what you want to do, then you can't do it like this. You can't use JS conditions with PHP. The PHP code is executed server-side (in the server), whereas the JS code is executed client-side (in the browser). What you would need is to do something like this:
warning: don't use this code, it's unsecure and shouldn't ever be used in a real app, it's just to show you how the whole thing works
(IN USERS.PHP)
if(isset($_GET['delete_dat_user']))
{
$qqq = mysql_query("DELETE from users WHERE panelistname='" . $_GET['delete_dat_user'] . "'") or die(mysql_error());
}
(IN THE WEBPAGE)
if(confirm('u serious u want to delete the user'))
{
window.location = 'users.php?delete_dat_user=theUserName';
}
else
{
nope
}

When your page loads, the PHP on your page will automatically execute, regardless of your JavaScript. Instead, try to prompt the user if they want to delete the account and if they click yes redirect them to a page that has your PHP query.
Also, the confirm function returns a boolean value depending on which option is clicked by the user. Try putting it in an if statement:
if(confirm("Delete user?.")){
window.location.href = "delete_user_page.php";
}else{
// cancel was clicked
}

Related

How to run a script only once [duplicate]

I don't think this is a very basic question, but I need some help or if you can guide me to a resource I'd appreciate it. I have a script that I would like to run only when the visitor comes for the first time.
<script>
$(document).ready(function(){
$(".posts").hide();
$("#header").hide();
$("#body").hide();
$("#footer").hide();
$("#intro").click(function(){
$(".posts").show(3000);
$("#header").show(3000);
$("#body").fadeIn(3000);
$("#footer").show(3000);
$("#intro").hide();
$("p").hide();
});
});
How do I go about this? The visitor enters my site and everything is hidden, then they press a button and it shows everything in a cool way. I do not want to run this script again after visitor returns back to home page from some other page on the website. Any ideas on how this can be done? I am using javascript with jquery.
Thanks in advance.
UPDATE: Thank you Emeeus and Chiran K. for helping me. This is the code and it works fine. For first time visitor, we enter if-block, first time visitor clicks button and enters site. When visitor goes back to home page, it goes to else block, and hides what I want.
$(document).ready(function(){
if(!localStorage.getItem("firstTime")){
$(".posts").hide();
$("#header").hide();
$("#body").hide();
$("#footer").hide();
$("#start").click(function(){$(".posts").show(3000); $("#header").show(3000); $("#body").fadeIn(3000); $("#footer").show(3000);$("#start").hide(); $("p").hide(); });
localStorage.setItem("firstTime","true");
} else {
$("#start").hide();
$("p").hide();
}
});
I think this should work
if(!localStorage.getItem("firstTime")){
//code executed first time
localStorage.setItem("firstTime","true");
}else{
//code executed 2th 3th etc.
}
That could be executed after some event, like click or onload. Keep in mind that you could store whatever you want with localStorage.
There are multiple ways to achieve this depending on your exact requirement.
If you want to handle it once per session, then you can have a session variable and handle it.
If you want to handle it once per user agent, then you can use either local storage or cookies to handle it.
refer this for more info.

Define a reference site for the history.back button

We want to have a back button in our site
but history.back in javascript does not help us.
We need this function only run on the site and if the user comes from other site, clicking the return button on the previous site should not return.
In fact, we want a return button to run on our site only.
my code is
<i class="fas fa-arrow-left"></i><span class="btn-text">Back</span>
This only works for your own made back button and won't work with the browser back button
There is two ways to achieve that: a simple but not always reliable method and a complex one but always good.
1- The simple method
You use document.referrer and ensure the domain is yours before calling history.back().
2- The complex method
You could register a JavaScript function on page load to get the first URL the internaut land which you could store using history.pushState. Before calling the back function, you could ensure this is not that page. Though, this idea is not complete as the user could probably have landed on this page twice. i.e. Home->Product->Home. I'll let you search for further code that would let you counter this problem.
This code checks the history of back button of the browser on its click event:
$('#backbtn').click(function () {
if (document.referrer.includes(window.location.hostname)) {
window.history.back();
} else {
window.location.href = "/your/path";
}
});

Putting javascript for input tag in php function :)

I have a php function which reloads one page in hided iframe before real redirection is done after input button is clicked.
function button_confirm_order_params() {
$url = "somepagetoreloadinbackground.php";
$alert = "alert('you will be redirected to ext. page')";
return "onclick=\"document.all.myFrame.src='$url'; $alert;\"";
}
Everything works good, however I would like to use something more beatiful than browser's alert.
Is this possible to put in there any javascript, so I would be able to show a good-looking pop-up? It's all inside >input< tag and I have no idea, how to get this through.
Look up sweet alert: http://t4t5.github.io/sweetalert/
Or one of my favourites toastr: http://codeseven.github.io/toastr/demo.html

Call JavaScript Function On Call Behind of Javascript before redirecting to another page

I have Javascript function which i need to call at code behind in vb.net. The Main problem is it is not called properly because there is redirection to next page before this function executes. I do not want to call this function on Onclick event of button or something like that i want to call it after some specific condition in code behind. I have already tried following solutions please let me know if you have some other suggestions.
System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, Me.GetType(), "Script", "ShowEntryPermForm();", True)
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Window", "ShowEntryPermForm();", True)
Problem Description: added from comment
The scenario is that in javascript function i have checked various conditions related to the project and it open up a pop up window where user enter his or her comments.
It is not necessary every time the function will open the pop up window. But by default the page redirects to new page as both the functions Javascript and redirection to another window are run on click event of the button.
But now my requirement is changed now i have to call the function from code behind in particular condition. Hope you get it now
You can do this in following way.
window.onbeforeunload = function()
{
//your code goes here
return "";
}
If you return anything here then browser will display and ask user whether to leave the page. In your case you don't need to return anything but runs the code.
The only way is to Separate the code and javascript in the way they will not rely on each other
for example you make an hidden asp:button with the rest of server side code
server side :
if(...) then
page.ClientScript.RegisterStartupScript(Me.GetType(), "Window", "ShowEntryPermForm();", True)
else
page.ClientScript.RegisterStartupScript(Me.GetType(), "Window", "otherfunction();", True)
end if
sub IDServersideHiddenbutton(obj as object ,e as eventargs)handles IDServersideHiddenbutton.click
rest of the server side code including the redirect
end sub
client side :
javascript ShowEntryPermForm()
{
// javascript code
$("#IDServersideHiddenbutton").click();
}
javascript otherfunction()
{
//just the click
$("#IDServersideHiddenbutton").click();
}
I really don't know your code structure but You can manipulate it to work with this idea

What's the javascript to only click a link if it exists?

I'm in the SeleniumIDE , but calling out to javascript.
Seems like this would be a fairly common scenario for others too.
I have a good test suite but the first thing it does is login.
I would like the suite to start off be making sure I am logged out and if not, logging me out.
I can tell if I am logged in by the presence of a 'Logout' hyperlink
But I only want to click on logout IF I am currently logged in, otherwise I want to do nothing, as trying to click on a non-existent element would raise an error if I am not already logged in)
So logically this is:
if ui element(logout link in my case) exists
click on logout link
else
do nothing
end
I am using the Selenium IDE and calling javascript - Given that I can't do if then in the basic seleniumIDE I was hoping I could do this in javascript itself.
something like:
store javascript{if ([a with text 'Logout' exists]) then click on it end;} id1
although instead of click on it [this], it would also be ok (though more brittle) if I just visited the url which is
http://my-apps-domain/users/sign_out
but I'm not sure of the exact syntax.
The relevant HTML is:
<li>Logout</li>
If it exists I would like to click on the a (or visit the url directly), otherwise nothing.
I would like to find a non-jquery solution if possible.
Update: I have found that even javascript{window.location.replace('http://google.com') } closes my seleniumIDE window and replaces it with google but doesn't affect the actual window where the tests themselves were running.
Triggering a click event in raw JavaScript can be tricky (check out this answer: https://stackoverflow.com/a/10339248/2386700)
However, if you can also use jQuery, that would simplify things. For example, if the logout button has an id like "logout" then you could do something like this:
var logoutButton = $('#logout');
if (logoutButton != null) {
logoutButton.click();
}
Since you don't have control over the HTML, I suggest referencing the link in another manner. The URL seems very reliable for that purpose:
var logoutLink = document.querySelector('a[href="/users/sign_out"]');
if(logoutLink != null) {
window.location.href = logoutLink.href;
}
You don't need to fire any kind of click event, because page navigation can easily be done with window.location.
UPDATE:
Another idea is to assign your button an id, then click it with selenium:
var logoutLink = document.querySelector('a[href="/users/sign_out"]');
if(logoutLink != null) {
logoutLink.setAttribute("id", "logoutLink");
}

Categories