I'm trying to create a page named 'list of users' where I have a sweetalert with input text form and user enters a name in sweetalert and then using a POST method like a form to redirect to mywebsite.com/search and show results with that name.
Sweetalert is putted on homepage.
<script>
function searchp()
{
Swal({
title: 'Search',
input: 'text',
inputPlaceholder: 'enter_name',
inputAttributes: {
autocapitalize: 'off'
},
showCancelButton: true,
confirmButtonText: 'Search',
confirmButtonColor: '#ffffff',
cancelButtonColor: '#d33'
}).then(result => {
if (result.value) {
$.ajax({
type: "POST",
url: '<?php echo base_url("search"); ?>',
data: {
//here 1
},
success: function(data)
{
//here 2
}
});
} else {
Swal(
'Ops!',
'You canceled.',
'error'
)
}
})
}
</script>
As you saw I don't know how to apply POST method on ''. I'm using Codeigniter 3 as php framework.
is equal to mywebsite.com/search.
I want after a user entered name in input form and pressed submit to apply post method on search page and show results there. The backend for search page is already made and is working with a normal tag.
Hey if you want to redirect the page then you don't need ajax request at all. First get the input value and then use it as a parameter in your wanted URL. I've created a demo, see if this works for you. ↓↓
function searchp() {
Swal.fire({
title: 'Search',
input: 'text',
inputPlaceholder: 'Enter Name',
inputAttributes: {
autocapitalize: 'off'
},
showCancelButton: true,
confirmButtonText: 'Search',
//confirmButtonColor: '#eee',
cancelButtonColor: '#d33',
preConfirm: (data) => {
if (data != "") {
// window.location = '<?php echo base_url('search')?>' + data;
// or(whichever works for you)
// window.location = '<?php echo base_url('search')?>' + '/' + data;
console.log(`Your name: ${data}`)
} else {
Swal.showValidationMessage(`Please enter name`)
}
},
})
}
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#9.10.12/dist/sweetalert2.all.min.js"></script>
<button onclick="searchp()" >Fire Sweet Alert</button>
Related
This question already has an answer here:
Display Successful Message Notifications at Sweetalert
(1 answer)
Closed 4 years ago.
I want to display the message "successfully deleting data" with Sweet alert, and the beginning of the script:
Delete
javascript :
jQuery(document).ready(function($) {
$('.delete-link').on('click', function() {
var getLink = $(this).attr('href');
swal({
title: 'Alert',
text: 'Delete?',
html: true,
confirmButtonColor: '#d9534f',
showCancelButton: true,
}, function() {
window.location.href = getLink
});
return false;
});
});
The data has been successfully deleted, but the way i want to display the data message has been deleted like this, where is it put in?
swal("Success!", "Successfully Deleted Data!", "success");
I don't know much about Sweetalert but as far as I guess the 2nd parameter of the swal function is confirm action!!
So you can delete this using jquery ajax after confirming true:
jQuery(document).ready(function($) {
$('.delete-link').on('click', function() {
var getLink = $(this).attr('href');
swal({
title: 'Alert',
text: 'Delete?',
html: true,
confirmButtonColor: '#d9534f',
showCancelButton: true,
}, function() {
// window.location.href = getLink // no redirection or page reload
$.ajax({
url: getLink, // link where your href is
success: function(result) {
swal('Successful!!', 'Successfully deleted!!'); //sweet alert
}
});
});
return false;
});
});
I Have Used The Sweet Alert For Delete using AJAX, And I set Page redirection after Deleteing. Whenever I Click delete, It asks Confirm or not buttons,
If i click Yes-Confirm it will delete,and the Page Was Redirected. I Want
like After deleteing success message "OK Successfully Deleted" That time only page Was Refreshed,
function delete_confirm(id) {
swal({
title: "Are you sure?",
text: "You will not be able to recover this Product Attribute!",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes, delete it!',
cancelButtonText: "No, cancel please!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
$.ajax({
url: "cart-delete.php",
type: "POST",
data: {
id: id,
},
success: function(data) {
console.log(data);
swal("Done!", "It was succesfully deleted!", "success");
$('[remove_attr_' + id + ']').parents('.demo-card-wide').remove();
window.location.href = 'add-to-cart.php';
}
});
} else {
swal("Cancelled", "Your Product Attribute! is safe :)", "error");
}
});
};
Remove this line On Success
window.location.href = 'add-to-cart.php';
Write in some other action
ex. On sweet alert close action
Hello I have a code using sweetalert
swal("Good job!", "You clicked the button!", "success")
this code will pop-up a message and has a button okay, what I like to do is I want to refresh the page after I click the okay button.
Can I do that?
You can try this, it works for me.
swal({
title: "Good job",
text: "You clicked the button!",
type: "success"
},
function(){
location.reload();
}
);
The answer from Yoshioka did not work for me, I did this and it worked perfectly:
swal({title: "Good job", text: "You clicked the button!", type:
"success"}).then(function(){
location.reload();
}
);
Use the callback function...
Swal.fire({
// Swal Setting's
}).then((result) => {
// Reload the Page
location.reload();
});
For Sweet Alert 2, this will work.
swal("Good job!", "You clicked the button!", "success").then(function(){
location.reload();
});
As you can see migration guide
Sweet Alert 2 uses Promise
You can check confirm by this:
swal({
title: "Good job",
text: "You clicked the button!",
icon: "success",
buttons: [
'NO',
'YES'
],
}).then(function(isConfirm) {
if (isConfirm) {
location.reload();
} else {
//if no clicked => do something else
}
});
I use sweet alert 2 and this works for me
swal("Good job!", "You clicked the button!","success").then( () => {
location.href = 'somepage.html'
})
‘’’
The answers making use of location.reload() is going to trigger your form to attempt to resubmit over and over again, thats why you should use location.href instead.
In Sweet Alert 2, there is callback function where you can implement your logic :
Swal.fire({
title: 'Great job',
text: "You clicked the button!",
type: 'success',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes'
}).then((result) => {
if(result){
// Do Stuff here for success
location.reload();
}else{
// something other stuff
}
})
You can find the reference on SweetAlert2.
Swal.fire(
{
title: "Good job",
text: "You clicked the button!",
type: "success",
showDenyButton: true, // In case you want two scenarios
denyButtonText: 'ABC',
showCancelButton: true, // In case you want two scenarios
cancelButtonText:'XYZ'
}
).then(function (result) {
if (result.isConfirmed) {
//You can add code here if user pressed ok button
} else if (result.isDenied) {
//You can add code here if user pressed deny button
} else if(result.isDismissed) {
//You can add code here if user pressed cancel button
}
)
this worked for me.
Swal.fire('Deleted !!', data.message, 'success').then(() => {
location.reload();
});
swal({
title: "Process Completed",
text: "Data Recorded successfully",
buttons: true
}).then(function(){
location.reload();
});
i solved it with this :
swal({title: "Updated!", text: "yourText", type: "success"},function() {
location.reload();
}) // swal end
Another way :
swal("Updated!","yourText","success",function() {
location.reload();
}) // swal end
I am developing a WordPress shot-code plugin.
i have added a listbox in TinyMCE and i need to load data to TinyMCE from wordpress database. i can not hard code the listbox values since all my shortcodes values are saved in wordpress database.
is there any possible way to do this ?
(function() {
tinymce.PluginManager.add('AP_tc_button', function( editor, url ) {
editor.addButton( 'AP_tc_button', {
text: 'My test button',
icon: 'wp_code',
onclick: function() {
editor.windowManager.open( {
title: 'Select Your AD',
body: [
{
type: 'listbox',
name: 'level',
label: 'Header level',
values: getValues()
}],
onsubmit: function( e ) {
editor.insertContent('dd');
}
});
}
});
});
})();
function getValues() {
//Set new values to myKeyValueList (i need this values get from the db)
tinyMCE.activeEditor.settings.myKeyValueList = [{text: 'newtext', value: 'newvalue'}];
return tinyMCE.activeEditor.settings.myKeyValueList;
}
if it helps someone who visit this post.
My solution was retrieving the data through a ajax request. The trick is doing a synchronous request (async: false).
function getValues() {
var data = {'action': 'getValuesAjax'};
var q = jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: data,
async: false,
dataType: 'json'
});
var values = q.responseJSON;
return values;
}
I've created a form using a bit of jquery, ajax and php.
The ajax, validation and php processing works well.
I came up with the following code to hide my form after submitting, but I don't know if this is the good way to do that. I would like your advise.
Below the js script with the ajax call
<script type="text/javascript">
$(document).ready(function(){
$("#submitContact").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'form/process.php',
data: $("#contact_form").serialize(),
success: function(response) {
$("#formstatus").hide().html(response).slideToggle(600);
}
});
});
});
</script>
The above code will call the php to validate and populates the div#formstatus to notify the user if the form is sent or not.
Within my process.php, I will hide the form if there are no errors found using echo js script.
// If no errors found echo succes message
if (!($formerrors)) :
//Hide the form
echo '<script type="text/javascript">
$(document).ready(function(){
$("#contact_form").hide();
});
</script>';
// display success message
echo '<div>
Your message has been sent. <br />
Thank you for contacting us!
</div>';
Etc....
To sum up:
Should I use this method to hide my form? (Because it does work)
Note. I'm new to jquery and ajax :)
I think it would be better to return a JSON object which contains the information relevant to the request.
For example:
if (!($formerrors)){
echo json_encode(array(
'success'=> true,
'message'=> 'Your message has been sent. <br> Thank you for contacting us!'
));
}
else{
echo json_encode(array(
'success'=> false,
'message'=> 'Error processing form',
'errors'=> array(
'phone'> 'A phone number is required'
)
));
}
This will be easy to work with on the client side (jQuery will automatically parse the json)
<script type="text/javascript">
$(document).ready(function(){
$("#submitContact").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'form/process.php',
data: $("#contact_form").serialize(),
success: function(response) {
if(response.success){
$("#formstatus").hide().text(response.message).slideToggle(600);
}
else{
jQuery.each(response.errors,function(){ ... });
}
}
});
});
});
I think you'll find you have more manageable code if you separate display concerns from functional concerns. For php I agree with Walkerneo.
Javascript AJAX Success Handler
success: function(response) {
var response = $.parseJSON(response);
if(response.status === 'true') {
$("#formstatus").hide().html(response.message).slideToggle(600);
$("#contact_form").hide();
} else {
$("#formstatus").hide().html(response.message).slideToggle(600);
}
}
PHP
if(!$formerrors) {
exit(json_encode(array('status' => 'true', 'message' => 'Your message has been sent. \n Thank you for contacting us!')));
} else {
$message = '<p class="error">' . implode('</p><p>', $formerrors) . '</p>';
exit(json_encode(array('status' => 'false', 'message' => $message)));
}
I recommend avoiding this method. You should instead return information about the status and message to display to the user. For example, here's how you can do it without reloading the page.
demo (non-blank data will be accepted)
We prevent the default event, so that the page doesn't reload. Because of the below HTML changes, we also can make or code more general.
$('form').submit(function(e){
e.preventDefault();
var $this = $(this);
$.ajax({
cache: false,
type: 'POST',
url: 'URLHERE',
data: $(this).serialize(),
dataType: 'jsonp',
success: function(response) {
We display the error or success message here. Depending on the status field, we make the text green or red, and decide whether to hide the form or not.
$("#formstatus").hide().text(response.msg).show(600);
if (response.status === "success") {
$this.hide();
$("#formstatus").css({color: "green"});
}
else {
$("#formstatus").css({color: "red"});
}
}
});
return false;
});
Our PHP simply returns a JSON object.
function callback($data){
$json = json_encode($data);
return $json;
}
if ($valid === true) {
echo callback(
array(
"msg" => "Your message has been sent.\nThank you for contacting us!",
"status" => "success"
)
);
}
else {
echo callback(
array(
"msg" => "Please fill in all fields.",
"status" => "error"
)
);
}
The HTML is also changed to use a submit button, which allows us to target the form instead of the button. The code may now be transported more easily.
<div id="formstatus"></div>
<form>
<input placeholder="First Name" name="name">
<input placeholder="Email" name="email">
<input placeholder="Comment" name="comment">
<input type="submit">
</form>