confirm message when onclick - javascript

I want to ask confirm message when onclick
Here is my code:
$('#activate').click(function() {
var url='<?php echo getStoreURL($_REQUEST['key']); ?>admin/email_tracker.php';
var key='<?php echo $data['api_key'];?>'
$.post(url, { key:key, activate:1 } );
alert('Store activated');
location.reload(true);
});
Here I need an alert box are you sure you want to active?. How to do it?. Thanks

Try this,
$('#activate').click(function() {
var url='<?php echo getStoreURL($_REQUEST['key']); ?>admin/email_tracker.php';
var key='<?php echo $data['api_key'];?>'
if(!confirm("Your message")){ return; }
$.post(url, { key:key, activate:1 } );
alert('Store activated');
location.reload(true);
});
PROCEDURAL DEMO

Try this:
$('#activate').click(function() {
var Confirm = confirm("Are you sure?");
if (Confirm == true) {
//put your function here
}
});

Related

$("#signInModal").modal('hide'); not a function

I trying to hide modal after login success by call ajax
But I cannot use $("#signInModal").modal('hide'); ($().modal is not a function. i don't understand how it work, I use bootstrap 4 's modal. How can l use this or the other way to hide modal ##
i really use it ontop, and I cannot use it again.Please help me ##
here is my code
$("#signUpButton").on('click', function () {
$("#signInModal").modal('hide');
})
})(jQuery);
// //validate password on login event
(function ($) {
$(document).ready(function(){
$("#login").submit(function(event){
event.preventDefault();
var txtUsername = $("#exampleInputEmail1");
var txtPassword = $("#logInPassword");
var username=txtUsername.val().trim();
var password=txtPassword.val().trim();
console.log(username);
console.log(password);
if( username != "" && password != "" ){
$.ajax({
url:'login.php',
type:'Post',
data:{username:username,password:password},
success:function(response){
var msg = "";
console.log(response);
if(response == 1){
$("#signInModal").modal('hide');
console.log(response);
}else{
msg = "Invalid username and password!";
}
if (!strIsEmpty(msg)) {
console.log(msg);
return;
}
}
});
}
});
});
})(jQuery);
I think you included js in the footer of the page. Please call the function after it.

AJAX returns whole web page after 2nd form submit - JQuery

My code works as expected the first time the form submits. I'm forcing an error by entering wrong credentials, it shows an error, all fine. After doing so it should log me in if I enter the correct credentials the second time the form submits. The problem is, data in my AJAX call contains the whole web page instead of a JSON string after submitting for the second time.
I'm using the following code (JS):
$(document).ready(function() {
$('form').submit(function(event) {
var $u = $('#rnumber').val(),
$p = $('#password').val(),
$t = $('#token').val(),
$s = $('#source').val(),
$key = false;
var $r = $('#remember:checked').length > 0;
if(!$u) {
// Add Error
$('#alert_error').show();
$('#login_error').text('Relatienummer is verplicht!');
$key = true;
$('#input_rnumber').addClass('has-error');
// Check if input has been filled
$( "#rnumber" ).keyup(function() {
$('#input_rnumber').removeClass('has-error');
$('#alert_error').hide();
$key = false;
});
} else if(!$p) {
$('#alert_error').show();
$('#login_error').text('Wachtwoord is verplicht!');
$key = true;
$('#input_pass').addClass('has-error');
// Check if input has been filled
$( "#password" ).keyup(function() {
$('#input_pass').removeClass('has-error');
$('#alert_error').hide();
$key = false;
});
}
if(!$s) {
$s = null;
}
event.preventDefault(event);
if($key == false) {
$.ajax({
url: '/cp/login.php',
data: {u: $u, p: $p, t: $t, r: $r, s: $s},
type: 'post',
success: function(data) {
console.log(data);
data = data.substring(data.indexOf("{"));
var json = JSON.parse(data);
console.log(json);
if(json.Error == 'Login') {
$('#alert_error').show();
$('#login_error').text(json.Message);
$('#password').val("");
// Check if input has been filled
$( "#password" ).keyup(function() {
$('#alert_error').hide();
});
} else if(json.Error == 'Membership') {
$('#alert_error').show();
$('#login_error').html(json.Message);
$('#password').val("");
} else if(json.Redirect) {
$('#loading').show();
var counter = 5;
var interval = setInterval(function() {
counter--;
$('#loading_text').html('<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> Je word doorgestuurd in ' + counter + ' seconden.');
if (counter == 5) {
clearInterval(interval);
}
}, 1000);
setTimeout(function(){
window.location.replace("http://" + document.location.hostname + "/" + json.Redirect);
}, 5000);
} else if(json.Success == 'Dashboard') {
$('#loading').show();
$('#loading_text').html('<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> Je word ingelogd...');
setTimeout(function(){
window.location.replace("dashboard");
}, 2000);
} else if(json.Success == 'Admin') {
$('#loading').show();
$('#loading_text').html('<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> Je word ingelogd...');
setTimeout(function(){
window.location.replace("http://" + document.location.hostname + '/admin/');
}, 2000);
} else if(json.Success == 'Company') {
$('#loading').show();
$('#loading_text').html('<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i> Je word ingelogd...');
setTimeout(function(){
window.location.replace("http://" + document.location.hostname + '/company/dashboard');
}, 2000);
}
}
});
}
});
});
Login.php:
if(isset($_POST['u']) && isset($_POST['p']) && isset($_POST['t']) && isset($_POST['r'])) {
if(Token::check(escape($_POST['t']))) {
$rnumber = escape($_POST['u']);
$pass = escape($_POST['p']);
$remember = escape($_POST['r']);
$source = escape($_POST['s']);
if(substr( $rnumber, 0, 1 ) === "c") {
$c = new Company();
$cInfo = $c->findR($rnumber);
$cInfo = $c->data();
$login = $c->login($rnumber, $pass, $remember);
if($login) {
print json_encode(array("Success"=>"Company"));
exit();
} else {
print json_encode(array("Error"=>"Login", "Message"=>"Er zijn onjuiste inloggegevens ingevoerd! Probeer het opnieuw!"));
exit();
}
}
}
}
UPDATE:
I changed my first if() statement in the success function from AJAX. It currently looks like this:
if(json.Error == 'Login') {
$('#alert_error').show();
$('#login_error').text(json.Message);
$('#password').val("");
console.log('returning false');
return false;
}
After I enter invalid credentials and submit the form for the first time, it shows the error message as expected. It also logs returning false.
When I try entering the correct credentials and submit the form for the second time, it won't do anything.
I also added dataType: 'json' to the AJAX call.
So after putting console.log() at some places in my code, I noticed that when I submit the form for the second time, it does submit the form, and it is firing a AJAX request. It just does not return a new JSON string from PHP.
Please make few changes in your code.
Remove keyup event from submit function and placed it outside.
When there is an error during form submission like validation error then return false(It break the execution process).
Finally managed to get everything working again.
I noticed that the token in my form did not change. This is of course because the page does not refresh.
So, I created a simple javascript function that fires a AJAX request to another PHP file that will change the token to a new valid one.
function token() {
$.ajax({
url: '/cp/_token.php',
data: {token: true},
type: 'post',
success: function(output) {
$('#token').val(output);
}
});
}
if(json.Error == 'Login') {
$('#alert_error').show();
$('#login_error').text(json.Message);
$('#password').val("");
token();
// Check if input has been filled
$( "#password" ).keyup(function() {
$('#alert_error').hide();
return false;
});
}
Thanks everyone who tried to help!

Remove alert from a javascript

I've the below code from a tutorial,i want the action but i just want to remove the alert,
here is the code:
<script type="text/javascript">
setTimeout('read()', 10000);
function read()
{
FB.api('/me/news.reads' +
'?article=<?php echo $fbrdurl ?>&access_token=<?php echo $access_token ?>','post',
function(response) {
var msg = 'Error occured';
if (!response || response.error) {
if (response.error) {
msg += "\n\nType: "+response.error.type+"\n\nMessage: "+response.error.message;
}
alert(msg);
}
else {
alert('Post was successful! Action ID: ' + response.id);
}
});
}
</script>
I've tried this:
<script type="text/javascript">
setTimeout('read()', 10000);
function read()
{
FB.api('/me/news.reads' +
'?article=<?php echo $fbrdurl ?>&access_token=<?php echo $access_token ?>','post';
}
</script>
but not worked, thanks
If what you're trying to do is just to ignore the response (remove the alert dialogs):
function read()
{
FB.api('/me/news.reads' +
'?article=<?php echo $fbrdurl ?>&access_token=<?php echo $access_token ?>','post',
function(response) {});
}
If you're not using the alert() function anywhere else, you can simply override it so it does nothing:
window.alert = function() {};

How to show a confirm message before delete?

I want to get a confirm message on clicking delete (this maybe a button or an image). If the user selects 'Ok' then delete is done, else if 'Cancel' is clicked nothing happens.
I tried echoing this when the button was clicked, but echoing stuff makes my input boxes and text boxes lose their styles and design.
Write this in onclick event of the button:
var result = confirm("Want to delete?");
if (result) {
//Logic to delete the item
}
You can better use as follows
Delete
This is how you would do it with unobtrusive JavaScript and the confirm message being hold in the HTML.
Delete
This is pure vanilla JS, compatible with IE 9+:
var deleteLinks = document.querySelectorAll('.delete');
for (var i = 0; i < deleteLinks.length; i++) {
deleteLinks[i].addEventListener('click', function(event) {
event.preventDefault();
var choice = confirm(this.getAttribute('data-confirm'));
if (choice) {
window.location.href = this.getAttribute('href');
}
});
}
See it in action: http://codepen.io/anon/pen/NqdKZq
function ConfirmDelete()
{
return confirm("Are you sure you want to delete?");
}
<input type="button" onclick="ConfirmDelete()">
it is very simple and one line of code
Delete
Try this. It works for me
Remove
improving on user1697128 (because I cant yet comment on it)
<script>
function ConfirmDelete()
{
return confirm("Are you sure you want to delete?");
}
</script>
<button Onclick="return ConfirmDelete();" type="submit" name="actiondelete" value="1"><img src="images/action_delete.png" alt="Delete"></button>
will cancel form submission if cancel is pressed
I would like to offer the way I do this:
<form action="/route" method="POST">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="the_token">
<button type="submit" class="btn btn-link" onclick="if (!confirm('Are you sure?')) { return false }"><span>Delete</span></button>
</form>
It can be simplify to this:
<button onclick="return confirm('Are you sure you want to delete?');" />
HTML
<input onclick="return myConfirm();" type="submit" name="deleteYear" class="btn btn-danger" value="Delete">
Javascript
<script>
function myConfirm() {
var result = confirm("Want to delete?");
if (result==true) {
return true;
} else {
return false;
}
}
If you are interested in some quick pretty solution with css format done, you can use SweetAlert
$(function(){
$(".delete").click(function(){
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}).then(isConfirmed => {
if(isConfirmed) {
$(".file").addClass("isDeleted");
swal("Deleted!", "Your imaginary file has been deleted.", "success");
}
});
});
});
html { zoom: 0.7 } /* little "hack" to make example visible in stackoverflow snippet preview */
body > p { font-size: 32px }
.delete { cursor: pointer; color: #00A }
.isDeleted { text-decoration:line-through }
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<link rel="stylesheet" href="http://t4t5.github.io/sweetalert/dist/sweetalert.css">
<p class="file">File 1 <span class="delete">(delete)</span></p>
HTML:
Delete
Using jQuery:
$('.delete').on("click", function (e) {
e.preventDefault();
var choice = confirm($(this).attr('data-confirm'));
if (choice) {
window.location.href = $(this).attr('href');
}
});
<form onsubmit="return confirm('Are you sure?');" />
works well for forms. Form-specific question: JavaScript Form Submit - Confirm or Cancel Submission Dialog Box
Delete Product
<!-- language: lang-js -->
<script>
function del_product(id){
$('.process').css('display','block');
$('.process').html('<img src="./images/loading.gif">');
$.ajax({
'url':'./process.php?action=del_product&id='+id,
'type':"post",
success: function(result){
info=JSON.parse(result);
if(result.status==1){
setTimeout(function(){
$('.process').hide();
$('.tr_'+id).hide();
},3000);
setTimeout(function(){
$('.process').html(result.notice);
},1000);
} else if(result.status==0){
setTimeout(function(){
$('.process').hide();
},3000);
setTimeout(function(){
$('.process').html(result.notice);
},1000);
}
}
});
}
</script>
Practice
<form name=myform>
<input type=button value="Try it now"
onClick="if(confirm('Format the hard disk?'))
alert('You are very brave!');
else alert('A wise decision!')">
</form>
Web Original:
http://www.javascripter.net/faq/confirm.htm
to set a conformation message when you delete something in php & mysql...
use this script code:
<script>
function Conform_Delete()
{
return conform("Are You Sure Want to Delete?");
}
</script>
use this html code:
<a onclick="return Conform_Delete()" href="#">delete</a>
var txt;
var r = confirm("Press a button!");
if (r == true) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
var txt;
var r = confirm("Press a button!");
if (r == true) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
function confirmDelete()
{
var r=confirm("Are you sure you want to delte this image");
if (r==true)
{
//User Pressed okay. Delete
}
else
{
//user pressed cancel. Do nothing
}
}
<img src="deleteicon.png" onclick="confirmDelete()">
You might want to pass some data with confirmDelete to determine which entry is to be deleted
Using jQuery:
$(".delete-link").on("click", null, function(){
return confirm("Are you sure?");
});
I know this is old, but I needed an answer and non of these but alpesh's answer worked for me and wanted to share with people that might had the same problem.
<script>
function confirmDelete(url) {
if (confirm("Are you sure you want to delete this?")) {
window.open(url);
} else {
false;
}
}
</script>
Normal version:
<input type="button" name="delete" value="Delete" onClick="confirmDelete('delete.php?id=123&title=Hello')">
My PHP version:
$deleteUrl = "delete.php?id=" .$id. "&title=" .$title;
echo "<input type=\"button\" name=\"delete\" value=\"Delete\" onClick=\"confirmDelete('" .$deleteUrl. "')\"/>";
This might not be the correct way of doing it publicly but this worked for me on a private site. :)
Its very simple
function archiveRemove(any) {
var click = $(any);
var id = click.attr("id");
swal.fire({
title: 'Are you sure !',
text: "?????",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'yes!',
cancelButtonText: 'no'
}).then(function (success) {
if (success) {
$('a[id="' + id + '"]').parents(".archiveItem").submit();
}
})
}
function del_confirm(msg,url)
{
if(confirm(msg))
{
window.location.href=url
}
else
{
false;
}
}
<a onclick="del_confirm('Are you Sure want to delete this record?','<filename>.php?action=delete&id=<?<id> >')"href="#"></a>
<SCRIPT LANGUAGE="javascript">
function Del()
{
var r=confirm("Are you sure?")
if(r==true){return href;}else{return false;}
}
</SCRIPT>
your link for it:
<a href='edit_post.php?id=$myrow[id]'> Delete</a>
The onclick handler should return false after the function call. For eg.
onclick="ConfirmDelete(); return false;">
I think the simplest unobtrusive solution would be:
Link:
Delete
Javascript:
$('.delete').click(function () {
return confirm("Are you sure?");
});
Delete Product
function del_product(id){
$('.process').css('display','block');
$('.process').html('<img src="./images/loading.gif">');
$.ajax({
'url':'./process.php?action=del_product&id='+id,
'type':"post",
success: function(result){
info=JSON.parse(result);
if(result.status==1){
setTimeout(function(){
$('.process').hide();
$('.tr_'+id).hide();
},3000);
setTimeout(function(){
$('.process').html(result.notice);
},1000);
}else if(result.status==0){
setTimeout(function(){
$('.process').hide();
},3000);
setTimeout(function(){
$('.process').html(result.notice);
},1000);
}
}
});
}
Here is another simple example in pure JS using className and binding event to it.
var eraseable = document.getElementsByClassName("eraseable");
for (var i = 0; i < eraseable.length; i++) {
eraseable[i].addEventListener('click', delFunction, false); //bind delFunction on click to eraseables
}
function delFunction(){
var msg = confirm("Are you sure?");
if (msg == true) {
this.remove(); //remove the clicked element if confirmed
}
};
<button class="eraseable">
<img class="eraseable" src="http://zelcs.com/wp-content/uploads/2013/02/stackoverflow-logo-dumpster.jpg" style="width:100px;height:auto;">
Delete me</button>
<button class="eraseable">
<img class="eraseable" src="http://zelcs.com/wp-content/uploads/2013/02/stackoverflow-logo-dumpster.jpg" style="width:100px;height:auto;">
Delete me</button>
<button class="eraseable">
<img class="eraseable" src="http://zelcs.com/wp-content/uploads/2013/02/stackoverflow-logo-dumpster.jpg" style="width:100px;height:auto;">
Delete me</button>
<script>
function deleteItem()
{
var resp = confirm("Do you want to delete this item???");
if (resp == true) {
//do something
}
else {
//do something
}
}
</script>
call this function using onClick
For "confirmation message on delete" use:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Searching.aspx/Delete_Student_Data",
data: "{'StudentID': '" + studentID + "'}",
dataType: "json",
success: function (data) {
alert("Delete StudentID Successfully");
return true;
}
Angularjs With Javascript Delete Example
html code
<button ng-click="ConfirmDelete(single_play.play_id)" type="submit" name="actiondelete" value="1"><img src="images/remove.png" alt="Delete"></button>
"single_play.play_id" is any angularjs variable suppose you want to pass any parameter during the delete action
Angularjs code inside the app module
$scope.ConfirmDelete = function(yy)
{
var x = confirm("Are you sure you want to delete?");
if (x) {
// Action for press ok
$http({
method : 'POST',
url : 'sample.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({ delete_play_id : yy})
}).then(function (response) {
$scope.message = response.data;
});
}
else {
//Action for cancel
return false;
}
}

jquery return false in form

<script LANGUAGE="JavaScript">
function confirmSubmit() {
jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog', function(r) {
if(r) {
return true;
} else {
return false;
}
});
}
</script>
<form name='cancel_form'id='cancel_form' method='POST' action="">
<center>
<input type='submit' name='confirm_appointment' value='Cancel Appointment' onclick='return confirmSubmit();'>
</center>
</form>
<script type='text/javascript'>
var ajax_load = "<img class='loading' src='img/load.gif' alt='loading...' />";
var saveUrl = "<?php echo $this->url(array('controller' => 'appointment', 'action' =>'cancelsave'));?>";
$('#cancel_form').ajaxForm({ success: saveCallbk , url : saveUrl });
function saveCallbk(responseText) {
jAlert(responseText,'Alert Dialog');
if(responseText.indexOf("ERROR")<0) {
$(location).attr('href',redirectUrl);
}
}
</script>
When I submit the form I call this function and use jConfirm from jQuery. I print r. It's printing properly (e.g. true and false), but return false or return true has no effect -- it just shows the pop up and submits the form, and does not wait for confirmation. How to solve this?
The ajaxForm plugin takes care of the submission by itself and it needs a submit button. If I use:
function confirmSubmit() {
var agree=confirm("Is the Appointment Cancelled?");
if (agree) {
return true;
} else {
return false;
}
}
like default javascript it works well
Use type="button" instead of type="submit" and attach this on the click event of your form button.
$('#button').click(function () {
jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog', function(r) {
if (r) {
$('#form').submit();
}
});
});
What Ivo said.
Your function confirmSubmit should return true or false.
Edit -
I am not familiar with jConfirm, but you may need to return the results from jConfirm, like this.
<script>
function confirmSubmit()
{
return jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog',
function(r) {
if(r){return true;} else {return false;}
});
}
</script>
if this is the case, you could do away with confirmSubmit() altogether and just say:
$('#form').submit(function() {
return jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog', function(r) { return r; } );
});
Hope this helps...
Dang that Ivo is GOOD :-) Personally, i do what Ivo has demonstrated. Create an input of type="button", then delegate a click function.
This is how I cancel submit events using JavaScript and jQuery:
First I have a utility function called cancelEvent: (Which I picked up from this blog entry.)
function cancelEvent(e)
{
e = e ? e : window.event;
if(e.stopPropagation)
e.stopPropagation();
if(e.preventDefault)
e.preventDefault();
e.cancelBubble = true;
e.cancel = true;
e.returnValue = false;
return false;
}
Then I'll have the main JavaScript file that will contain code something like this:
function validateForm(e)
{
var validated = true;
/*
Validation code goes here.
If validation fails set validated to false
*/
//If validation fails then at the end I'll want to cancel the submit event
if(validated)
{
return true;
}
return cancelEvent(e);
}
jQuery(document).ready(function()
{
jQuery("#theForm").submit(validateForm);
}

Categories