JQuery Ajax post method is not working in laravel - php

I want to save an image and two text field using JQuery,Ajax. here, i'm using bootstrap modal. But when I submit the modal form it's show MethodNotAllowedHttpException Exception.
My Ajax Method.
$(document).ready(function(){
$('#advisoradd').on('submit',function(){
var name=$('#adname').val();
var title=$('#adtitle').val();
var img=$('#adfile').val();
$.ajax({
url:"{{route('add.advisor')}}",
type:'post',
data:{
'_token':"{{csrf_token()}}",
'name':name,
'title':title,
'img':img,
},
success:function(data)
{
console.log(data);
}
});
});
});
My view Modal code.
<form method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<div class="img_upload_team">
<button class="btn">+</button>
<input type="file" name="myfile" id="adfile">
</div>
<h2>Add A Profile Photo</h2>
<p>Click “+” Sign to Add</p>
</div>
<div class="form-group">
<input type="text" name="adname" class="form-control" id="adname" placeholder="Name">
</div>
<div class="form-group">
<input type="text" name="adtitle" class="form-control" id="adtitle" placeholder="Title">
</div>
<button type="submit" class="btn btn_modal_submit" id="advisoradd">Add</button>
</form>
My controller and Route for this Request.
public function addadvisor(Request $request)
{
$advisor=new Advisor();
$advisor->name=$request->name;
$advisor->title=$request->title;
$file = $request->file('img') ;
$fileName = $file->getClientOriginalName();
$destinationpath=public_path().'/images/';
$file->move($destinationpath,$fileName);
$advisor->image=$fileName;
$advisor->save();
return response()->json($advisor);
}
Route::post('/advisor','ImageController#addadvisor')->name('add.advisor');

You've mixed up button and form events. Buttons don't have a submit event, forms do. Since you're adding the event on the button, change it to click.
We should also add a preventDefault() to stop the button from submitting the form.
(We could also add the type="button" attribute on the button element to stop it from submitting the form).
This should work:
$(document).ready(function() {
// Add a 'click' event instead of an invalid 'submit' event.
$('#advisoradd').on('click', function(e) {
// Prevent the button from submitting the form
e.preventDefault();
// The rest of your code
});
});

Related

JQuery Form Validator's toggleDisabled module does not work on buttons that are not type 'submit'

I have a form that uses the jquery form validator plugin (http://www.formvalidator.net/) to perform client side pre-submit validation. I have the toggleDisabled module activated so that the submit button is disabled until all required fields are filled out and formatted correctly. My jquery then sends the form data to a processing page via ajax. The storeData.php code stores the data in a table. On success, the ajax should open a modal. I have verified that the data is being stored in my table.
The issue lies (I suspect) with the form submit button. In order for my toggleDisabled module to work correctly, the button has to be of type 'submit.' But because of the nature of a submit button the success function of my ajax is effectively being bypassed so that the modal will never be displayed.
I have tested this by changing the submit button to a regular button. At the expense of my toggleDisabled module not functioning this way, my modal is displayed.
I have found many solutions here for enabling/disabling buttons and also for preventing form submit by changing the button type to button. However, I want to use the validator module to disable/enable the button because it is designed to listen to the data-validation attributes for my form fields. But it won't work unless it's a submit button. Is there a simple solution that I'm overlooking?
index.php
<form method="post" name="talentForm" id="talentForm">
<div class="form-row">
<div class="col-auto redtext">*</div>
<div class="col">
<input type="text" id="first" class="form-control" placeholder="First name" data-validation="required">
</div>
<div class="col-auto"> </div>
<div class="col-auto redtext">*</div>
<div class="col">
<input type="text" id="last" class="form-control" placeholder="Last name" data-validation="required">
</div>
</div>
<div class="row rowtm20"></div>
<div class="form-row">
<div class="col-auto redtext">*</div>
<div class="col">
<input type="text" id="email" class="form-control" placeholder="E-mail" data-validation="email">
</div>
<div class="col-auto"> </div>
<div class="col-auto"> </div>
<div class="col">
<input type="text" id="phone" class="form-control" placeholder="Phone">
</div>
</div>
<div class="form-row">
<button type="submit" id="registerButton" class="btn btn-primary mb-2 biggertext">Register</button>
</div>
</form>
<script>
$.validate({
modules : 'security,toggleDisabled',
showErrorDialogs : false
});
$('#registerButton').on('click', function(){
var inputData = $('#last').val()+"|"+$('#fist').val()+"|"+$('#email').val()+"|"+$('#phone').val();
$.ajax({
type: 'post',
url: 'storeEntry.php',
data: {registration:inputData},
success: function(response){
if(response == "1"){
$("#thankyouModal").modal("show");
}
else{
alert("Error");
}
}
});
});
</script>
storeEntry.php
if(isset($_POST)){
$data = explode("|",$_POST['registration']);
$addRegistration = "insert into talent (Last,First,email,Phone) values('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."')";
$entry = $dbConn->query($addRegistration) or die ("Error performing addRegistration query: ".mysqli_error($dbConn));
if($entry){
echo "1";
} else{
echo "0";
}
}
Well, I found the answer. I added an argument to the click function and then called the preventDefault method, which will effectively 'turn off' the submit action of a submit button. This allows my toggleDisabled module in the validator to function correctly while also allowing my modal to appear and my ajax to execute. Hre is my revised click function:
$('#registerButton').on('click', function(e){
e.preventDefult();
var inputData = $('#last').val()+"|"+$('#fist').val()+"|"+$('#email').val()+"|"+$('#phone').val();
$.ajax({
type: 'post',
url: 'storeEntry.php',
data: {registration:inputData},
success: function(response){
if(response == "1"){
$("#thankyouModal").modal("show");
}
else{
alert("Error");
}
}
});
});

jQuery form submit not working php

I am creating a form that need to be submit using jQuery. Below is my code -
<script src="js/app.js" type="text/javascript"></script>
<form method="post" class="needs-validation" id="new-item" action="admin-add-inventory2.php">
<div class="mb-3">
<label>Item Name</label>
<input type="text" class="form-control" id="itemname" name="itemname" placeholder="Item name" required>
<span id='inmessage'>
</div>
<div class="mb-3">
<label>Description
<span class="text-muted">(Optional)</span>
</label>
<input type="text" class="form-control" id="description" name="description" placeholder="description...">
<span id='dmessage'>
</div>
<hr class="mb-4">
<input type="submit" value="Add To Inventory" name="submit" id="submit" class="btn btn-primary btn-lg btn-block error-w3l-btn">
</form>
<div id="form-messages"></div>
Code for app.js --
$(function() {
// Get the form.
var form = $('#new-item');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#itemname').val('');
$('#description').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured, please try again.');
}
});
});
});
But when pressing the submit button, app.js is not getting executed. Its directly going to action="admin-add-inventory2.php" of form tag.
Kindly point me the logic i m missing.
Its not taking the question in stackoverflow due to more code and less text, so i am adding extra text to submit. Pls ignore the below text.
But when pressing the submit button, app.js is not getting executed. Its directly going to action="admin-add-inventory2.php" of form tag.
Kindly point me the logic i m missing.
But when pressing the submit button, app.js is not getting executed. Its directly going to action="admin-add-inventory2.php" of form tag.
Kindly point me the logic i m missing.
Please replace button type from submit to button.
Eg: <input type="button" value="Add To Inventory" name="submit" id="submit" class="btn btn-primary btn-lg btn-block error-w3l-btn">
Also replace $(form).submit(function(e) { with $("#submit").click(function(e) { if you want to call the AJAX code in your JS file on click of the button.

Submit a Form via a Reveal Modal

I am trying to submit a form and open a modal with the forms post data on it.
Modal works fine but the form post is not passed through.
I have tried jquery/ajax but no luck.
<form id="frmTractors" method="post" action='process.php'>
<select id="tractor" name="tractor_number">
<options...>
</select>
<input type="submit" value="Submit" data-reveal-id="myModal" data-reveal-ajax="process.php" />
</form>
<!-- ### MODAL ### -->
<div id="myModal" class="reveal-modal" data-reveal></div>
I am running something similar on a site:
HTML
<input type="hidden" id="processURL" value="process.php">
<select id="tractor" name="tractor_number">
<options...>
</select>
JQUERY
$(function() {
$( "#tractor" ).change(function(){
var url = $('#processURL').val();
var tractor_number = $(this).val();
var postit = $.post( url, {tractor_number:tractor_number});
postit.done(function( data ) {
$('#myModal').foundation('reveal', 'open');
});
});
});
You don't need a form, just a hidden input to hold your process file URL.

Page is reloading when form submit usng jquery ajax

I am trying to submit a form using jquery ajax. My problem is when I submitting the form its submitting but my page is reloading. I tried using preventDefault(). But I still couldn't figure this out.
This is the HTML for my form:
<form action="" method="post" id="addCategoryForm">
<div class="form-group">
<input type="text" class="form-control" id="new_category" name="new_category" autofocus>
</div>
<div class="form-group">
<select class="form-control" name="parentCategoryList">
<option value="">-- Parent Category --</option>
<option value="">Lorem ipsum</option>
<option value="">Lorem ipsdffum</option>
</select>
</div>
<div class="form-group">
<button class="btn btn-default" id="addCategory">Add New Category</button>
</div>
</form>
This is how I tried it using jQuery:
$(document).on('click', 'button#addCategory', function (e) {
//e.preventDefault();
var data = $("form#addCategoryForm").serialize();
$.ajax({
type: "POST",
url: "./includes/process.php",
data: data,
cache: false,
beforeSend: function() {
window.tr.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function (response) {
$('#success').html(response);
$("#success-alert").fadeTo(2000, 500).slideUp(1000, function(){
$("#success-alert").alert('close');
});
}
});
//return false;
});
When I uncomment e.preventDefault(); form is not sumbitting. If I comment it form is submitting but page is reloading.
Can anybody tell me whats the problem of this?
Hope somebody may help me out. Thanks in advance.
You should listen to the submit event, your elements were enclosed by a form
Try this event
$('#addCategoryForm').on('submit', function(e) {
e.preventDefault();
//Do ajax here
}
try this
<div class="form-group">
<button type="button" class="btn btn-default" id="addCategory">Add New Category</button>
</div>
Please note that i have added type="button" . This is because, when no type is mentioned, by default it takes it as a submit button. And that is the reason why page reloads

Form does not work after clicking close button of bootstrap alert

Im facing a really strange problem here. I use bootstrap for some of my tooltips alerts etc. Now I have a ajax form that responds error messages in a alert if something is wrong. This all works fine but when i click the "close" button of the alert box the alert dissapears but then the form submit button does not work anymore? I dont know why it's behaviour is like this can someone help me out?
Also, when i do not close the alert, then when I enter new data and click on submit it does submit. Only after closing alert form does not submit anymore
Form (with error div)
<!-- ERROR BOX -->
<div id="regError" class="alert alert-error" style="margin-right: 20px; display: none;"></div>
<!-- ERROR BOX -->
<form id="registerform" action="ajax/register.php" method="post">
<fieldset> <span class="help-block"><B>Jou gegevens</B></span>
<input name="username" class="span4" type="text" value="Gebruikersnaam" onblur="onBlur(this)" onfocus="onFocus(this)" placeholder="Gebruikersnaam">
<input name="email" class="span4" type="text" value="Email adres" onblur="onBlur(this)" onfocus="onFocus(this)" placeholder="Email adres">
<input class="span4" type="text" value="Email adres (opnieuw)" onblur="onBlur(this)" onfocus="onFocus(this)" placeholder="Email adres (opnieuw)">
<input class="span4" type="text" value="Wachtwoord" onblur="onBlur(this)" onfocus="onFocus(this)" placeholder="wachtwoord">
</fieldset>
<button type="submit" class="btn btn-primary" >Save changes</button>
<button type="button" class="btn">Cancel</button>
javascript ajax call
$(document).ready(function () {
$("#registerform").submit(function () {
//Get al form data This = form and EL is element of the form
var el = $(this),
// get form action and method attribute
url = el.attr('action'),
type = el.attr('method'),
// emty data array to fill with form data
data = {}
// The loop to get al form data
el.find('[name]').each(function (index, value) {
var el = $(this)
name = el.attr('name'),
value = el.val();
//make data object
data[name] = value;
});
//Do the ajax call
$.ajax({
type: type,
url: url,
data: data,
success: function (response) {
$('#regError').html(response);
$('#regError').fadeIn();
}
})
return false;
})
})
the PHP is just to test if it works..
<?php
if (isset($_POST)) {
echo '<button type="button" class="close" data-dismiss="alert">×</button>';
print_r($_POST);
}
Well because i could not find a solution i just removed the close button.

Categories