I have done a Modal form and trying to submit the form, but it is not working.
This is my form
<div class="modal-body">
<div class="card-body">
<form action="{{ url('/admin/modaluser/add')}}" method="POST" id="customerSubmit">
<div class="row">
<div class="col">
#if(session('success'))
<div class="alert alert-success">{{session('success')}}</div>
#endif
#if(session('error'))
<div class="alert alert-error">{{session('error')}}</div>
#endif
#csrf
<div class="row">
<div class="form-group col-md-6">
<label for="name">Name</label>
<input class="form-control" name="name" id="name"
type="text"
placeholder="Enter Name" data-original-title="" title=""
required>
</div>
<div class="form-group col-md-6">
<label for="hpcontact">HP Contact No</label>
<input class="form-control" name="hpcontact" id="hpcontact"
type="text"
placeholder="HP Contact No" data-original-title="" title=""
required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="icno">IC No</label>
<input class="form-control" name="icno" id="icno"
type="text"
placeholder="Enter IC No" data-original-title="" title=""
required>
</div>
<div class="form-group col-md-6">
<label for="homephone">Home Contact No</label>
<input class="form-control" name="homephone" id="homephone"
type="text"
placeholder="Enter home contact no" data-original-title="" title=""
required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="dob">D.O.B</label>
<input class="form-control" name="dob" id="dob"
type="date"
placeholder="Enter DOB" data-original-title="" title=""
required>
</div>
<div class="form-group col-md-6">
<label for="officeno">Office No</label>
<input class="form-control" name="officeno" id="officeno"
type="text"
placeholder="Enter Office No" data-original-title="" title=""
required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="address">Address</label>
<input class="form-control" name="address" id="address"
type="text"
placeholder="Enter Address" data-original-title="" title=""
required>
</div>
<div class="form-group col-md-6">
<label for="email">Email</label>
<input class="form-control" name="email" id="email"
type="email"
placeholder="Enter Email" data-original-title="" title=""
required>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
This is my jQuery for the Ajax
$(document).ready(function(){
$('body').on('click','#addcustomer',function(e){
e.preventDefault();
// AJAX request
console.log($('#customerSubmit').serialize())
$.ajax({
method: 'post',
url: '/admin/modaluser/add',
data: $('#customerSubmit').serialize(),
success: function(msg) {
console.log(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});
});
});
And this my Controller
public function adduser(Request $request)
{
if(Request::ajax()){
$name = Input::get( 'name' );
$hpcontact = Input::get( 'hpcontact' );
$icno = Input::get( 'icno' );
$homephone = Input::get( 'homephone' );
$dob = Input::get( 'dob' );
$officeno = Input::get( 'officeno' );
$address = Input::get( 'address' );
$email = Input::get( 'email' );
$customer = new Customer();
$customer->name = $name;
$customer->hpcontact = $hpcontact;
$customer->icno = $icno;
$customer->homephone = $homephone;
$customer->dob = $dob;
$customer->officeno = $officeno;
$customer->address = $address;
$customer->email = $email;
$customer->save();
$response = array(
'status' => 'success',
'msg' => 'Customer created successfully',
);
return Response::json($response);
}
else {
echo 'no';
exit;
}
}
And finally, this is my Router
Route::post('modaluser/add', 'CustomerController#adduser')->name('customer.adduser');
When I click the button, nothing has happened. But this error is coming.
POST http://127.0.0.1:8000/admin/modaluser/add 500 (Internal Server Error)
And showing me the console error, which is defined in the ajax. Is there anything wrong I am doing. This is my First Ajax in Laravel. Please help me to solve this. Thanks in advance.
add /admin into your route:
Route::post('admin/modaluser/add', 'CustomerController#adduser')->name('customer.adduser');
and change url path in ajax:
$(document).ready(function(){
$(document).on('submit','#customerSubmit',function(e){
e.preventDefault();
// AJAX request
console.log($(this).serialize())
$.ajax({
method: 'post',
url: "{{route('customer.adduser')}}",
data: $(this).serialize(),
success: function(msg) {
console.log(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});
});
});
remove form action:
<form action="" method="POST" id="customerSubmit">
You should check all class used paths declared on top of the controller or not. You should add the CSRF header in your ajax request.
$.ajax({
method: 'post',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "route name or url",
data: $(this).serialize(),
success: function(msg) {
console.log(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});
Related
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;
});
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);
}
});
});
});
I have a small contact form that almost works as i should. The file is uploaded and sent correctly, but all the other values from the input fields in the form does not pass throug the script. Does anyone see what I am missing?
Form:
<form id="contactForm" name="sentMessage" novalidate="" method="post" enctype="multipart/form-data">
<input type="hidden" name="path" id="path" value="projectpage">
<div><div class="textwidget custom-html-widget"><div class="moduletable pt-2 pb-2 mb-4">
<div class="custom pl-2 pr-2 pt-4 pb-2 mb-4">
<div class="control-group form-group">
<div class="col"><label for="name">Navn:</label><input id="name" class="form-control" required="" type="text" data-validation-required-message="Skriv inn ditt navn.">
<div class="help-block"></div>
</div>
</div>
<div class="control-group form-group">
<div class="col"><label for="phone">Telefonnummer:</label><input id="phone" class="form-control" required="" type="tel" data-validation-required-message="Skriv inn et telefonnummer.">
<div class="help-block"></div>
</div>
</div>
<div class="control-group form-group">
<div class="col"><label for="email">E-post:</label><input id="email" class="form-control" required="" type="email" data-validation-required-message="Skriv inn en e-postadresse.">
<div class="help-block"></div>
</div>
</div>
<div class="control-group form-group">
<div class="col"><label for="message">Melding:</label><textarea id="message" class="form-control" style="resize: none;" cols="100" maxlength="999" required="" rows="10" data-validation-required-message="Skriv en melding"></textarea>
<div class="help-block"></div>
</div>
</div>
<div class="control-group form-group">
<div class="col"><label for="attachment">Vedlegg:</label> <input type="file" name="attachment[]" class="form-control border-0 w-auto" multiple="multiple">
</div>
</div>
<div class="control-group form-group">
<div class="col"><label class="checkbox"> <input id="terms-and-conditions" name="terms-and-conditions" required="" type="checkbox" data-validation-required-message="Kryss av denne boksen hvis du vil fortsette"> Ved avkryssning samtykker du i vår personvernerklæring. </label>
<div class="help-block"></div>
</div>
</div>
<p class="help-block"></p>
<div id="success"></div>
<div class="col"><button id="sendMessageButton" class="btn btn-success" type="submit">Send oss melding</button></div></div>
</div></div></div></form>
JS: I think the problem is here, but I cant figure out what to change or add to make the data from the fields pass through along with the attachment.
$(function() {
$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {},
submitSuccess: function($form, event) {
$("#btnSubmit").attr("disabled", true);
event.preventDefault();
var data = new FormData(contactForm);
$.ajax({
url: "/wp-content/themes/bootstrap/mail/contact_me.php",
type: "POST",
method: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
success: function() {
$("#btnSubmit").attr("disabled", false);
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×").append("</button>");
$('#success > .alert-success').append("<strong>Takk for din interesse. </strong>");
$('#success > .alert-success').append('</div>');
$('#contactForm').trigger("reset");
},
error: function() {
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×").append("</button>");
$('#success > .alert-danger').append("<strong>Sorry, it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
$('#contactForm').trigger("reset");
},
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
$('#name').focus(function() {
$('#success').html('');
});
PHP:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
/* Exception class. */
require 'Exception.php';
/* The main PHPMailer class. */
require 'PHPMailer.php';
$name = strip_tags(htmlspecialchars($_POST['name']));
$from = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$path = strip_tags(htmlspecialchars($_POST['path']));
$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
$mail->AddReplyTo(($email_address), ($name));
$mail->setFrom('noreply#mydomain.no', 'Kontaktskjema på nettside');
$mail->addAddress('email#gmail.com', 'My NAME');
$mail->Subject = 'Melding fra ' .$name. ' via kontaktskjema';
$mail->Body = "Du har fått en melding via kontaktskjemaet på nettsiden.\n\n"."Her er detaljene:\n\nNavn: $name\n\nE-post: $email_address\n\nTelefon: $phone\n\nMelding:\n$message";
foreach ($_FILES["attachment"]["name"] as $k => $v) {
$mail->AddAttachment( $_FILES["attachment"]["tmp_name"][$k], $_FILES["attachment"]["name"][$k] );
}
if(!$mail->send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
return true;
?>
Most of your <input> elements don't have name attributes. So this won't include them:
new FormData(contactForm)
The file input works because it has a name:
<input type="file" name="attachment[]" class="form-control border-0 w-auto" multiple="multiple">
^----- here ------^
Add names to the rest of the inputs that you want included in the FormData object.
Like David said most of your <input> elements dont have name attributes and thats why the FormData method dont include them, you have two work arounds here:
Get all your data into an array using the id of each element and pass this array to your ajax e.g:
let data = {
name : $('#name').val(),
email: $('#email').val(),
.....
};
add the name attribute to each input.
Hope it helps
please help me with this error. I have a javascript that i want to append a single image file to my form and i want to send the form data into ajax.
Here is my code:
<form id="frm_product" class="form-horizontal" enctype="multipart/form-data">
<div style="position:relative;">
<input type="file" name="addfiles" id="addfiles">
<span class='label label-info' id="upload-file-info"></span>
</div>
<br>
<div class="form-group">
<label for="cat_name">Product Name: </label>
<input type="text" class="form-control" name="prod_name">
<span class="error prod_name"></span>
</div>
<div class="form-group">
<label for="cat_desc">Description: </label>
<input type="text" class="form-control" name="prod_desc">
<span class="error prod_desc"></span>
</div>
<div class="form-group">
<label for="cat_desc">Price: </label>
<input type="text" class="form-control" name="prod_price">
<span class="error prod_price"></span>
</div>
<div class="form-group">
<label for="cat_desc">Category: </label>
<select class="form-control" name="prod_cat">
<?php foreach($data as $category){ ?>
<option value="<?php echo $category->id; ?>"><?php echo $category->name; ?></option>';
<?php } ?>
</select>
<span class="error prod_cat"></span>
</div>
</form>
here is my ajax code where i want to append a single file:
function submitProduct() {
var formData = new FormData($("#frm_product")[0]);
formData.append('image', $("#addfiles")[0].files);
$.ajax({
url : siteurl+"/product/addproduct",
type: "POST",
data: formData,
dataType: "JSON",
contentType: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
success: function(resp) {
$('.error').html('');
if(resp.status == false) {
$.each(resp.message,function(i,m){
$('.'+i).text(m);
});
}
else if(resp.status == true) {
$('#addProduct').modal('hide');
$('#frm_product')[0].reset();
alert("Successfully Added");
}
}
});
}
when i do upload file it says error:
you didn't select a file to upload
I want to insert some data into database using Bootstrap Modal. But the problem is Save button doesn't work properly on Bootstrap Modal as I couldn't insert the data into database through form. If anyone could help me to find it please!?
Here is the form part in blade:
<div id="myAlert" class="modal hide">
<div class="modal-header">
<button data-dismiss="modal" class="close" type="button">×</button>
<h3>Create User</h3>
</div>
<div class="modal-body">
<div class="row-fluid">
<div class="span12">
<div class="widget-box">
<div class="widget-content nopadding">
<form action="#" method="get" id="userForm" class="form-horizontal">
<div class="control-group">
<label class="control-label">Name :</label>
<div class="controls">
<input class="span11" placeholder="Name" type="text">
</div>
</div>
<div class="control-group">
<label class="control-label">Email :</label>
<div class="controls">
<input class="span11" placeholder="Email" type="email">
</div>
</div>
<div class="control-group">
<label class="control-label">Password</label>
<div class="controls">
<input class="span11" placeholder="Enter Password" type="password">
</div>
</div>
<div class="control-group">
<label class="control-label">Confirm Password</label>
<div class="controls">
<input class="span11" placeholder="Confirm Password" type="password">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer"><a data-dismiss="modal" class="btn btn-primary" href="#">Confirm</a> <a
data-dismiss="modal" class="btn" href="#">Cancel</a>
</div>
</div>
Here is the Ajax Part :
$('#userForm').on('success.form.fv', function(e) {
e.preventDefault();
$.ajax({
method: 'POST',
action:"{{ url('/register') }}",
data: $form.serialize()
});
});
You need the submit button. Try to put this code inside your form.
<button type="submit" class="btn btn-primary">Register</button>
Problem with your current Confirm button is: 1) he don't have type=submit; 2) he is outside the form.
first of all add type="submit" to your button
secondly check your network tab in the dev tools in your browser and check the request does it go to /register or not ?
if the request is hitting /register what's the parameters ?
Change form method get to post
I answer here for ajax call
Laravel ajax internal servor 500 (internal server-error)
Your input type elements are missing name attribute
<input class="span11" placeholder="Name" name="name" type="text">
<input class="span11" placeholder="Email" name="email" type="email">
<input class="span11" placeholder="Enter Password" name="password" type="password">
<input class="span11" placeholder="Confirm Password" name ="confirm_password" type="password">
You then retrieve the content using Request or Input by passing the value of the name attribute
At first change your form method from get to post. Then add save button with id btnSave.
Ajax :
$("#btnSave").click(function(e){
e.preventDefault()
var $form = $("#userForm");
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function (data, status) {
if(data.error){
return;
}
alert(data.success); // THis is success message
$('#myModal').modal('hide'); // Your modal Id
},
error: function (result) {
}
});
});
In controller :
public function store(Request $request)
{ try {
$inputs = $request->all();
ModelName::create($inputs);
$data = ['success' =>'Data saved successfully'];
} catch (\Exception $e) {
$data = ['error' =>$e->getMessage()];
}
return Response::json($data);
}
Form part in blade:
<div class="modal-footer"><a data-dismiss="modal" class="btn btn-primary" id="btnAdd">Confirm</a></div>
Ajax Part
$('#btnAdd').click(function () {
$.ajax({
url: '{{url('/register')}}',
type: 'POST',
data: $('#userForm').serialize(),
success: function (object) {
},
error: function (result) {
}
});
});