Form submitting on return false - javascript

I have the following form:
<form id="sizeForm" style="float:right;">
<input value="test" name="comments" type="text">
<input class="btn-sm btn-main" value="Save" type="submit">
</form>
Which I'm trying to submit using ajax but the form is posting, here's the JQuery:
$("#sizeForm").submit(function () {
$.ajax({
type: "POST",
url: "/ajax/actions/editSize.php",
data: $(this).serialize(),
success: function (dataBack) {
$('#size2'+dataBack).fadeOut().promise().done(
function(){
$('#size1'+dataBack).fadeIn();
}
);
}
});
return false;
});
Any ideas where I'm going wrong?

The issue may be with your PHP script (which you haven't provided), but here are some ideas.
HTML:
<form id="sizeForm" style="float:right;">
<input value="test" name="comments" type="text">
<input class="btn-sm btn-main" value="Save" type="submit">
</form>
javascript:
$("#sizeForm").on('submit', function () {
$.ajax({
type: "POST",
url: "/ajax/actions/editSize.php",
data: $(this).serialize(),
success: function (dataBack) {
$('#size2'+dataBack).fadeOut().promise().done(
function(){
$('#size1'+dataBack).fadeIn();
}
);
}
});
return false;
});
In your PHP script add something like this so you know the value is received. This will show in the network tab in the browser developer tools.
if (!empty($_POST['comments'])) {
echo "form submitted!";
exit;
}
In the network tab, you should see an entry like POST editSize.php. If you don't see it, the form was not sent. If you do see it, open it up and look at the "post" tab. This will show you what was sent. Then, your "response" tab will show you the output from your PHP script.

Related

Form not submitting on ajax request

So I'm comparing the value of the input field entered by the user to the value of the mysql DB (using an Ajax request to the checkAnswer.php file). The request itself works fine, it displays the correct "OK" or "WRONG" message, but then it does not submit the form if "OK". Should I put the .submit() somewhere else?
HTML code:
<form id="answerInput" action="index" method="post">
<div id="answer-warning"></div>
<div><input id="answer-input" name="answer" type="text"></div>
<input type="hidden" id="id" name="id" value="<?=$id?>">
<div><button type="submit" id="validate">Valider</button></div>
</form>
</div>
JS code
$("#validate").click(function(e){
e.preventDefault();
$.post(
'includes/checkAnswer.php',
{
answer : $('#answer-input').val(),
id : $('#id').val()
},
function(data){
if(data === '1'){
$("#answer-warning").html("OK");
$("#answerInput").submit();
}
else{
$("#answer-warning").html("WRONG");
}
},
'text'
);
});
I think it is because you set your button type as submit. Why?
When you do $("#validate").click(function(e){, you implicitly replace the default submit behavior of the form.
As you want to interfere in the middle of the process for extra stuff, I suggest you change the button type to button or simply remove the type attribute.
Then the $("#validate").click(function(e){ will alter behavior of click, not the submit of form.
<form id="answerInput" action="index" method="post">
<div id="answer-warning"></div>
<input id="answer-input" name="answer" type="text">
<input type="hidden" id="id" name="id" value="<?=$id?>">
<button onlcick="validate()">Valider</button>
</form>
/******** JS ************/
function validate(){
var post = {};
post['answer'] = $('#answer-input').val();
post['id'] = $('#id').val();
$.ajax({
url: 'includes/checkAnswer.php',
type: 'POST',
data: {data: post},
success:function (data) {
console.log('succsess');
},
error:function (jQXHR, textStatus, errorThrown) {
console.log('failure');
}
});
}

JavaScript ActiveElement is form not button with Safari

I have a list of forms on my site with JS/AJAX that submits the forms on click. The JavaScript determines the submit type based on the active element. This has been working find across multiple browser.
Problem: Basically Safari (Version 10.0.2) on MAC considers the activeElement the form instead of the button so the getAttribute returns null. Is there a way to get the clicked element? I need to know which button the user clicked.
HTML Stuff:
<div id="#Records">
<form action="update.php" method="post">
...
<input name="submit" type="submit" data-action="send" value="send stuff" />
<input name="submit" type="submit" data-action="update" value="update" />
<input name="submit" type="submit" data-action="delete" value="delete" />
</form>
</div>
JavaScript stuff
$("#Records form").submit(function (e) {
e.preventDefault();
var url = this.action;
var data = $(this).serializeArray();
var action = document.activeElement.getAttribute('data-action');
data.push({ name: 'submit', value: action });
$.ajax({
type: "POST",
data: data,
cache: false,
url: url
}).done(function (data) {
$("#Records").html(data);
}).fail(function (result) {
ShowMessage("Error updating record!");
});
return false;
});
Can't you get the element using e.currentTarget instead of the active element? Something like
var action = $(e.currentTarget).attr('data-action');
(I'm assuming button click leads to the submit)
Ok, based on Tiny Giant and other comments I have changed the code to this. Not sure it is the best method but seems to work everywhere I have tested.
note simplified, comments welcome
HTML
<div id="#Records">
<form action="update.php" method="post">
...
<input type="button" onclick="return $(this).processRequest(this, 'send');" data-action="send" value="send stuff" />
<input type="button" onclick="return $(this).processRequest(this, 'update');" data-action="update" value="update" />
<input type="button" onclick="return $(this).processRequest(this, 'delete');" data-action="delete" value="delete" />
</form>
</div>
JavaScript
jQuery.fn.processRequest =
function(button, action)
{
var form = $(button).parents('form');
var url = form[0].action;
var data = $(form).serializeArray()
data.push({ name: 'submit', value: action });
$.ajax({
type: "POST",
data: data,
cache: false,
url: url
}).done(function (data) {
$("#Records").html(data);
}).fail(function (result) {
ShowMessage("Error updating record!");
});
return false;
}

How to submit an ajax form post that has loaded dynamically in a bootstrap modal window?

I'm going to make this as concise as possible. I'm loading this form dynamically in a modal window in Bootstrap. But when I submit it...instead of posting via ajax, the whole page is submitted. What can I do to submit via AJAX (in the background) while saving the state of the page? Here is the code that loads into the modal div element:
<script>
$(function(){
$('.modal form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: "index2.html",
type: "POST",
data: $("multiform").serialize(),
success: function(data){
alert("Successfully submitted.")
}
});
});
});
</script>
<form name="multiform" id="multiform" action="index2.html" method="POST" >
Name: <input type="text" name="name" value="Ravi"/> <br/>
Age :<input type="text" name="age" value="1" /> <br/>
<input type="submit" value="Save" name="save" class="btn btn-primary" style="margin-top: 2px; height: 27px; width: 89px;" ></input>
</form>
I figured it out. I needed to surround the code with $(document).ready() and I needed to reference the data to serialize via '.modal form'. Once I did that, everything worked well.
$(document).ready( function() {
$('.modal form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: "index2.html",
type: "POST",
data: $('.modal form').serialize(),
success: function(data){
alert(data);
}
});
});
});

ajax on submit no refresh form using php

ok so i know this ajax works, but i cant seem to understand why it's not submitting here.
<script type="text/javascript">
$(function(){
$('input[type=submit]').click(function(){
$.ajax({
type: "POST",
url: "postitem.php",
data: $("#myform").serialize(),
beforeSend: function(){
$('#result').html('<img src="loading.gif" />');
},
success: function(data){
$('#result').html(data);
}
});
});
});
submit form
<form action="" method="post" onsubmit="return false;" id="myform">
submit button
<input type="hidden" value="Post" name="submit" />
<button type="submit" title="Done" style="height:33px; width:50px">
<img src="../../css/images/plus_25.png" />
</button>
i'm pretty something is wrong with the button, but i want to keep the way the button is because alot of my other forms use this same button, thanks if you can explain to me why click this submit button does nothing.
You are selecting an <input> instead of a <button>. I had success by changing your jQuery selector from this:
$('input[type=submit]')
to this:
$('button[type=submit]')
http://jsfiddle.net/H3Bcc/
Not all browsers interpret a click attached to a submit button as submitting the form so you are effectively just negating the click of that button.
Preventing a form submission should preferably be captured by attaching the submit handler to the <form> when you have a <input type="submit"> or <button type="submit> so this is the best way to assure success:
jQuery
$(function(){
$('#myform').on('submit', function(e){
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'), // <-- get method of form
url: $(this).attr('action'), // <-- get action of form
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
$('#result').html('<img src="loading.gif" />');
},
success: function(data){
$('#result').html(data);
}
});
});
});
HTML
<form action="postitem.php" method="POST" id="myform">
<input type="hidden" value="Post" name="submit" />
<button type="submit" title="Done" style="height:33px; width:50px">
<img src="../../css/images/plus_25.png" />
</button>
</form>
try this :
<script type="text/javascript">
$(function(){
$('input[type=submit]').click(function(e){
e.preventDefault(); // prevent the browser's default action of submitting
$.ajax({
type: "POST",
url: "postitem.php",
data: $("#myform").serialize(),
beforeSend: function(){
$('#result').html('<img src="loading.gif" />');
},
success: function(data){
$('#result').html(data);
}
});
});
});

Serialize checkboxs within Ajax call using jQuery

i need to serialize form input to send an Ajax call using jQuery to php script and each time i tried to print out the values of the form it gives empty array .
HTML Form
<form class="form-horizontal" id="generateCompression" method="post">
<fieldset>
<div class="control-group"><label class="control-label">Checkboxes</label>
<div class="controls">
<input type="checkbox" name="names[]" value="Jan-2011"> Jan-2013</label>
<input type="checkbox" name="names[]" value="Jan-2012"> Jan-2013</label>
<input type="checkbox" name="names[]" value="Jan-2013"> Jan-2013</label>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Generate</button>
<button type="reset" class="btn">Cancel</button>
</div>
</fieldset>
</form>
Javascript
$(document).ready(function(){
$("#result").hide();
$("#generateCompression").submit(function(){
$.ajax({
url: "compare-action.php",
type: "POST",
data: $("#generateCompression").serialize(),
async: true,
beforeSend : function (){
$("#loading").show();
$("#reportFilecreate").fadeOut();
},
success: function(response) {
$("#loading").hide();
$("#error").show();
$("#error").html(response);
}
});
return false;
});
});
this is the PHP file
<?php
$inputs = $_POST;
print_r($inputs);
?>
Checkboxes do not send anything to the server if at least one checkbox is not checked.
Your script needs to check for the existence of your form field, if the formfield doesnt exist then you know nothing has been checked.
To test simply add a text box to your form and then run your script again.
Try this.
Send serialized data in one variable like
$.ajax({
url: "compare-action.php",
type: "POST",
traditional: true,
data: {
"test_data" : $("#generateCompression").serialize()
},
async: true,
beforeSend : function (){
$("#loading").show();
$("#reportFilecreate").fadeOut();
},
success: function(response) {
$("#loading").hide();
$("#error").show();
$("#error").html(response);
}
});
And in the compare-action.php file
print_r($_POST("test_data"));

Categories

Resources