jQuery form submit not working php - 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.

Related

My HTML form has its action linked to php code. When the submit button is clicked though, the form redirects to the PHP file. How can I prevent this?

I have a signup form in my HTML file. The action of the form is a PHP file. I want the PHP to process the entered data and leave the user on the signup page (HTML.) However, when the submit button is clicked, the website redirects to the PHP file. Is there some way of preventing this?
I have tried setting the form's target to "_self", but that didn't help.
HTML:
<? include('signup.php'); ?>
<?php include('errors.php'); ?>
<form method="post" action="signup.php">
***More Input fields here***
<button type="submit" name="submit">Sign Up</button>
you can actually leave that empty, so the same page gets targeted :)
Remove or blank the action attribute in form like as:
HTML:
<?php include('signup.php');
include('errors.php');
?>
<form method="post">
***More Input fields here***
<button type="submit" name="submit">Sign Up</button>
</form>
If you don't want to refresh the page and handle user input you can use AJAX
Simple example:
<form>
<label for="username">
Username
<input type="text" id="username">
</label>
<label for="password">
Password
<input type="password" id="password">
</label>
<button id="submit"></button>
</form>
<script>
$(function () {
$('#submit').click(function () {
$.ajax({
method: 'POST',
url: 'signup.php',
data:
{
name: $('#username').val(),
password: $('#password').val()
}
}).done(function (msg) {
alert('Data Saved: ' + msg);
});
});
});
</script>
If you want to send POST request to the same page, just remove action attribute from the form
<form method="post">
***More Input fields here***
<button type="submit" name="submit">Sign Up</button>

Jquery and AJAX not even triggering

I have this piece of code.
It's a input for a newsletter.
<form id="newsletter-form" name="newsletter-form" method="post" action="/newsletter">
<div class="form-group">
<label for="exampleInputEmail1"><span>Cadastre-se em nossa newsletter</span></label>
<input type="email" class="form-control" id="newsletter-email" name="newsletter-email" placeholder="e-mail" value="">
</div>
<button class="btn btn-secondary btn-block" type="button"><i class="fas fa-paper-plane fa-fw mr-1"></i>Cadastrar</button>
</form>
Quite simple!
And I have this JS:
$(function()
{
var form = $('#newsletter-form');
// ----------
$(form).submit(function(form_response)
{
form_response.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response)
{
$('#newsletter-email').removeClass('is-invalid');
$('#newsletter-email').addClass('is-valid');
$('#newsletter-email').val(response);
})
.fail(function(data)
{
$('#newsletter-email').removeClass('is-valid');
$('#newsletter-email').addClass('is-invalid');
if (data.responseText !== '')
{
$('#newsletter-email').val(data.responseText);
}
else
{
$('#newsletter-email').val('Ocorreu um erro!');
}
});
});
});
My PHP check if email is valid, if already is inserted, etc, etc.
The PHP returns codes and echos correctly(I use it on other parts of my website)
The thing is:this form is not even triggering the JS to run the PHP.
It should run the PHP and add a is-valid or is-invalid class on the inpute and show the feedback as value or placeholder.
Any ideas why it's not working?
Just to add it as answer your button type was button not submit so eaither use input type submit or change button type to submit :D
This is your original code. var form = $('#newsletter-form');
Since you have put the form tag into a variable, you don't need to use $. Change $(form) into form. The code will look like this.
form.submit( /* some code */ );
or if you don't want to store it into variable, you can directly call the function from jquery.
$('#newsletter-form').submit( /* some code */ );

JQuery Ajax post method is not working in laravel

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
});
});

Show Jquery dialog in previous page

This is my registration form located in login.html:
<form action="Registar.php" method="post">
<input type="text" name="user" placeholder="Username (Sem espaços)" maxlength="25">
<input type="text" placeholder="Email" name="email" maxlength="31"/>
<input type="text" name="nome" placeholder="Nome" maxlength="31"/>
<input type="text" name="morada" placeholder="Morada" maxlength="120"/>
<input type="hidden" name="action" value="login">
<input type="number" name="telefone" placeholder="Telefone" maxlength="15"/>
<button type="submit" class="btn btn-default" name="submit">Signup</button>
</form>
It goes to "Registar.php" and runs the verification's i want like if the fields are empty or if the username already exists and show's that verification's in a jquery dialog.
Heres my Jquery script:
function alerta(msg,link){
var dialog = $('<div>'+msg+'</div>');
$(function() {
$( dialog ).dialog({
modal: true,
buttons: {
Ok: function() {
window.location = link;
}
}
});
})
};
The thing is it shows the dialog on the blank page of "Registar.php" and since i scripted some nice styles and overlays for my jquery dialog i want to show the jquery dialog verification messages in login.html and have that page in the background/overlay of the dialog.
Is there any way to do that but still running the action form to an external php script?
Thanks in advance!
One way to achieve this would be to use AJAX instead of sending the form via POST. Here's an example:
HTML
<form id="myForm" action="" method="post">
//your form content
</form>
JQuery
$('#myForm').on('submit', function(e) {
e.preventDefault(); //stop form submission
var formData = $(this).serialize();
$.ajax({
type: "POST",
url: "Registar.php",
data: formData,
success: function(result) {
//result is the value returned from Registrar.php
console.log(result);
//show the modal
}
});
});
JSFiddle

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