SweetAlert2 - Dynamic queue without clicking confirm button? - ajax

I am using the latest version of the jQuery plugin SweetAlert2. I want to use the "Dynamic queue"-function to make a AJAX call. So on the homepage there is a nice example, but you have to click a confirm button first to execute the AJAX call. I do not want this, when the alert is shown the AJAX call should execute immediately, without clicking a button. So how to do this?
Here the example from the homepage
swal.queue
([{
title: 'Your public IP',
confirmButtonText: 'Show my public IP',
text: 'Your public IP will be received via AJAX request',
showLoaderOnConfirm: true,
preConfirm: function()
{
return new Promise(function (resolve)
{
$.get('https://api.ipify.org?format=json').done(function(data)
{
swal.insertQueueStep(data.ip);
resolve();
});
});
}
}])

You should pass the callback with the AJAX request to onOpen parameter:
Swal.queue([{
title: 'Your public IP',
confirmButtonText: 'Show my public IP',
text:
'Your public IP will be received ' +
'via AJAX request',
onOpen: () => {
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => {
Swal.insertQueueStep(data.ip)
})
}
}])
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#8"></script>

My working example for auto submit form with sweetalert loading and display results.
var preMessage = $('#new-ad-form').attr('pre-message');
var formData = $('#new-ad-form').serialize();
var formUrl = $('#new-ad-form').attr('action');
Swal.queue([{
allowOutsideClick: false,
allowEscapeKey: false,
title: preMessage,
showConfirmButton: false,
showCloseButton: false,
showCancelButton: false,
onOpen: () => {
Swal.showLoading();
return fetch(formUrl, {
method: 'POST',
body: formData,
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': "application/x-www-form-urlencoded",
}
})
.then(response => response.json())
.then(data => {
Swal.hideLoading();
if (data.status == 'success') {
Swal.update({
allowEscapeKey: false,
allowOutsideClick: false,
showConfirmButton: false,
showCloseButton: false,
showCancelButton: false,
type: 'success',
title: false,
html: data.html
})
} else {
Swal.update({
type: 'error',
title: false,
html: data.html,
allowEscapeKey: true,
allowOutsideClick: true,
showConfirmButton: true,
})
}
})
.catch(() => {
Swal.hideLoading();
Swal.update({
type: 'error',
title: 'Save request error!',
html: false
})
})
}
}]);

Related

double insert in database while submiting form using Ajax in laravel

I'm trying to submit my form with ajax.
So I'm using the following ajax code:
<script>
if ($("#castingform").length > 0) {
$("#castingform").validate({
rules: {
casting_name: {
required: true,
maxlength: 50
},
casting_photo: {
required: true
},
},
messages: {
casting_name: {
required: "Please enter name",
maxlength: "Name should be 50 characters long."
},
casting_photo: {
required: "Please enter photo"
},
},
submitHandler: function(form) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#castingform').on('submit', function(event) {
event.preventDefault();
$.ajax({
url:"{{ url('castings') }}",
method:"POST",
data:new FormData(this),
dataType:'JSON',
contentType: false,
cache: false,
processData: false,
success:function(res) {
$("#createBtn").removeClass("disabled");
$("#createBtn").text("Sign in");
if (res.status == "success") {
$(".result").html("<div class='alert alert-success rounded'><button type='button' class='close' data-dismiss='alert'>×</button>" + res.message+ "</div>");
/* location.reload();*/
} else if(res.status == "failed") {
$(".result").html("<div class='alert alert-danger alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button>" + res.message+ "</div>");
}
}
});
});
}
})
}
</script>
But when I click for the first time on the button submit, the success message doesn't show, and for the second time I get the success message but I find a double insert in the database.
My Controller
EDIT
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'casting_name' => 'required',
'casting_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($validator->passes()) {
$input['casting_photo'] = time().'.'.$request->casting_photo->extension();
$request->casting_photo->move(public_path('castingimages'), $input['casting_photo']);
$data = [
'casting_name' => $request->casting_name,
'casting_photo'=> $input['casting_photo']
];
Casting::create($data);
return response()->json([
"status" => "success",
"message" => "Success! post created."
]);
}
return response()->json([
"status" => "failed",
"message" => "Alert! post not created"
]);
}
I think the problem is in this line submitHandler: function(form) and this line $('#castingform').on('submit', function(event) {, but I don't know how to solve it.

Laravel Datatable delete record with sweetalert dont working

I am using DataTables and Sweetalert but I have a problem, after confirmation in Sweetalert, nothing is deleted and I get 2 errors.
My controller(index & destroy):
public function index(Request $request)
{
if ($request->ajax()) {
$data = User::select('id','firstName')->get();
return Datatables::of($data)
->addColumn('action', 'partials.column')->rawColumns(['action'])
->make(true);
}
return view('admin.users.index');
}
public function destroy($id)
{
User::find($id)->delete();
return response()->json(['success'=>'Item deleted successfully.']);
}
Partials.column(blade)
<td><i class="bx bx-trash mr-1"></i> delete</td>
and js code
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var s, e = [];
0 < $("#users-list-datatable").length && (s = $("#users-list-datatable").DataTable({
order: [[0, "desc"]],
pageLength: 10,
processing: true,
serverSide: false,
language: {
'loadingRecords': ' ',
'processing': '<div class="spinner-border text-light spinner-border-lg"></div>'
},
ajax: "{{ route('admin.users.index')}}",
columns: [
{data: 'id', name: 'id'},
{data: 'firstName', name: 'firstName'},
{data: 'action', name: 'action', orderable: false, searchable: false},
],
}))
});
function deleteConfirmation(id) {
swal({
title: "Delete?",
text: "Please ensure and then confirm!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'DELETE',
url: "{{ route('admin.users.destroy','') }}"+'/'+id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal("Done!", results.message, "success");
} else {
swal("Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
show this errors
DELETE http://127.0.0.1:8000/admin/users/ 405 (Method Not Allowed)
DELETE http://127.0.0.1:8000/admin/users/undefined 500 (Internal
Server Error)
The 405 means that your route isn't accepting that method. You need to check that the route /admin/users is able to use the delete method
Route::delete($uri, $callback);
You can see more on routing at the following page:
https://laravel.com/docs/7.x/routing
However you might also need to clear the route cache with
php artisan route:cache

How prefill/preload images in uppy.io library

I have an article post service, which has an upload form with uppy.io
Everything works great, but I need to edit those articles and their linked images.
How can I prefill already uploaded images to the uppy.io DashBoard?
My actual code:
<div class="DashboardContainer"></div>
<!-- AJAX Uploading for Add Post -->
<script src="https://transloadit.edgly.net/releases/uppy/v1.8.0/uppy.min.js"></script>
<script src="https://transloadit.edgly.net/releases/uppy/locales/v1.11.0/es_ES.min.js"></script>
<script>
const uppy = Uppy.Core({
debug: true,
autoProceed: true,
restrictions: {
maxFileSize: 600000,
maxNumberOfFiles: 10,
minNumberOfFiles: 1,
allowedFileTypes: ['.jpg', '.jpeg', '.png', '.gif']
},
locale: Uppy.locales.es_ES
})
.use(Uppy.Dashboard, {
inline: true,
target: '.DashboardContainer',
replaceTargetContent: true,
showProgressDetails: true,
note: 'Sólo imágenes, hasta 10 fotos, de no más de 800kb',
height: 350,
width: '100%',
metaFields: [{
id: 'name',
name: 'Name',
placeholder: 'Nombre del fichero subido'
},
{
id: 'caption',
name: 'Caption',
placeholder: 'Describe la imagen que estás subiendo'
}
],
browserBackButtonClose: true,
plugins: ['Webcam']
})
.use(Uppy.XHRUpload, {
endpoint: "{{ route('save-image-ajax') }}",
formData: true,
fieldName: 'files[]',
headers: {
'X-CSRF-TOKEN': $('meta[name="token"]').attr('content')
},
})
uppy.on('upload-success', (file, response) => {
response.status // HTTP status code
response.body // extracted response data
// do something with file and response
$('<input>', {
type: 'hidden',
name: 'imageID[]',
value: response.body.imageID
}).appendTo("#add");
})
uppy.on('complete', result => {
console.log('successful files:', result.successful)
console.log('failed files:', result.failed)
})
</script>
The form works great for publishing an article, I just want to edit them, even the linked images.
You can prefill images from url (first converting the remote image into blob):
fetch({{your_image_url}})
.then((response) => response.blob())
.then((blob) => {
uppy.addFile({
name: "image.jpg",
type: blob.type,
data: blob
});
});
And then, set the state of the loaded images to "Completed" to avoid Uppy re upload them:
uppy.getFiles().forEach(file => {
uppy.setFileState(file.id, {
progress: { uploadComplete: true, uploadStarted: false }
})
})
Also, the property "autoProceed" must be false in the Uppy object configuration.
Source: https://github.com/transloadit/uppy/issues/1112#issuecomment-432339569

How to Update image in react native

I was trying to update the user profile but the profile picture only changes ones.To change it each time i had to change the image name each time how to solve it.I have tried to send the request in post method but my api does not support post.I will post my code below.Could some one help me and Thanks in advance.
class ProfileEdit extends Component {
state = {
username: '',
email: '',
about: '',
userInfo: '',
avatarSource: null,
showAlert: false,
showCancelButton: false,
showConfirmButton: false,
};
constructor(props) {
super(props);
this.selectPhotoTapped = this.selectPhotoTapped.bind(this);
}
hideAlert = () => {
this.setState({
showAlert: false
});
};
selectPhotoTapped() {
const options = {
quality: 1.0,
maxWidth: 500,
maxHeight: 500,
storageOptions: {
skipBackup: true,
},
};
ImagePicker.showImagePicker(options, response => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled photo picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
const source = { uri: response.uri }
this.setState({
avatarSource: source,
});
this.upLoadImage(response.uri);
}
});
}
upLoadImage = async (image_uri) => {
const value = await AsyncStorage.getItem('userToken');
//alert(value)
var url = 'http://www.dev.beta.duklr.com:8000/api/v2/profile/';
var b_url = url + value + '/';
let data = new FormData();
data.append('photo', { type: 'image/jpg', uri: image_uri, name: 'profile_image1.jpg' });
data.append('Content-Type', 'image/jpg');
fetch(b_url, {
method: 'PUT',
body: data
}).then((res) => res.json())
.then((res) => {
// alert("response" + JSON.stringify(res));
})
.catch((e) => this.setState({
showAlert: true,
message: e,
showCancelButton: true,
cancelText: 'close',
}))
.done()
}
componentDidMount = async () => {
const value = await AsyncStorage.getItem('userToken');
//alert(value)
var url = 'http://www.dev.beta.duklr.com:8000/api/v2/profile/';
var b_url = url + value + '/';
//alert(value);
return fetch(b_url)
.then(res => res.json())
.then(res => {
this.setState(
{
isLoading: false,
refreshing: false,
userInfo: res,
},
function () { }
);
})
.catch(error => {
this.setState({
showAlert: true,
message: error,
showCancelButton: true,
cancelText: 'close',
})
});
}
onUpdate = async () => {
const value = await AsyncStorage.getItem('userToken');
var url = 'my_api';
var b_url = url + value + '/';
//alert(b_url);
const { email, about, avatarSource } = this.state;
//alert(`${email},${about}`);
fetch(b_url, {
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
about_us: about,
}),
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
showAlert: true,
message: "Saved successfully",
showCancelButton: true,
cancelText: 'close',
})
// this.setState({
// dataSource: responseJson.promptmsg,
// })
})
.catch((error) => {
this.setState({
showAlert: true,
message: error,
showCancelButton: true,
cancelText: 'close',
})
});
}
catch(errors) {
this.setState({
showAlert: true,
message: errors,
showCancelButton: true,
cancelText: 'close',
});
}
render() {
const value_email = this.state.userInfo.email;
const value_about = this.state.userInfo.about_us;
return (
<View style={styles.continer}>
<ScrollView>
<View style={{ alignItems: 'center', padding: 20 }}>
<Avatar
source={this.state.avatarSource}
size="xlarge"
// showEditButton
onPress={this.selectPhotoTapped.bind(this)}
/>
</View>
<View style={styles.textContiner}>
{/* <TextField
label='User Name'
title={this.state.userInfo.name}
value={this.state.username}
onChangeText={(username) => this.setState({ username })}
/> */}
<TextField
label='Email Id'
placeholder={value_email}
//value={value_email}
onChangeText={(email) => this.setState({ email })}
/>
<TextField
label='About'
//value={value_about}
placeholder={value_about}
onChangeText={(about) => this.setState({ about })}
/>
<View style={{ marginTop: 20 }}>
<Button
title="Save"
onPress={this.onUpdate.bind(this)}>
</Button>
</View>
</View>
</ScrollView>
<AwesomeAlert
show={this.state.showAlert}
showProgress={false}
title="Hello There"
message={this.state.message}
closeOnTouchOutside={true}
closeOnHardwareBackPress={true}
showCancelButton={this.state.showCancelButton}
showConfirmButton={this.state.showConfirmButton}
cancelText={this.state.cancelText}
confirmText={this.state.confirmText}
confirmButtonColor="#DD6B55"
onCancelPressed={() => {
this.hideAlert();
}}
onConfirmPressed={() => {
this.hideAlert();
}}
/>
</View>
);
}
}
export default ProfileEdit;
Is Avatar based on React Native's Image? To my experience, the Image component shipped with React Native is very buggy. Indeed, reloading issue is one of them. I often use FastImage as replacement for Image.

SweetAlert2 : Validation required for one of the fields

I am trying to perform validation on one of the fields in the form.
Only if the value for that field exists will I be able to invoke the API, if not an error message will be thrown.
I tried various examples from SweetAlert2's website. I just want the validation for one of the fields.
Swal.fire({
title: 'Are you sure you want to Save the Notes?',
type: 'info',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes'
}).then((result) => {
console.log('result.value',result.value);
if (result.value) {
Swal.fire( {
title: 'Download Notes',
html:"<div class='b'><p>ID</p></div><input id='swal-input2' class='swal2-input' required/><div class='b'><p>Notes</p></div><input id='swal-input1' class='swal2-input' autofocus minlength='500' >",
confirmButtonText: 'Save',
preConfirm: (login) => {
console.log('document.getElementById(swal-input2).value',document.getElementById('swal-input2').value);
request_string = {
"Request":
[
{
"Col1": "value1",
"Col1": "value2",
"Col1": document.getElementById('swal-input2').value,
"Col1": document.getElementById('swal-input1').value,
}
]
};
fetch('API_URL', {
headers: {
'Accept': 'application/json, text/plain, application/xml, */*',
'Content-Type': 'application/json',
'Access-Control-Allow-Headers': 'Content-Type',
},
method: 'POST',
body: JSON.stringify(request_string)
}
).then(response => {
if (response.status !== 200) {
return;
}
response.text().then(data => {
response_data = data;
response_jsonObj = JSON.parse(response_data);
});
}).catch(error => this.setState({ error }));
},
allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
swal({
title: " Your request is being processed!",
icon: "success",
confirmButtonText: 'OK'
}).then((okay) => {
if (okay) {
history.push('/page1');
history.push('/page2');
}
});
});
}
})
If you just want to make sure that the first input (i.e. swal-input2) is not null, then you simply need to add preConfirm like that:
preConfirm: () => {
if (document.getElementById('swal-input2').value) {
// Handle return value
} else {
Swal.showValidationMessage('First input missing')
}
}
You can find the working solution here
For those who try to get every inputs with a required attribute try this :
inputAttributes: {
input: 'number',
required: 'true'
}
Hi folks this as been fixed here is the code sample for the same :
Swal.fire({
title: 'Are you sure you want to Save the Notes?',
type: 'info',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes'
}).then((result) => {
console.log('result.value',result.value);
if (result.value) {
Swal.fire( {
title: 'Download Notes',
html:"<div class='b'><p>ID</p></div><input id='swal-input2' class='swal2-input' required/><div class='b'><p>Notes</p></div><input id='swal-input1' class='swal2-input' autofocus minlength='500' >",
confirmButtonText: 'Save',
preConfirm: () => {
if((document.getElementById('swal-input2').value == "") || (document.getElementById('swal-input2').value == '') || ((document.getElementById('swal-input2').value == null)) ){
Swal.showValidationMessage(
`ID is a required field`
)
}
}
}).then((result) => {
request-string = {
"Request":
[
{
"COL1": VALUE1,
"COL2": VALUE2,
"COL3": VALUE3,
"COL4": VALUE4,
"COL5" : VALUE5,
"COL6" : VALUE6,
"COL7": VALUE7
}
]
};
;
fetch('API_URL', {
headers: {
'Accept': 'application/json, text/plain, application/xml, */*',
'Content-Type': 'application/json',
'Access-Control-Allow-Headers': 'Content-Type',
},
method: 'POST',
body: JSON.stringify(request-string)
}
).then(response => {
if (response.status !== 200) {
return;
}
response.text().then(data => {
response_data = data;
response_jsonObj = JSON.parse(response_data);
this.setState({ state: response_jsonObj });
});
}).catch(error => this.setState({ error }));
swal({
title: "Request Submitted Successfully!",
icon: "success",
confirmButtonText: 'OK'
}).then((okay) => {
if (okay) {
history.push('/page1');
history.push('/page2');
}
});
});

Resources