I have a feedback form in a pop-up div that otherwise works fine but processes SQL twice when the form results in error at first instance.
This is the html form:
<div id="stylized" class="myform">
<form id="form" method="post" name="form">
<p>Report:
<select id="fbtype" name="fbtype">
<option>Bug</option>
<option>Suggestion</option>
<option>Discontentment</option>
<option>Appreciation</option>
</select>
</p>
<p>Brief description:
<textarea name="comments" id="comments" cols="45" rows="10"></textarea>
</p>
<span class="error" style="display:none">Please describe your feedback.</span>
<span class="success" style="display:none">We would like to thank you for your valuable input.</span>
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()"/>
</form>
</div>
The feedback_form_submit() function is:
function feedback_form_submit() {
$(function() {
$(".submit").click(function() {
var fbtype = $("#fbtype").val();
var comments = $("#comments").val();
var dataString = 'fbtype='+ fbtype + '&comments=' + comments;
if(fbtype=='' || comments=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "processfeedback.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
}
And the processfeedback.php has:
include "./include/session_check.php";
include_once "./include/connect_to_mysql.php";
if (isset($_POST['fbtype'])){
$userid =$_SESSION['id'];
$fbtype=$_POST['fbtype'];
$comments=$_POST['comments'];
$sql = mysql_query("INSERT INTO feedback (userid, type, comments)
VALUES('$userid','$fbtype','$comments')") or die (mysql_error());
}
Could anyone figure out why does the form submits twice? And any suggestion to control this behaviour?
If this is actually the code you're using, you seem to have wrapped your onclick function around the $.click event-adding function:
function feedback_form_submit() {
$(function() {
// This adds a click handler each time you run feedback_form_submit():
$(".submit").click(function() {
// ... //
return false;
});
});
}
When I tried this on jsFiddle.net, I clicked Submit the first time and nothing happened, then the second time it posted twice, the third click posted three times, etc.
You should just keep it simple: take out the onclick attribute:
<input type="button" value="Submit" class="submit" />
and remove the feedback_form_submit() wrapper:
$(function() {
$(".submit").click(function() {
// ... //
return false;
});
});
This way the $.click handler function will be applied just once, when the page loads, and will only run once when Submit is clicked.
EDIT:
If your form is loaded via AJAX in a popup DIV, you have two options:
Keep your onclick but remove the $.click wrapper instead:
function feedback_form_submit() {
// ... //
}
and
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()" />
Note that you only need to return false if you're using <input type="submit" ... >; when using <input type="button" ... >, the browser does not watch the return value of onclick to determine whether to post the form or not. (The return value may affect event propagation of the click, however ...).
Alternatively, you can use jQuery's $.live function:
$(function() {
$('.submit').live('click',function() {
// ... //
});
});
and
<input type="button" value="Submit" class="submit" />
This has the effect of watching for new DOM elements as they are added dynamically; in your case, new class="submit" elements.
Your feedback_form_submit function doesn't return false and on submit click you're also posting to the server. There is no need to have onClick in:
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()"/>
Change that to:
<input type="button" value="Submit" class="submit"/>
And change your code to:
// Update: Since you're loading via AJAX, bind it in the success function of the
// AJAX request.
// Let's make a function that handles what should happen when the popup div is rendered
function renderPopupDiv() {
// Bind a handler to submit's click event
$(".submit").click(function(event) {
var fbtype = $("#fbtype").val();
var comments = $("#comments").val();
var dataString = 'fbtype='+ fbtype + '&comments=' + comments;
if(fbtype=='' || comments=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "processfeedback.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
// This is the success function for the AJAX request that loads the popup div
success: function() {
...
// Run our "onRender" function
renderPopupDiv();
}
Related
I'm pretty sure it has to do with my core.js file with the ajax hashing url. But I'm trying to submit a form, but it's not submitting like I want it to. This is the core.js file:
// call init
$(init);
function init() {
ajax_page_handler();
page_load($(window.location).attr("hash")); // goto first page if #! is available
}
function page_load($href) {
if($href != undefined && $href.substring(0, 2) == '#/') {
// replace body the #content with loaded html
$('#content').load($href.substring(2), function () {
$('#content').hide().fadeIn('slow');
});
}
}
function ajax_page_handler() {
$(window).bind('hashchange', function () {
$href = $(window.location).attr("hash");
page_load($href);
});
// this allow you to reload by clicking the same link
$('a[href^="#/"]').live('click', function() {
$curhref = $(window.location).attr("hash");
$href = $(this).attr('href');
if($curhref == $href) {
page_load($href);
}
});
}
The live viewing is over at www.krissales.com. The form is here: http://www.krissales.com/#/media/5.Testing-1
Hit the link "Post Comment", then you'll type info in, then hit comment, but it just refreshes, but doesn't submit it.
The steps I've taken to solve it was in the comment file, in the form action field, I inserted the tag name="#content" simply because that's the name of my div that I'm submitting to.
The original stuff is on http://blog.krissales.com/article/7.Testing-3-man ( where you can actually post a comment, and it'll work)
But apparently it's not working. Do you guys have a clue as to what it is that I'm doing wrong? thanks for your help in advance!
<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "simple"
});
</script>
<form action="#/media/article.php" name="#content" method="POST">
Name:
<br />
<input type="text" name="name" class="userpass"/>
<br /><br />
Comment:
<br />
<textarea id="elm1" name="comment" rows="7" cols="30" style="width: 500px;">
</textarea>
<br />
<input type="submit" name="submit" value="Comment" class="button" />
<input type="reset" name="submit" value="Reset" class="button" />
</form>
I noticed that you are not setting the ajax type on the file 'comment.php'.
you need...
$.ajax({
type: 'POST',
url: 'comment_ajax.php',
data: { form_name: name, form_comment: comment },
success: function(data) {
$('#new_comment').prepend(data);
// close modal box
// do other shit
// kthnxbai
}
});
If type is not specified, it defaults to a GET request which will not post data. :)
Your current core.js handles changes in the URL hash, and it reroutes any links with a hash to load that relative path into #content. What's missing is code to redirect form submits to do the same thing (add this to ajax_page_handler):
$('form').live('submit', function(e) {
var $action = $(this).attr('action');
if($action.substring(0, 2) == '#/') {
// replace the #content with result of the form post
$.ajax({
url: $action.substring(2),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(data) {
$('#content').html(data);
$('#content').hide().fadeIn('slow');
}
});
// stop the real form submit from happening
e.preventDefault();
}
});
You should change the action attribute of your form like this :
<form action="script-handling-comment-data.php#/media/article.php" name="#content" method="POST">
For the moment, you're sending the comment data to http://www.krissales.com/ and i think the main page doesn't handle the comment posting.
You seem to be handling links properly, but form submission isn't a link, you probably want to handle submission using $(form).submit(function(){ ... })
In your case, if you gave your form the id form1
$('#form1').submit(function(){
var keyValues = $(this).serializeArray();
var map = {};
for(i in keyValues)
{
var value = keyValues.value;
var name = keyValues.name;
map[name] = value;
}
$.post($(this).attr('action'),map,function(){
alert("Submitted values: " + $(this).serialize());
});
return false;
})
See serializeArray, $.post and .submit for more information
i am building one form with fancy box, form work fine but i could not get value from text box.
my java script is
$(function () {
$("#button").click(function () {
var yourName = $("input#yourName").val();
alert(yourName);
if (yourName == "") {
$('input#yourName').css({
backgroundColor: "#F90"
});
$("input#yourName").focus();
return false;
}
$.ajax({
type: "POST",
url: "bin/form1.php",
data: $("#login_form").serialize(),
context: document.body,
success: function (res) {
var success = '<?php echo sprintf(_m('Success name % s '), "" ); ?>';
success = success.replace(/^\s*|\s*$/g, "");
var RegularExpression = new RegExp(success);
if (RegularExpression.test(res)) {
alert('Message Sent');
$.fancybox.close();
} else {
alert('Error While processing');
}
},
});
return false;
});
});
now my html is
<div style="display:none; height:450px">
<form id="login_form" action="">
<p id="login_error">
Please, enter data
</p>
<input type="hidden" name="action" value="send_friend_post" />
<label for="yourName" style="margin-right:110px;">
<?php _e( 'Your name', 'newcorp') ; ?>
</label>
<input id="yourName" type="text" name="yourName" value="" class="text_new " />
<br/>
<input type="submit" value="Submit" id="button" class="text_new" style="background:#930; color:#FFF; width:250px; margin-left:170px" />
</form>
</div>
i am opening this fancy box popup from
<a id="tip5" title="" href="#login_form"><?php echo "Login" ; ?></a>
every thing work fine but i can't get value of yourName even alert is showing blank.
Thanks
instead of this
var yourName = $("input#yourName").val();
try
var yourName = $("input[name='yourName']:text").val();
this will make ur function read the value of text box .
Firstly, with your form, it should be better to use
$(document).on('submit', 'form', function () { ... })
instead of
$(document).on('click', '#myButton', function () { ... })
Secondly, you should encapsulate your code into $(document).ready(function () { .. });
Here is a working example ;) http://jsfiddle.net/aANmv/1/
Check that the ID of Your input is not changed by fancybox at the time of opening the popup.
Instead of directly catching up the click event try to live the event if using jQuery 1.7 > or on when using jQuery 1.7 <.
live:
$("#button").live('click', function() { ... });
on:
$("#button").on('click', function() { ... });
Also try to load the javascript after the DOM is loaded:
$(document).ready(function(){
$("#button").live('click', function() { ... });
...
});
Instead of that
$(function() {
try
$(document).ready() {
this way you are sure that code is executed only after the document has loaded completely. Oh, and you could use #yourName instead of input#yourName, if i'm not wrong it should be faster.
I have two forms on my website, and I use jQuery to submit them, to my PHP script.
These are the forms:
<form method="post" class="settings-form" id="passwordSettings">
<label id="npasswordbox" class="infoLabel">New Password: </label>
<input type="password" name="npassword" size="50" value="" >
<div class="move"></div>
<label id="cnpasswordbox" class="infoLabel">Confirm: </label>
<input type="password" name="cnpassword" size="50" value="" >
<button class="btn" name="passwordSetings" style="margin-left:185px" type="submit">Save </button>
</form><!-- end form -->
And the next:
<form method="post" class="settings-form" id="normalSettings">
<label id="npasswordbox" class="infoLabel">New Username: </label>
<input type="text" name="username" size="50" value="" >
<div class="move"></div>
<button class="btn" name="normalSettings" style="margin-left:185px" type="submit">Save </button>
</form><!-- end form -->
Here is the jQuery I have written for these two forms:
$(function() {
$('form#passwordSettings').submit(function(){
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#passwordSettings').serialize(),
function (data) {
proccessPWData(data);
}
);
return false;
});
});
function proccessPWData (data) {
$('#status').hide().html('');
if(data=='success'){
$('form#normalSettings').fadeOut();
$('html, body').animate({scrollTop:0});
$("#status").removeClass();
$('#status').addClass('alert alert-success').html('You have successfully changed your personal settings.<br />').slideDown().delay(5000);
redirect("/account");
}
else {
$('html, body').animate({scrollTop:0});
$('#status').removeClass().addClass('alert alert-error').html(data).fadeIn();
setTimeout(function(){
$('#status').slideUp("slow");
},7000);
}
}
$(function() {
$('form#normalSettings').submit(function(){
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#normalSettings').serialize(),
function (data) {
proccessData(data);
}
);
return false;
});
});
function proccessData (data) {
$('#status').hide().html('');
if(data=='success'){
$('form#normalSettings').fadeOut();
$('html, body').animate({scrollTop:0});
$("#status").removeClass();
$('#status').addClass('alert alert-success').html('You have successfully changed your personal settings.<br />').slideDown().delay(5000);
redirect("/account");
}
else {
$('html, body').animate({scrollTop:0});
$('#status').removeClass().addClass('alert alert-error').html(data).fadeIn();
setTimeout(function(){
$('#status').slideUp("slow");
},7000);
}
}
And then the PHP code:
if(isset($_POST['normalSettings']))
{
$username = inputFilter($_POST['username']);
if(!$username){
$error ="no username";
}
if(!$error){
echo "success!";
}
}
if(isset($_POST['passwordSettings']))
{
$password = inputFilter($_POST['npassword']);
if(!$username){
$error ="no pw";
}
if(!$error){
echo "success!";
}
}
My problem is, that whenever I submit one of these forms, I see the form with my $error in the #status div.
How can I have multiply forms on one page, but submit the correct ones?
$(function() {
$('form#passwordSettings').submit(function(e){
e.preventDefault(); // prevents the default action (in this case, submitting the form)
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#passwordSettings').serialize(),
function (data) {
proccessPWData(data);
}
);
return false;
});
});
or you could just give an hidden input-field with it
<input type="hidden" name="_normalSettings">
and check in your PHP
if (isset($_POST['_normalSettings']) // ...
This is basically just answer to your question: "How can I have multiple forms on one page, but submit the correct ones?"
I have many dynamically generated forms on a single page and I send them to process file one by one. This is one form simplified:
<form name="form" id="form">
<!--form fields
hidden field could be used to trigger wanted process in the process file
-->
<input type="hidden" name="secret_process_id" value="1" />
<a class="button_ajax">Send form</a>
</form>
<div id="process_msg<?php echo $id; ?>"></div>
And here's the form submit function:
$(document).ready(function() {
$('.submit_ajax').click(function() { //serializes the parent form
//alert($(this).serialize());
dataString = $(this).parent().serialize();
//if you want to echo some message right below the processed form
var id = /id=\d+/.exec(dataString);
var id = /\d+/.exec(id);
$.ajax({
type: 'post',
url: '_process.php?ajax=1', //some or none parameters
data: dataString,
dataType: 'html',
success: function(data) {
$('#process_msg' + id).fadeIn(400);
$('#process_msg' + id).html(data);
}
}); //end of $.ajax
return false;
});
});
All you need is a process file/function and you are ready to go. Works just fine with one or dozens of forms. There you can do something like this:
if ($_POST['secret_process_id']==1){
//do something
}
if ($_POST['secret_process_id']==2){
//do something else
}
//etc.
I want to submit a POST form that contains a textarea field and an input field(s) (type="checkbox" with an arbitrary/variable number of checkboxes) on my website via jQuery's .ajax(). PHP receives the textarea data and the ajax response is correctly displayed to the user. However, it seems that PHP is not receiving the checkbox data (was it checked, or not). How can I get this to work? Here is the code I have:
The HTML:
<form method="post" action="myurl.php" id=myForm>
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
...(maybe some more checkboxes - dynamically generated as necessary)
<input id="submit" type="submit" name="submit" value="Submit" onclick="submitForm()" />
</form>
The jQuery:
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: { myField:$("textarea[name=myField]").val(),
myCheckboxes:myCheckboxes },
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
Now, the PHP
$myField = htmlspecialchars( $_POST['myField'] ) );
if( isset( $_POST['myCheckboxes'] ) )
{
for ( $i=0; $i < count( $_POST['myCheckboxes'] ); $i++ )
{
// do some stuff, save to database, etc.
}
}
// create the response
$response = 'an HTML response';
$response = stripslashes($response);
echo($response);
Everything works great: when the form is submitted a new record is stored in my database, the response is ajaxed back to webpage, but the checkbox data is not sent. I want to know which, if any, of the checkboxes have been checked. I've read about .serialize(), JSON, etc, but none this has worked. Do I have to serialize/JSON in jQuery and PHP? How? Is one method better than another when sending form data with checkboxes? I've been stuck on this for 2 days. Any help would be greatly appreciated. Thanks ahead of time!
Yes it's pretty work with jquery.serialize()
HTML
<form id="myform" class="myform" method="post" name="myform">
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitForm()" />
</form>
<div id="myResponse"></div>
JQuery
function submitForm() {
var form = document.myform;
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url:'myurl.php',
data: dataString,
success: function(data){
$('#myResponse').html(data);
}
});
return false;
}
NOW THE PHP, i export the POST data
echo var_export($_POST);
You can see the all the checkbox value are sent.I hope it may help you
var myCheckboxes = new Array();
$("input:checked").each(function() {
data['myCheckboxes[]'].push($(this).val());
});
You are pushing checkboxes to wrong array data['myCheckboxes[]'] instead of myCheckboxes.push
Check this out.
<script type="text/javascript">
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: 'myField='+$("textarea[name=myField]").val()+'&myCheckboxes='+myCheckboxes,
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
}
</script>
And on myurl.php you can use print_r($_POST['myCheckboxes']);
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like.
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
You may also try this,
var arr = $('input[name="myCheckboxes[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
The code you have at the moment seems to be all right. Check what the checkboxes array contains using this. Add this code on the top of your php script and see whether the checkboxes are being passed to your script.
echo '<pre>'.print_r($_POST['myCheckboxes'], true).'</pre>';
exit;
I have some question. I have the html form with one hidden input element. And I have an array in my javascript code. I want to catch pressing submit button event (by using jquery) and push the array data in the hidden input.
The question is - what happens first: form date will flow to .php script or javascript's array will be pushed into hidden input and afterwords .php script will be called? And why it is so?
TIA!
upd (code sample):
...
// process $_POST['domains']
...
<form action="registration?id=reg" method="post" enctype="multipart/form-data" id="reg_form">
...
<input type="hidden" id="domains" name="domains[]" value=""/>
...
<input type="submit" name="go" value="Register"/>
</form>
<script type="text/javascript">
var domainlist = [];
Array.prototype.indexOf = function (name) {
var ind = -1;
for (var i = 0; i < this.length; i++) {
if (this[i].name == name) {
ind = i;
break;
}
}
return ind;
}
$(document).ready(function() {
...
});
function checkDomain() {
...
req = $.ajax({
type: 'post',
cache: false,
url: 'ajax.php',
data: ...,
success: function(data) {
$('#domain_list_wrap').delegate('input:checkbox', 'click', function () {
var dmnName = $(this).attr('name');
domainlist.push({name: dmnName, cost: domainsArr[dmnName.split('.')[1]]});
...
});
$('#domain_cart').delegate('input:checkbox', 'click', function () {
domainlist.splice(domainlist.indexOf($(this).attr('name')), 1);
...
});
}
});
...
}
</script>
The JavaScript submit event is fired when the form is submitted, but before the request is made to the server (as JavaScript runs on the client side this makes perfect sense). Therefore, the way you have imagined it working should be fine, and you can bind to the form submit event using jQuery as follows:
$("#yourForm").submit(function() {
//Submit event handler will run on form submit
});
The submit event handler can also be used to cancel form submission (for example, if some validation fails) by returning false. It wouldn't really work if the data was sent to the server first!
Put this in your body
<form id="frm" method="post" action="/">
<input type="hidden" id="txtHidden" />
<input type="submit" id="btnSubmit" value="submit" />
</form>
And this in your head:
<script type="text/javascript">
var arr = [ "hello", "there", "world" ];
$(document).ready( function() {
$("#btnSubmit").click( function(event) {
var str = arr.join(",");
$("#txtHidden").val(str);
// make sure the value is in the field
alert($("#txtHidden").val());
});
});
</script>
When you click on btnSubmit, the array will be joined with commas, you'll see the alert, then the form will be submitted.