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.
Related
I have a admin login where the admin has to approve the student,I have used a toggle button for approval option, when clicked on the toggle button the value of status in database as to change from 1 to 0? How do I do this? Even if there are ways for it to work with normal buttons would also be helpful.Thank You.
<script type="text/javascript">
$(document).ready(function() {
$.noConflict();
fill_datatable();
function fill_datatable(collegeID = '') {
var table = $('.user_datatable1').DataTable({
order: [
[0, 'desc']
],
processing: true,
serverSide: true,
ajax: {
url: "{{ route('alumni.datatable1') }}",
data: {
collegeID: collegeID
}
},
columns: [{
data: 'id',
name: 'id'
},
{
data: 'name',
name: 'name'
},
{
data: 'status',
name: 'status',
mRender: function(data) {
return '<input data-id="{{$colleges->id}}" class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Approved" data-off="Pending" {{ $colleges->status ? "checked" : "" }}>'
}
},
{
data: 'action',
name: 'action',
orderable: false,
searchable: false
},
]
});
}
});
</script>
<script>
$(function() {
$(".toggle-class").change (function() {
var status = $(this).prop("checked")== true ? 0 : 1;
var id = $(this).data("id");
$.ajax({
type: "GET",
dataType: "json",
url: "/changeStatus",
data: {"status": status, "id": id},
success: function(data) {
console.log("Success")
}
});
});
});
</script>
Route
Route::get('changeStatus', [AdminAuthController::class, 'changeStatus'])->name('changeStatus');
Controller
public function changeStatus(Request $request,$regno)
{
$colleges = College::find($regno);
$colleges->status = $request->status;
$colleges->save();
return back();
}
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
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');
}
});
});
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
})
})
}
}]);
I have used check boxes in my gridview,like this
<?php
if(isset($dataProvider) && !empty($dataProvider)) {
echo \yii\grid\GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn',
'header' => 'No.'],
[
'class' => 'yii\grid\CheckboxColumn',
'header'=>'Select',
'checkboxOptions' => function ($model, $key, $index, $column) {
return ['value' => $model->dsItemId];
}
],
[
'label'=>'Category',
'value' => function ($model) {
return $model->getdscategoryName();
},
],
'dsItemName',
'qty',
[
'attribute' => 'image',
'enableSorting' => false,
'format' => 'image',
'value' => function ($model) {
return $model->getImageUrl();
},
],
],
]);
echo Html::submitButton('Save',['id' => 'saveBtn','class' => 'btn btn-danger']);
}?>
When I'm selecting check boxes and select savebutton, it will go to this function given below,
<script>
$( document ).ready(function() {
$('#saveBtn').click(function() {
var idVar = '';
$("input[name='selection[]']").each( function () {
if($(this).is(':checked')) {
if(idVar != '') {
idVar += ',' + $(this).val();
}else {
idVar = $(this).val();
}
}
});
$.ajax({
type: "POST",
url:"<?php echo Yii::$app->urlManager->createAbsoluteUrl(['dsproductitems/setproduct'])?>",
data: { dsItemId : idVar },
success:function(data) {
location.reload();
}
});
});
});
</script>
Here I'm trying to redirect my form to controller through ajax and the problem is, program control is failing to enter into flowing code.
$.ajax({
type: "POST",
url:"<?php echo Yii::$app->urlManager->createAbsoluteUrl(['dsproductitems/setproduct'])?>",
data: { dsItemId : idVar },
success:function(data) {
location.reload();
}
});
});
i'm failing to figure out why.. please help..