Page is reloading when form submit usng jquery ajax - php

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

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

How to fix ajax that loads a class on a page?

I made a comment column by putting process.php in the page header, but when I want to load a #comment-list, 1 page entered into the div.
I've tried changing ajax.url and it works, but it will affect the entire system that was created.
I want to load this part when ajax is successful
HTML
<div id="comment-list" class="widget-body">
<?php news_comment($server_conn,$id_news); ?>
</div>
FORM
<form action="<?php echo FullURL() ?>" method="post" id="newcomment">
<div class="form-group">
<label for="comment">* Comment:</label>
<textarea class="form-control" rows="3" name="text_comment" placeholder="Your Comment" required></textarea>
</div>
<button type="submit" class="btn btn-primary" id="submit-comment" name="submit-comment" value="<?php echo $row['id_news']; ?>">Post Comment</button>
</form>
AJAX
$("#submit-comment").click(function(event){
event.preventDefault();
var submit = $(this).attr('value');
var post_url = $("#newcomment").attr("action");
var request_method = $("#newcomment").attr("method");
var form_data = $("#newcomment").serialize();
$.ajax({
url : post_url,
type: request_method,
data : form_data + '&submit-comment=' + submit,
success: function(){
$("#newcomment")[0].reset();
$("#comment-list").load(post_url + "#comment-list");
}
})
});
When Ajax responds successfully, I want #comment-list loads automatically, without entering a 1-page display

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

Passing variable data between jQuery and PHP using AJAX shorthand

I'm trying to create a search feature that searches a database based on the criteria a user has entered. Right now, I'm just trying to get the jQuery variable data into PHP. I've decided to use the shorthand AJAX $.post method because this is just a demo project. I know there are numerous similar questions like mine, but I have yet to find an answer to any of them that I can use.
So what I'm trying to do is, the user will click on a drop down menu and select an option. AJAX then sends the selected value to the PHP file and the PHP will eventually perform a database search based on what was selected. The issue is, in PHP, I'm getting a string of "Search" when the data is parsed and I echo it but when I do a console log on the variable that was sent, I'm getting the correct text. Can anyone tell me where I'm going wrong?
Here's what I have so far.
AJAX
$("#search_form").on("submit", function(ev){
ev.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
console.log(data);
})
})
PHP
ob_start();
require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo $criteria;
HTML
<form id="search_form" method="post">
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search" id="search" />
<input type="submit" class="button" value="Search_Now" />
</fieldset>
As Requested
Here is a fiddle of the drop down menu to show how it works.
http://jsfiddle.net/xvmxc0zo/
Your form is being submitted via default form submission; the ajax call is misplaced, it should be within the submit handler, which should prevent default form submission.
Note that I have removed both name and id attributes from the submit button; you do not need them. Just let the submit button do it's job and listen for the submit event on the form where you would then use event.preventDefault(); to make sure the form does not submit, then you can make your ajax call.
$("#searchBy").on("click", ".option", function(){
$('#search').val( $(this).text() );
});
$('form').on('submit', function(e) {
e.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
//jsonData = window.JSON.parse(data);
console.log( data);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="hidden" name="search" id="search" />
<input type="text" name="search_text" id="search_text" />
<input type="submit" class="button" value="Search" />
</fieldset>
</form>
In your PHP use echo $criteria; instead of echo json_encode($criteria);.
I'd suggest to use the way of jQuery documentation to check changes in your drop down.
$( "select" ).change(function () {
$( "select option:selected" ).each(function() {
$.post("../php/test.php", {search: $(this).text()}, function(data){
jsonData = window.JSON.parse(data);
});
});
})
You are getting "Search" on the PHP side because that is the value of your submit button.
You want the post to occur when you click on an option? Try adjusting your selector as follows:
$("#searchBy .option").on("click", function () {
var search = $(this).text().trim();
$.post("../php/test.php", { search: search }, function (data) {
jsonData = window.JSON.parse(data);
})
});
I think your header.php is provoking the error. I created a test file myself with your code and that works perfectly fine:
<?php
if($_POST)
{
ob_start();
//require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo json_encode($criteria);
exit;
}
?>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search_text" id="search_text" />
<input type="submit" name="search" id="search" class="button" value="Search" />
</fieldset>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$("#searchBy").on("click", ".option", function(){
var search = $(this).text();
$.post("<?=$_SERVER['PHP_SELF']?>", {search: search}, function(data){
jsonData = window.JSON.parse(data);
console.log(jsonData); //Prints the correct string
})
});
</script>

How do I prevent AJAX from sending me to the top of the page?

I have the following signup form near the bottom of a new website. As soon as the AJAX response loads, the page skips to the top of the page. As far as I can tell, I have included "return false" correctly. What am I missing? Thank you!
## index.php ##
<script type="text/javascript" src="mailing-list.js"></script>
<div class="signup container">
<form id="signup-form" action="<?=$_SERVER['PHP_SELF']; ?>" method="get">
<fieldset>
<legend><h2 style="align:center;">Enter Your Email Address</h2></legend>
<div class="row">
<div class="offset4 span3">
<input class="email" type="text" name="email" id="email" />
</div>
<div class="span1">
<input type="submit" name="submit" value="Join" class="btn btn-large btn-primary" />
</div>
</div>
<div id="response">
<? require_once('inc/store-address.php'); if($_GET['submit']){ echo storeAddress(); } ?>
</div>
</fieldset>
</form>
</div>
## and mailing-list.js ##
$(document).ready(function() {
$('#signup-form').submit(function() {
// update user interface
$('#response').html('Adding email address');
// Prepare query string and send AJAX request
$.ajax({
url: 'inc/store-address.php',
data: 'ajax=true&email=' + escape($('#email').val()),
success: function(msg) {
$('#response').html(msg);
}
});
return false;
});
});
$(document).ready(function() {
$('#signup-form').submit(function(e) {
e.preventDefault();
// update user interface
$('#response').html('Adding email address');
// Prepare query string and send AJAX request
$.ajax({
url: 'inc/store-address.php',
data: 'ajax=true&email=' + escape($('#email').val()),
success: function(msg) {
$('#response').html(msg);
}
});
return false;
});
});
I doubt it is executing the default form submit behavior. Prevent it byt using the preventDefault method.
$(function(){
$('#signup-form').submit(function(e) {
e.preventDefault();
//your existing code goes here
});
});
You need to prevent the form from submitting the data (even if it is to the same file). Otherwise the page will reload before your ajax call is done. You do this with .preventDefault();
Try
...
$('#signup-form').submit(function(event) {
event.preventDefault();
// update user interface
...

Categories