Prevent Default for Ajax created form - php

I am getting the form on click from a file called test.php which contains the following:
<form method="post" class="adminTM">
<input type="hidden" name="execID" value="<?=$_POST['exec']?>" />
<input type="hidden" name="fromTM" value="<?=$_POST['TM']?>" />
<input type="text" name="toTM" value="<?=$_POST['TM']?>" />
<input type="hidden" name="symbol" value="<?=$_POST['symbol']?>" />
<button class="submitTM">SUBMIT</button>
</form>
The javascript looks like so:
$(function(){
$('.adminTMClick').live('click', function(e){
$(this).data('TM', this.innerHTML);
$.post('test.php', $(this).data(), function(data){
$(data).dialog({
modal: true,
beforeClose: function(){
$(this).remove();
}
});
console.log($('.adminTM'));
console.log($('.submitTM'));
});
});
$('.submitTM').live('click', function(e){
//originally had .adminTM with submit which failed
e.preventdefault();
alert('i am here');
return false;
});
});
How do i make it so that the form DOES NOT do the default submit action when the submit button is clicked?
Here is a fiddle that demonstrates basically what I am doing (i had to change it a bit because of the way jsfiddle works): http://jsfiddle.net/maniator/tQVnV/show/

You should use the submit() event on the form instead of the click() on the submit, since pressing enter will still submit the form (bypassing the submit button).
This should properly prevent the form from doing the default submit:
$('.adminTM').live('submit', function(e) {
// execute custom code
console.log("submit event fired");
// prevent default submit
return false;
});
jsFiddle: http://jsfiddle.net/bjorn/tQVnV/11/

Related

Problems about keep in the page with ajax

I have a form. My objective is send and insert the values of the form to my database. Then
Clear the input of the form
Show the successful message.
Like this:
My problems:When I press the "save" button, I am redirected to another page.
This is the operating error:
and change the page
¿What is the problem on my code?
html
<html>
<head><title>Insert Data Into MySQL: jQuery + AJAX + PHP</title></head>
<body>
<form id="myForm" action="userInfo.php" method="post">
Name: <input type="text" name="name" /><br />
Age : <input type="text" name="age" /><br />
<button type="submit" id="sub">Save</button>
</form>
<span id="result"></span>
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/elscript.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js">
</script>
</body>
</html
This is my script
$("#myForm").submit( function(e) {
// Prevent the normal form submission event
e.preventDefault();
// Create an object of the form
var form = $(this);
// Make an AJAX request
$.post(this.action, form.serializeArray(), function(info) {
// Clear the form
form[0].reset();
// Display message
$("#result").html(info);
});
});
Finally, my code to insert
<?php
$conn = mysql_connect('localhost', 'root', '');
$db = mysql_select_db('practicas');
$name = $_POST['name'];
$age = $_POST['age'];
if(mysql_query("INSERT INTO ajaxtabla VALUES('$name', '$age')"))
echo "Successfully Inserted";
else
echo "Insertion Failed";
?>
Thanks for help me
You can simplify the code by having just one event handler for when you submit the form. Additionally, you need to include e.preventDefault() which prevents the normal function of the submit button.
$("#myForm").submit( function(e) {
// Prevent the normal form submission event
e.preventDefault();
// Create an object of the form
var form = $(this);
// Make an AJAX request
$.post(this.action, form.serializeArray(), function(info) {
// Clear the form
form[0].reset();
// Display message
$("#result").html(info);
});
});
Give your button a type attribute as well to ensure your form submits upon clicking.
<button type="submit" id="sub">Save</button>
Demo
$(function() {
$("#myForm").submit(function(e) {
// Prevent the normal form submission event
e.preventDefault();
console.log('onsubmit event handler triggered');
// Create an object of the form
var form = $(this);
// Make an AJAX request
/*$.post(this.action, form.serializeArray(), function(info) {
// Clear the form
form[0].reset();
// Display message
$("#result").html(info);
});*/
// fake AJAX request
setTimeout(function(){
// Clear the form
form[0].reset();
// Display message
$("#result").html('Successfully Inserted');
}, 3000);
});
});
<form id="myForm" action="userInfo.php" method="post">
Name: <input type="text" name="name" /><br /> Age : <input type="text" name="age" /><br />
<button type="submit" id="sub">Save</button>
</form>
<span id="result"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
In ajax you are posting the form with its action so it will be redirected confirm
If you don't want to redirect then send ajax request like this
$.ajax({
method:post,
url:"File name you want to send request"
}).done(function(response){
});

jQuery submit form via submit button

Is it possible to submit a form by clicking a div-element as if it was submitted by the submit button?
So that this PHP works:
if(isset($_POST["share"])) { /* do something*/ }
Form:
<form id="form" action="publish.php" method="POST">
<textarea name="description" maxlength="500">Description...</textarea>
<input type="submit" name="share" value="Share" />
</form>
This does NOT post the share value, $_POST['share'].
if($(".post-form").length){
$(".post-form").click(function(event) {
$("#form").submit();
return false;
});
}
Yes this is possible by using the .submit() function. You can use it like so:
// Wait until the document has been fully loaded
$(document).ready(function() {
// Bind a click event to your element
$('div').click(function(event) {
// Submit the form
// The callback should add a hidden field with the name "share"
$('form').submit(function(eventObj) {
$('<input />').attr('type', 'hidden')
.attr('name', "share")
.attr('value', "Share")
.appendTo('form');
return true;
});
});
});
You can find more information here
Demo: jsfiddle
Set an id for submit button:
<input type="submit" name="share" value="Share" id="btn_submit" />
then you can control it in jquery like this:
$("#btn_submit").onclick(function(){
if(condition==true)
{
return true;
}
else
{
return false;
}
});

jQuery form plugin , how to submit only visible fields

Using the jQuery form plugin, I just want to submit the visible fields (not the hidden ones ) of the form.
HTML:
<div class="result"></div>
<form id="myForm" action="comment.php" method="post">
Name: <input type="text" name="name" />
Comment: <textarea name="comment"></textarea>
<div style="display:none;">
<input type="text" value="" name="name_1" />
</div>
<input type="submit" value="Submit Comment" />
</form>
I cannot find a way to submit only the visible fields using any of the methods below:
ajaxForm:
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
ajaxSubmit:
$('#myForm').ajaxSubmit({
target: '.result',
success: function(response) {
alert("Thank you for your comment!");
}
});
There is another method formSerialize but found no way to use it with the 2 methods mentioned above (usable with $.ajax however).
How to submit only the visible fields using any of the two methods ?
$("#myForm").on("submit", function() {
var visibleData = $('#myForm input:visible,textarea:visible,select:visible').fieldSerialize();
$.post(this.action, visibleData, function(result) {
alert('Thank you for your comment!');
});
// this is needed to prevent a non-ajax submit
return false;
});

How to have two buttons in a same form to do different actions in ajax?

I have a form, which take name from form and it sends to javascript codes and show in php by Ajax. these actions are done with clicking by submit button, I need to have another button, as review in my main page. how can I address to ajax that in process.php page have "if isset(submit)" or "if isset(review)"?
I need to do different sql action when each of buttons are clicked.
how can I add another button and be able to do different action on php part in process.php page?
<script type="text/javascript">
$(document).ready(function(){
$("#myform").validate({
debug: false,
submitHandler: function(form) {
$.post('process.php', $("#myform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
</script>
<body>
<form name="myform" id="myform" action="" method="POST">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value=""/>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<div id="results"><div>
</body>
process.php:
<?php
print "<br>Your name is <b>".$_POST['name']."</b> ";
?>
You just need to add a button and an onclick handler for it.
Html:
<input type="button" id="review" value="Review"/>
Js:
$("#review").click(function(){
var myData = $("#myform").serialize() + "&review=review";
$.post('process.php', myData , function(data) {
$('#results').html(data);
});
}
);
Since you have set a variable review here, you can use it to know that is call has come by clicking the review button.
Bind the event handlers to the buttons' click events instead of the form's submit event.
Use the different event handler functions to add different pieces of extra data to the data object you pass to the ajax method.

Disable the enter key on a jquery-powered form

I have a form using the form jQuery plug in to handel the posting of the data. In the example i am working with the data is psoted to another php file which reades a database and echos back a result which is displayed below the from.
The code works very well with one glitch. If you hit the enter button while the text filed is selected everything cleared including the result that has been written to the screen. Is it possible to disable to enter key and prevent it from doing this?
FORM:
<html>
<head>
</head>
<p>enter code here
<form name="form" action="" method="">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name"/>
<input type="button" value="get" onclick="get();"/>
</form>
<div id="age"></div>
</p>
</body>
</html>
SCRIPT:
function get() {
$.post('data.php', {name: form.name.value},
function(output) {
$('#age').hide().html(output).fadeIn(1000);
});
}
}
Cheers.
You should consider using the jQuery Forms Plugin. It will save you from doing some of the dirty work, additionally it will intercept all ways of submitting the form - so instead of having to disable the RETURN key it will submit your form via AJAX.
If you don't want that, get rid of the button with the onclick event and replace it with a submit button and register your function as a onsubmit handöer:
$('form[name=form]').submit(function(e) {
e.preventDefault();
$.post('data.php', {name: form.name.value},
function(output) {
$('#age').hide().html(output).fadeIn(1000);
});
}
});
$(document).ready(function(){
$('form').submit(function(){
return false;
});
});
This will prevent the form from submitting, however the form will not work at all for users with javascript disabled.
A found some tuts and solved the issue.
I just put this in before my Jquery code to disable the enter button.
$(function () {
$('input').keypress(function (e) {
var code = null;
code = (e.keyCode ? e.keyCode : e.which);
return (code == 13) ? false : true;
});
});

Categories