Laravel ajax, the page keeps on refreshing. I want to stop it from refreshing after posting data - ajax

I am using laravel and ajax to update records from table. Currently, the records are successfully being updated but somehow a refresh is triggered, making the ajax feature useless. i need a way to just post the form to update my database record without refreshing the page.
The following is my code.
View File Ajax
$(document).on("click", "#primaryButton", function(e) {
e.preventDefault(); // Prevent Default form Submission
$.ajax({
type: "post",
url: "{{ route('event-qr-post') }}",
data: $("#message").serialize(),
success: function(store) {
location.href = store;
console.log("success!");
console.log(location.href);
console.log($("#message").serialize());
},
error: function() {
console.log("fail");
}
}).done(function(store) {
console.log("itsdone");
});
// e.preventDefault();
return false;
});
View File Submit Form
<form enctype="multipart/form-data" id="message">
#csrf
<div class="form-l">
<div id="ref-lookup">
<label style="font-size: 22px; font-weight: 700;margin-block:10px;" for="eventTitle">Reference
number</label>
<input id="id" name="id" value="{{ '' }}" required>
{{-- <input type="hidden" name="name" value="{{ $eid->name }}" required> --}}
<input type="hidden" name="staffName" value="{{ $sid->name }}" required>
<input type="hidden" name="submitType" id="submitType" value="">
<input type="hidden" name="pageType" id="pageType" value="{{ $type }}">
{{-- <input type="hidden" name="guestLeft" id="guestLeft" value=""> --}}
<div style="display:flex;justify-content:space-between;gap:10px">
<button type="button" style="background-color:green"
onclick="findGuest(document.getElementById('id').value);">Find Contact</button>
<button id="addGuest" type="button" style="background-color:red" onclick="addGuests();">Add a
Replacement</button>
</div>
</div>
<div id="guestForm">
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">First Name</label>
<input id="guestFirstName" name="first_name" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Last Name</label>
<input id="guestSurname" name="last_name" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Email</label>
<input id="guestEmail" name="email" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Company</label>
<input id="companyName" name="company" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Job Title</label>
<input id="guestTitle" name="title" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Tel</label>
<input id="guestPhone" name="tel" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Country</label>
<input id="guestCountry" name="country" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Notes</label>
<input id="guestNotes" name="notes" value="">
</div>
<button type="button" class="btn-blue" id="primaryButton">
Submit
<span class="foo fa fa-star checked"></span>
</button>
</div>
</div>
Controller
public function post_eventQR_attendance(Request $request)
{
// $ins = $request->all();
// unset($ins['_token']);
// dd($ins);
$User = MasterTempAward::where('id', $request->get('id'))->first();
$User->modified_by = $request->get('staffName');
$User->attended = "Yes";
$User->time = Carbon::now();
$User->business_card = "";
$User->save();
}

Your page is being refreshed because of the location.href = store; that you passed after the ajax request receives a success response.
location.href redirects the webpage to the specified URL.
So change your Ajax code to this:
$(document).on("click", "#primaryButton", function(e) {
e.preventDefault(); // Prevent Default form Submission
$.ajax({
type: "post",
url: "{{ route('event-qr-post') }}",
data: $("#message").serialize(),
success: function(store) {
// location.href = store;
console.log("success!");
// console.log(location.href);
console.log($("#message").serialize());
},
error: function() {
console.log("fail");
}
}).done(function(store) {
console.log("itsdone");
});
// e.preventDefault();
return false;
});

Related

cannot save data through Ajax laravel 8

when normal request performed , it saves data without any error but through ajax it returned error: [object HTMLDivElement].
but when I comment the create function in controller , request is performed successfully.
csrf token added in meta tag
data can be saved through normal request but not with the ajax
Route is properly configured
ass far as i understand , error is generating while performing create function in the controller.
Controller
public function store(Request $request)
{
$data = $request->all();
Contact::create($data);
return response()->json(['success'=>'Message Sent Successfully']);
}
Blade.php
<!-- ======= Contact Section ======= -->
<section id="contact" class="contact">
<form method="POST" action="{{route('contact.store')}}" class="php-email-form" id="contact-form">
<div class="row gy-4">
<div class="col-md-6">
<input type="text" name="name" class="form-control" placeholder="Your Name" required>
</div>
#csrf
<div class="col-md-6 ">
<input type="email" class="form-control" name="email" placeholder="Your Email" required>
</div>
<div class="col-md-12">
<input type="text" class="form-control" name="subject" placeholder="Subject" required>
</div>
<div class="col-md-12">
<textarea class="form-control" name="message" rows="6" placeholder="Message" required></textarea>
</div>
<div class="col-md-12 text-center">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
<button type="submit" id="send-message">Send Message</button>
</div>
</div>
</form>
</section><!-- End Contact Section -->
Ajax
$(document).ready(function() {$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$("#contact-form").submit(function(e){
e.preventDefault();
$('.loading').addClass("d-block");
var name = $("input[name=name]").val();
var email = $("input[name=email]").val();
var subject = $("input[name=subject]").val();
var message = $("input[name=message]").val();
$.ajax({
type:'POST',
url:"{{route('contact.store')}}",
data:{name:name, email:email, subject:subject, message:message},
success:function(data){
$('.sent-message').addClass("d-block");
$('.sent-message').text(data.success);
//$('#contact-form').trigger("reset");
},
complete: function(){
$('.loading').removeClass("d-block");
},
error:function(data){
$('.error-message').addClass("d-block");
$('.error-message').text(data.error);
}
});
});
});

Programatically trigger form validation with JQuery Validator don't work

According to the docs of jQuery Validator doing this should programatically trigger form validation.
var validator = $( "#myform" ).validate();
validator.form();
But in my code it does nothing, why? I have a submit button on my form that is working fine, but validator.form() doesn't work at all. I've updated the post with my HTML form as well as the javascript code.
This is my form
<form class="kt-form kt-form--label-right" id="frm_sok" action="ajax/artikkel.php?a=sok_artikler" method="post">
<div class="kt-portlet__body">
<div class="kt-blog-post">
<div class="form-group ">
<div class="col-12">
<input class="form-control" type="search" value="{{ sok }}" id="searchinput" name="searchinput">
</div>
</div>
<div class="row">
<div class="col-4">
<label>Ikke søk i :</label>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="skjulnyheter" name="skjulnyheter">
<label class="form-check-label" for="skjulnyheter">Nyheter</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="skjulforum" name="skjulforum">
<label class="form-check-label" for="skjulforum">Forum</label>
</div>
</div>
<div class="col-4">
<label for="sorter">Sorter:</label><br />
<select class="form-control" name="sorter" id="sorter">
<option value="a.opp_dato DESC">Nyeste</option>
<option value="score">Beste treff</option>
<option value="a.opp_dato ASC">Eldste</option>
</select>
</div>
</div>
</div>
</div>
<div class="kt-portlet__foot">
<div class="kt-form__actions">
<input type="submit" class="btn btn-primary sokknapp" value="Søk" />
</div>
</div>
</form>
Here is my Javascript:
$( window ).on( 'load', function()
{
var validator = $("#frm_sok").validate(
{
rules:
{
searchinput:
{
required: true
}
},
messages:
{
searchinput :
{
required : 'Du må neste søke etter noe. Noe som helst. Ett eller annet.'
}
},
invalidHandler: function(event, validator)
{
$('.error').css( "display", "inline-block !important");
},
submitHandler: function(form)
{
preload_kamp();
$(form).ajaxSubmit(
{
success: function(data)
{
$( "#sokcontent" ).html(data);
}
});
}
});
validator.form();
});

Edit Data on Modal Using Ajax

I want to edit my data on a modal and I can't pass my data from JSON to the modal.
I tried to print my JSON using console.log() function and it works fine. But when I'm trying to pass the data to my modal, it doesn't work.
Here's my script:
$(document).on('click', '.editBtn', function(e){
e.preventDefault();
edit_id = $(this).attr("id");
$.ajax({
url:"action.php",
method:"POST",
data:{edit_id:edit_id},
dataType:"json",
success:function(data){
// data = JSON.parse(response);
console.log(data);
$('#id').val(data.id); //id name of the modal; the hidden type
$('#fname').val(data.fname);
$('#lname').val(data.lname);
$('#email').val(data.email);
$('#phone').val(data.phone);
}
});
});
Here's how I encode my JSON:
if (isset($_POST['edit_id'])){
$id = $_POST['edit_id'];
$row = $db->getUserById($id);
echo json_encode($row);
}
And here's my code for getUserByID():
public function getUserById($id){
$sql = "SELECT * FROM users WHERE id = ?";
$stmt = $this->conn->prepare($sql);
$stmt->execute([$id]);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
Btw, here's my code for the modal:
<div class="modal fade" id="editModal">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit User</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body px-4">
<form accept="" method="post" id="edit-form-data">
<input type="hidden" name="id" id="id">
<div class="form-group">
<input type="text" name="fname" class="form-control" id="fname" required>
</div>
<div class="form-group">
<input type="text" name="lname" class="form-control" id="lname" required>
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" id="email" required>
</div>
<div class="form-group">
<input type="tel" name="phone" class="form-control" id="phone" required>
</div>
<div class="form-group">
<input type="submit" name="update" id="update" value="Update User" class="btn btn-primary btn-block">
</div>
</form>
</div>
</div>
</div>
</div>
I've already figured it out. My code in script is incomplete. It should be data[0].id etc.

How to validate modal form on click with Ajax in Laravel

I have a modal form for login in Laravel project. When I enter false data and click to the button "Log in" the page refreshing and modal is closing. I can see errors only when I open modal again. It's not user-friendly. I want to validate modal with Ajax and show errors if something goes wrong without refreshing page
This is my modal
<form action="/login" method="post">
#csrf
<div class="sign-in-wrapper">
Login with Facebook
Login with Google
<div class="divider"><span>Or</span></div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" name="email" id="email">
<i class="icon_mail_alt"></i>
#error('email')
<strong style="color: red">{{$message}}</strong>
#enderror
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" name="password" id="password" value="">
<i class="icon_lock_alt"></i>
#error('password')
<strong style="color: red">{{$message}}</strong>
#enderror
</div>
<div class="clearfix add_bottom_15">
<div class="checkboxes float-left">
<input id="remember-me" type="checkbox" name="check">
<label for="remember-me">Remember Me</label>
</div>
<div class="float-right"><a id="forgot" href="javascript:void(0);">Forgot Password?</a></div>
</div>
<div class="text-center">
<button type="submit" class="btn_login">Log In</button>
</div>
<div class="text-center">
Don’t have an account? Sign up
</div>
<div id="forgot_pw">
<div class="form-group">
<label>Please confirm login email below</label>
<input type="email" class="form-control" name="email_forgot" id="email_forgot">
<i class="icon_mail_alt"></i>
</div>
<p>You will receive an email containing a link allowing you to reset your password to a new preferred
one.</p>
<div class="text-center"><input type="submit" value="Reset Password" class="btn_1"></div>
</div>
</div>
</form>
Try this
You need to some custom changes yourself in code.
$('#frmLogin').on('submit', function (event) {
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: '/login',
data: formData,
success: function (res) {
console.log(res); // get resposnse from controller in json
if (res.emailError) {
$('.error-email').show().text(res.errorMsg);
} else {
$('.error-email').hide();
}
if (res.passwordError) {
$('.error-password').text(res.errorMsg);
} else {
$('.error-password').hide();
}
},
error: function (data) {
alert(data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="frmLogin" method="POST">
#csrf
<div class="sign-in-wrapper">
Login with Facebook
Login with Google
<div class="divider"><span>Or</span></div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" name="email" id="email">
<i class="icon_mail_alt"></i>
<strong style="color: red;display: none;" class="error-email">{{$message}}</strong>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" name="password" id="password" value="">
<i class="icon_lock_alt"></i>
<strong style="color: red;display: none;" class="error-password">{{$message}}</strong>
</div>
<div class="clearfix add_bottom_15">
<div class="checkboxes float-left">
<input id="remember-me" type="checkbox" name="check">
<label for="remember-me">Remember Me</label>
</div>
<div class="float-right"><a id="forgot" href="javascript:void(0);">Forgot Password?</a></div>
</div>
<div class="text-center">
<button type="submit" class="btn_login">Log In</button>
</div>
<div class="text-center">
Don’t have an account? Sign up
</div>
</div>
</form>

getting typerror in Vue JS while trying to bind the JSON data in select model

I want to bind the select option with returned JSON data. However, when I do the API call and set the options model groups to the returned JSON, I get the error 'TypeError: Cannot set property 'groups' of undefined'.
Here is the vue file
<template>
<div class="register">
<div class="container">
<div class="row">
<div class="col">
<h3 class="mb-10">Register as a volunteer</h3>
<form action="">
<div class="form-group">
<label for="first_name">First Name</label>
<input type="text" v-model="first_name" placeholder="First Name" class="form-control" id="first_name">
</div>
<div class="form-group">
<label for="last_name">Last Name</label>
<input type="text" v-model="last_name" placeholder="Last Name" class="form-control" id="last_name">
</div>
<div class="form-group">
<label for="group">Select Institution/Organization/Company</label>
<select v-model="group" class="form-control" id="group">
<option v-for="group in groups" v-bind:name="name">{{ group.code }}</option>
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="text" v-model="adv_phone" placeholder="Phone" class="form-control" id="phone">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" v-model="adv_password" class="form-control" id="password" placeholder="Password">
</div>
<div class="form-group">
<label for="confirm-password">Confirm Password</label>
<input type="password" v-model="adv_password" class="form-control" id="confirm-password" placeholder="Confirm Password">
</div>
<div class="from-group">
<input type="submit" class="btn btn-primary" value="Register">
<router-link :to="{name:'home'}">
<a class="btn btn-outline-secondary">Cancel</a>
</router-link>
</div>
</form>
</div>
</div>
</div>
<div class="register-form"></div>
</div>
</template>
<script>
export default {
mounted(){
this.getGroups()
},
data (){
return {
group: '',
groups:'',
first_name:'',
last_name:'',
adv_email:'',
adv_phone:'',
adv_password:'',
confirm_password:''
}
},
methods:{
getGroups(){
axios.get('/api/group/get/all')
.then(function (response) {
console.log(response);
this.groups = response.data;
//console.log(groups);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
}
}
}
</script>
and here is my json returned
[{"id":8,"name":"Villa Maria Academy","code":"Vil-9458-3786","advisors":25,"students":99,"subscription_time":99,"subscription_type":0,"admin_name":"","admin_email":"","phone":"817879234","address":"Abcde street","state":"Pennsylvania","zip":16502,"apt":"","city":"Erie"},{"id":9,"name":"Cathedral Prep","code":"Cat-1959-1432","advisors":99,"students":99,"subscription_time":99,"subscription_type":0,"admin_name":"","admin_email":"","phone":"0","address":"","state":"","zip":0,"apt":"","city":""}]
Why am I getting a type error, when I set this.groups = response.data?
You can use arrow function to fix problem.
methods:{
getGroups(){
axios.get('/api/group/get/all')
.then(response => {
console.log(response);
this.groups = response.data;
//console.log(groups);
})
.catch(error => {
console.log(error);
})
.then(() => {
// always executed
});
}
}

Resources