I have a form for Tags that is working OK, with some server validation, I would like to add a Jquery to submit the content without refreshing:
<form method="post" action="tags">
<div>
<input type="hidden" name="id" value="getId()" />
<input type="text" name="tag" />
<input type="submit" value="Add" name="add" />
</div>
</form>
Any advice will be highly appreciated.
Check out the jQuery Form Plugin. Using it, you can submit a form without reloading the page like so:
<form id="aForm" action="target.php" method="post>
...
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#aForm").ajaxForm();
});
</script>
The ajaxForm() function also supports all options (such as a callback function) that can be passed to the standard jQuery $.ajax function.
$(document).ready(function() {
$(form).submit( function() { // could use $(#submit).on('click', function(){ as well
$.ajax({
url: 'yourposturl',
data: $(form).serialize(),
Success: function() {
alert('ok');
}
}); //end ajax
return false;
}); //end submit()
});
Should take all form vars , serialize them so the server can receive, the return false is so page doesnt refresh on submit (stops propagation and default)
Add the JQuery javascript library
Turn the submit into a button
<button id="submitbutton" >Add</button>
Add ids to your inputs
<input type="text" id="tag" name="tag" />
And add the jquery to the click for the button ...
<script type="text/javascript">
$(document).ready(function() {
$("#submitbutton").button().click(function(){
$.post("tags.php",{id: $("#id").val(), tag: $("#tag").val()});
});
});
</script>
<form method="post" action="tags">
<div>
<input type="hidden" name="id" value="getId()" />
<input type="text" name="tag" />
<input class="button" type="button" value="Add" name="add" />
</div>
</form>
$(function(){
$('.button').click(function(){
var data = $('form').serializeToObject();
$.post('tags.php', data);
});
});
// jQuery Extension to serialize a selector's elements to an object
$.fn.serializeToObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Related
I 'm beginner, In dynamically added Input fields Reference From: Validate Dynamically Added Input fields, when passed Validation and submit cannot to another page
Follow script sample.
<script src="js/jquery-3.1.1.min.js"></script>
<script src="js/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('form.commentForm').on('submit', function(event) {
// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
})
});
// prevent default submit action
event.preventDefault();
// test if form is valid
if($('form.commentForm').validate().form()) {
console.log("validates");
} else {
console.log("does not validate");
}
})
// set handler for addInput button click
$("#addInput").on('click', addInput);
// initialize the validator
$('form.commentForm').validate();
});
</script>
when passed validation click submit butt cannot to action="/action_page_post.php"
And HTML code
<form class="commentForm" method="get" action="/action_page_post.ph">
<div>
<p id="inputs">
<input class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>
Changes I made
changed on('submit') to submitbutton.onclick
added $('.commentForm').submit(); inside the if condition which execute if the validation is true
Reason : Since you are using event.preventDefault(), it will prevent the default behaviour of the form and so did not go to next page. So You have to submit the form manually using $(form).submit();
The below code will work on normal page but not on SO Snippet
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('input.submit').click(function(event) {
// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
});
});
// prevent default submit action
event.preventDefault();
// test if form is valid
if($('form.commentForm').validate().form()) {
console.log("validates");
$('.commentForm').submit();
} else {
console.log("does not validate");
}
})
// set handler for addInput button click
$("#addInput").on('click', addInput);
// initialize the validator
$('form.commentForm').validate();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<form class="commentForm" method="get" action="action_page_post.php">
<div>
<p id="inputs">
<input type="text" class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>
I want to send data using GET or POST to another php file on a button's(NOT Submit button) onClick() Event.
Please help me.
Let I give you simple HTML with post method using AJAX
Test.php
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function() {
$("#Submit").click(function() {
var value = jQuery("#txt").val();
var data=jQuery('#myform_new').serializeArray();
$.post('test1.php', { myform: data});
return false;
});
});
</script>
</head>
<body>
<form id="myform_new">
<input type="text" name="abc" value="abc" id="txt"/>
<input type="text" name="abc1" value="abc1" id="txt1"/>
<input type="button" name="Submit" id="Submit" value="Submit" />
</form>
</body>
</html>
Test1.php(ajax calling file)
<?php
echo "<pre>";print_r($_POST);
?>
Let i give you some of the ajax posting method
(1)
<script>
$(function() {
$("#Submit").click(function() {
var value = jQuery("#txt").val();
var data=jQuery('#myform_new').serializeArray();
$.post('test1.php', { myform: data});
return false;
});
});
</script>
(2)
<script type="text/javascript"> $(function() { $("#Submit").click(function()
{
var txt = jQuery("#txt").val();
var txt1 = jQuery("#txt").val();
$.post('test1.php', { txt: txt,txt1:txt1 }); return false; }); });
</script>
(3)
<script type="text/javascript"> $(function() { $("#Submit").click(function() {
var txt = jQuery("#txt").val();
var txt1 = jQuery("#txt").val();
$.post('test1.php', { data: "txt="+txt+"&txt1="+txt1}); return false; }); });
</script>
Hello in there i have explain both ajax and get/post method, Please have look below link for get/post method for submit a form in php.
http://www.tutorialspoint.com/php/php_get_post.htm
This below code is used for submit form using ajax
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="formoid" action="studentFormInsert.php" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name" >
</div>
<div>
<label class="title">Name</label>
<input type="text" id="name2" name="name2" >
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { name: $('#name').val(), name2: $('#name2').val() } );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});
</script>
</body>
</html>
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;
});
<div id = "result"> Fade me in and hide div hideme</div>
<div id="hideme">
<form method="POST">
Yes<input type="radio" name="name" value="yes"/>
No<input type="radio" name="name" value="no" checked=true />
<input type="submit" id="submit" name="submit" value="HIDE NOW!" />
</form>
</div>
<script>
$(document).ready(function () {
$('#result').hide();
$('#submit').click(function(e) {
e.preventDefault();
$('#hideme').hide();
$('#result').fadeIn(5000);
});
});
</script>
This will hide my div where the submit is, whenever click on submit it wont send values to PHP.
How to fix that to make it send the values to PHP so i will get the values from html?
You have this e.preventDefault(); in your jquery click handler function. It means that when you press the submit button, the form wouldn't be submitted. It's simply preventing original action of that selector on click.
Here's how to fix it. Use ajax. There's many jquery functions for that, i will show you how to use $.ajax method.
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "yourphpscriphere.php",
data: "name=" + $('input[name="name"]').val(),
success: function() {
alert('thank you for using my form');
},
error: function() {
alert('an error happened during the request');
}
});
$('#hideme').hide();
$('#result').fadeIn(5000);
});
Remember to change url to your own. Then you can get your radio button value using $_POST['name'] in php.
try this code :
html:
<div id="result"> Fade me in and hide div hideme</div>
<div id="hideme">
<form method="POST" id="eform">
Yes<input type="radio" name="name" value="yes"/>
No<input type="radio" name="name" value="no" checked=true />
<input type="submit" id="submit" name="submit" value="HIDE NOW!" />
</form>
</div>
jQuery :
$(document).ready(function () {
$('#result').hide();
$('#submit').click(function(e) {
$.post("page.php",$("#eform").serialize(),function(data){
$('#hideme').hide();
$('#result').html(data).fadeIn(5000);
})
});
});
I have a loginout.php like:
<?php if($isLoggedIn) { ?>
<form method="POST" action="" name="logoutForm" id="logoutForm" accept-charset='UTF-8'>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<input type="submit" name="logout" value="Logout" />
</form>
<? } else { ?>
<form method="POST" action="" name="loginForm" id="loginForm" accept-charset='UTF-8'>
<input type='hidden' name='submitted' id='submitted' value='1'/>
Email: <input type="text" name="usr" /><br />
Password: <input type="password" name="pw" /><br />
<input type="submit" name="login" value="Login" />
</form>
<? }?>
a div like
<div id="loginLogoutDiv"></div>
and also jquery code:
$(document).ready(function(){
$('#loginLogoutDiv').load('loginout.php');
$('#loginForm, #logoutForm').live('submitted', function() {
$.post('loginout.php', $(this).serialize(), function (
data, textStatus) {
$('#loginLogoutDiv').html(data);
});
return false;
});
});
What is wrong if pressing the Login button, then whole page is refreshed that i don't want?
Thank you
Replace:
$('#loginForm, #logoutForm').live('submitted', function() {
...
With
$('#loginForm, #logoutForm').submit(function(event) {
event.preventDefault();
...
so that you get...
$(function(){
$('#loginLogoutDiv').load('loginout.php');
$('#loginForm, #logoutForm').submit(function(event) {
event.preventDefault();
$.post('loginout.php', $(this).serialize(), function (
data, textStatus) {
$('#loginLogoutDiv').html(data);
});
return false;
});
});
The event you want to attach to is called submit, not submitted.
Also, check your console for errors in your javascript — if your script is terminated due to an error before it can return false in your onsubmit handler, the default behavior will not be prevented.
I would do it this way (mean JS):
$(document).ready(function(){
$('#loginLogoutDiv').load('loginout.php');
$('#loginForm, #logoutForm').submit(function(e) {
e.preventDefault(); // this will prevent the page to really do a submit
$.post('loginout.php', $(this).serialize(), function (
data, textStatus) {
$('#loginLogoutDiv').html(data);
});
});
});
If You need to use live(), this should do it:
$(document).ready(function(){
$('#loginLogoutDiv').load('loginout.php');
$('#loginForm, #logoutForm').live('submit', function(e) {
e.preventDefault(); // this will prevent the page to really do a submit
$.post('loginout.php', $(this).serialize(), function (
data, textStatus) {
$('#loginLogoutDiv').html(data);
});
});
});