Is there a way in laravel that will not allow the website to refresh on form submission ?
CodePudding user response:
You can create JS function that will send the request for you, and leave the user on the page. Attach it to the submit button, and use event.preventDefault(), to stop the redirect.
CodePudding user response:
STEP1:
Include Jquery CDN
<script src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
STEP2:
Create controller function
public function FUNCTION_NAME(Request $request){
$input = $request->all();
$field_1 =trim($input['field1']);
$field_2 =trim($input['field2']);
$field_3 =trim($input['field3']);
$success=array();
if((!empty($field_1) || !empty($field_2) && !empty($field_3)){
$ret = DB::table('TBL_NAME')->insert([
'field_1' => $field_1,
'field_2' => $field_2,
'field_3' => $field_3,
]);
$success = array('success'=>1,'msg'=>'Values successfully inserted!');
}
} else{
$success = array('success'=>2,'msg'=>'Mandatory fields missing');
}
return json_encode($success); exit();
}
STEP3:
Add ajax function in blade template
<script>
$(document).ready(function() {
$('.saveValues').click(function() {
var field1 = $('#field1').val();
var field2 = $('#field2').val();
var field3 = $('#field3').val();
if (field1 != '' && field2 != '' && || field3 != '') {
$('.successmsg').html('');
$('.successmsg').removeAttr('style');
$.ajax({
url: '<?php echo e(url("/YOUR_ROUTE")); ?>',
type: 'POST',
'headers': {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
data: {
field_1: field1,
field_2: field2,
field_3: field3
},
success: function(response) {
var res = JSON.parse(response); // alert(res.success);
if (res.success == true) {
$('.successmsg').html('Values updated!').show();
setTimeout(function() {
$('#updatesubmodel').modal('hide');
}, 2000);
} else {
$('.successmsg').html(res.msg).show();
}
}
});
} else {
$('.successmsg').html('Required fields are missing.').show();
}
});
</script>