Adding a unique FORM name or ID to a function - javascript

is there a way of adding the form name or id to this Function to make it unique? I have a loop process that displays 5 forms and I need this piece of coding to be unique to each.
<script type="text/javascript">
$(function() {
$("input, select, textarea, checkbox, radio").autosave({
url: "/js/autosave/autosave.php",
method: "post",
grouped: false,
success: function(data) {
$("#message").html("Data updated successfully");
},
send: function(){
$("#message").html("Sending data...");
},
dataType: "html"
});
});
</script>
the form
<form action="/js/autosave/autosave.php" method="post">
<fieldset>
<label for="name">Name:<input type="text" name="word" id="word" value="<?php echo $row['word'] ?>"/></label>
<label for="email">Email:<input type="text" name="type" id="type" value="<?php echo $row['type'] ?>" /></label>
<input type="hidden" name="id" value="<?php echo $row['Id'] ?>" />
<input type="submit" value="Save changes" />
</fieldset>
</form>

Based on your updated question...
$(function() {
var formCounter = 0;
$("form:not([id])").each(function(){
$(this).attr("id", "form_" + formCounter);
formCounter++;
});
}

You could reference $(this) within autosave to get the caller and query it for its parent (and add an attribute or some identifying characteristic to each)

$(function(){
$('form').each(function(){
$(this).find('input, select, textarea, checkbox, radio').autosave({
url: "/js/autosave/autosave.php",
method: "post",
grouped: false,
success: function(data) {
$("#message").html("Data updated successfully");
},
send: function(){
$("#message").html("Sending data...");
},
dataType: "html"
});
});
});
The code above adds autosave functionality to each form individually, which should solve your issue.

Related

How do I pass a value to a PHP script using AJAX?

I am trying to learn web design with a search function using MySql. I want make it to 2 steps selection however, I have run into a problem which really confuses me since I don't have a strong background to design. I am trying to be as specific as possible to make the question clear.
test.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>count</title>
<link rel="stylesheet" type="text/css" href="dbstyle.css">
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'>
</script>
</head>
<body>
<form id="serc" method="post" action="">
<input type="radio" value="typeA" name="comments" onclick="expr()">Good
<input type="radio" value="typeB" name="comments" onclick="expr()">Bad
</form>
<form id="form1" name="form1" method="post" style="visibility:hidden">
<p>please select reason:</p>
<input type="checkbox" class="check" name="checkbox[]" value="COL 8">aaa<br />
<input type="checkbox" class="check" name="checkbox[]" value="COL 9">bbb<br />
<input type="checkbox" class="check" name="checkbox[]" value="COL 10" >ccc<br />
<button id="aaa" type="submit" class="butt" name="sub2" style="visibility:hidden">Submit</button>
</form>
<?php
$comm = $_POST["gender"];
$reas = $_POST["checkbox"];
if($comm){$respond = $_POST['comments'];
echo $respond;
}
<script src="limit.js"></script>
</body>
</html>
limit.js
//click to get Value
$("input[type='Radio']").click(function(){
var radioValue = $("input[name='comments']:checked").val();
$("#serc").css("display", "none");
$("#form1").css("visibility", "visible");
});
//limit multiple selection up to 4
$("input:checkbox").click(function() {
var bol = $("input:checkbox:checked").length;
if(bol == 4){
$("input:checkbox").not(":checked").attr("disabled",bol);
$("#aaa").css("visibility", "visible");
}
else {
$("#aaa").css("visibility", "hidden");
$("input:checkbox").removeAttr("disabled");
}
});
// return value
function expr()
{
var radioValue = $("input[name='comments']:checked").val();
var dataTosend= radioValue;
$.ajax({
url: 'index.php',
type: 'POST',
data: dataTosend,
async: true,
success: function (data) {
alert(data)
},
});
}
The function will be:
First stage select from radio item, onclick use jQuery to hide the selection items and also get radioValue from the jQuery by Ajax way to send to php use.
Second stage select 4 items from checkbox, and submit to run search field.
I expect load the radioValue back to php as a variable but seems it didn't get the value.
Any help would be appreciated.
You must send data using key value pair like this:
function expr(){
var radioValue = $("input:radio[name='comments']").val();
var dataTosend= {'radioValue': radioValue};
$.ajax({
url: 'index.php',
type: 'POST',
data: dataTosend,
async: true,
success: function (data) {
alert(data)
},
});
}

Ajax Post Submit Function Submits Twice

I've tried many of the other solutions to this problem on SO, and elsewhere, but I can't seem to prevent my form from submitting twice. Here is the code that I'm currently having this issue with:
jQuery Code
$(function() {
var additemtoform = $('#additemform');
var handleData = function(responseData) {
if ($(responseData).find('#repitems').length) {
var replacement = $('<div />').html(responseData).find('#repitems').html();
$('#test').html(replacement);
} else {
additemtoform.submit();
}
};
$("#additemform .addbtn").on("click", function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'WebCatPageServer.exe',
dataType: 'html',
cache: false,
data: additemtoform.serialize(),
beforeSend: function() {},
success: function(data) {
handleData(data);
},
error: function() {
alert('error');
}
});
return false;
});
});
If I remove the submit in the callback, then the form doesn't submit at all. So, what am I missing?
Thanks!
Update
Note that this code is update from the original per Habbe's suggestion below. The same issue with the double submit persists, however.
HTML Code (Generated)
<form name="AddItem" id="additemform" method="post" action="WebCatPageServer.exe">
<input name="Action" type="hidden" value="Add_Item" />
<table>
<tbody>
<tr>
<td>BRW2394746301</td>
<td>239-47463-01</td>
<td>Gas Valve Complete, Icon Natural Gas</td>
<td> $207.32</td>
<td>Available</td>
<td>
<input name="Q1" tabindex="1" class="qtyfield" type="text" size="1" value="0" onblur="clickrecall(this,'0')" onfocus="Q1.select()" />
</td>
<td>
<input name="P1" type="hidden" value="BRW2394746301" />
<input name="M1" type="hidden" value="239-47463-01" />
<input name="D1" type="hidden" value="Gas Valve Complete, Icon Natural Gas" />
<button type="button" class="button lightgray smallrounded addbtn" value="Add">Add</button>
</td>
</tr>
<tr>
<td>BRW2394746501</td>
<td>239-47465-01</td>
<td>Gas Valve Complete , Icon Propane</td>
<td> $272.58</td>
<td>Available</td>
<td>
<input name="Q2" tabindex="2" class="qtyfield" type="text" size="1" value="0" onblur="clickrecall(this,'0')" onfocus="Q2.select()"/>
</td>
<td>
<input name="P2" type="hidden" value="BRW2394746501" />
<input name="M2" type="hidden" value="239-47465-01" />
<input name="D2" type="hidden" value="Gas Valve Complete , Icon Propane" />
<button type="button" class="button lightgray smallrounded addbtn" value="Add">Add</button>
</td>
</tr>
<tr>
<td>BRW2334784505</td>
<td>233-47845-05</td>
<td>Pilot Assembly, Icon Natural Gas</td>
<td> $32.58</td>
<td>Available</td>
<td>
<input name="Q3" tabindex="3" class="qtyfield" type="text" size="1" value="0" onblur="clickrecall(this,'0')" onfocus="Q3.select()" />
</td>
<td>
<input name="P3" type="hidden" value="BRW2334784505" />
<input name="M3" type="hidden" value="233-47845-05" />
<input name="D3" type="hidden" value="Pilot Assembly, Icon Natural Gas" />
<button type="button" class="button lightgray smallrounded addbtn" value="Add">Add</button>
</td>
</tr>
</tbody>
</table>
</form>
Solution - Final Code
As it turns out, I was overthinking this. The form was submitting via ajax on the initial submit. The form was submitted again in the callback. Since an item was added to the cart on the initial submit, I simply loaded the cart page in the callback.
$(function() {
var additemtoform = $('#additemform');
// Reset Qty to 0 on Page Load
$('#additemform .inputqty').val('0');
//Ajax CallBack
var handleData = function(responseData) {
if ($(responseData).find('#repitems').length) {
var replacement = $('<div />').html(responseData).find('#repitems').html();
$(replacement).appendTo('body').modal();
} else {
location.href = "WebCatPageServer.exe?Cart";
}
};
$("#additemform .addbtn").on("click", function(e) {
e.preventDefault();
// If qty is 0, set value to 1
if($(this).closest('tr').find('input[type=text]').val() === '0'){
$(this).closest('tr').find('input[type=text]').val('1');
}
else {
}
// Post Form
$.ajax({
type: 'POST',
url: 'WebCatPageServer.exe',
dataType: 'html',
cache: false,
data: additemtoform.serialize(),
beforeSend: function() {},
success: function(data) {
handleData(data);
},
error: function() {
alert('error');
}
});
return false;
});
NB! ensure that the binding occurs just once and that you don't have multiple submit elements in your form.
You could try to include the event.stopPropagation call. I dont see how this could effect anything, but perhaps worth a shot.
$(function() {
var additemtoform = $('#additemform');
var handleData = function(responseData) {
if ($(responseData).find('#repitems').length) {
var replacement = $('<div />').html(responseData).find('#repitems').html();
$('#test').html(replacement);
} else {
additemtoform.submit();
}
};
$("#additemform .addbtn").on("click", function(e) {
e.preventDefault();
e.stopPropagation();
$.ajax({
type: 'POST',
url: 'WebCatPageServer.exe',
dataType: 'html',
cache: false,
data: additemtoform.serialize(),
beforeSend: function() {},
success: function(data) {
handleData(data);
},
error: function() {
alert('error');
}
});
return false;
});
});
On the third line, the function(e) is open telling function handleData(responseData) to run oy omitting the closing }. Then in the ajax you tell function handleData(responseData) to run again.
Try This:
$(function() {
var additemtoform = $('#additemform');
$("#additemform .addbtn").off().on("click", function(e) {
///your code
});
My guess would be, because you are calling submit form action twice. Once in the form tag, and secondly in jquery. Try removing one and see what happens.
During first time ajax call, the form is not submitted. Just passes the call and receives response length 0 or null. So the else part demands form submission again. So try to submit the form before first call and make sure form submit target is self().
Good Luck!

Post multiple forms with Jquery

I have multiple forms in my page. I'd like to be able to post those forms from single Jquery function.
It only work for the first form. I think this is because all forms have the same Id, I would need to use click function() instead of submit() and use something like $(this).closest("form") ...
<form class="form-horizontal" role="form" id="fpostcomm">
<input name="cmt" type="text" class="form-control input-sm" id="inputcommt" autocomplete="off">
</form>
<script>
$(document).ready(function(){
$("#fpostcomm").submit(function(){
$.ajax({type:"POST", data: $(this).serialize(), url:"ajax/ajxaaddcmt.php",
success: function(data){
$("#inputcommt").val('');
},
error: function(){
alert ("Error.");
}
});
return false;
});
});
</script>
You cannot reuse IDs. They must be unique in a document. Fix that and you can then grab them however you need.
If you want a single shared name on all of them, use a class instead.
<form class="form-horizontal fpostcomm" role="form">
<input name="cmt" type="text" class="form-control input-sm inputcommt" autocomplete="off">
</form>
<script>
$(document).ready(function(){
$(".fpostcomm").submit(function(){
$form = $(this);
$.ajax({type:"POST", data: $(this).serialize(), url:"ajax/ajxaaddcmt.php",
success: function(data){
$form.find(".inputcommt").val('');
},
error: function(){
alert ("Error.");
}
});
return false;
});
});
</script>

Page gets reloaded in ajax

I'm trying to build a subscribe form.
The problem is that the page gets redirected, and the data doesn't get entered into db,
page gets redirected to
http://localhost/xampp/MY/SUB_FOLDERS/includes/parse.php?subscriber=sid%40patel&subscribe=subscribe
HTML CODE
<div id="subsc">
<form class="navbar-form navbar-right" action="includes/parse.php" mathod="post">
<div class="form-group">
<input type="email" placeholder="Email" class="form-control" name="subs" id="subs" required="required">
</div>
<input type="submit" class="btn btn-success" name="subscribe" id="subscribe" value="subscribe">
</form>
</div>
Ajax code:
<script type="text/javascript">
$(document).ready(function(){
$("#subscribe").click(function(){
username=$("#subs").val();
$.ajax({
type: "POST",
url: "includes/parse.php",
//data:dataString,
success: function(html){
if(html=='true')
{
$("#subsc").fadeOut("normal");
$("#subsc").html("Thank you for subscriping!");
}
else
{
$("#subsc").html("Error in subscribing");
}
},
});
return false;
});
});
</script>
PHP script for inserting data to database:
<?php include("connect.php");
if (#$_POST['subs']) {
$subscriber = mysql_real_escape_string(strip_tags($_POST['subs']));
$sendmessage = mysql_query("INSERT INTO subscriber VALUES('','$subscriber',now())");
echo 'true';
}
?>
PS: Name of rows in subscriber id, email, datetime
I guess there is one simpler approach here using your existing code itself...Instead of these lines:
$("#subscribe").click(function(){
username=$("#subs").val();
Use these lines:
$("#subscribe").click(function(e){
e.preventDefault();
. e.stopPropagation();
username=$("#subs").val();
This should stop the form post back even for submit button.
Hope this helps.
Add an id on your form:
<form id="myform" class="navbar-form navbar-right" action="includes/parse.php" method="post">
Change your Javascript to:
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit(function(event){
username=$("#subs").val();
$.ajax({
type: "POST",
url: "includes/parse.php",
//data:dataString,
success: function(html){
if(html=='true')
{
$("#subsc").fadeOut("normal");
$("#subsc").html("Thank you for subscriping!");
}
else
{
$("#subsc").html("Error in subscribing");
}
},
});
event.preventDefault();
});
});
</script>
This will prevent the default action of the form to submit the data and the apparent redirect. Also by handling the form's submit event you also handle the situation where the form may be submitted by other means.
First bind your subscribe button to a click event and Remove attribute action="includes/parse.php"
<input type="button" class="btn btn-success" name="subscribe" id="subscribe" value="subscribe">
jQuery('#subscribe').click(function(){
jQuery.ajax({
url:'YOUR URL',
type:'POST',
data:'subsribe=true&email='+jQuery('#subs').val(),
success:function(data){
if(data == 'true')
{
//enter code here
window.location.reload(true);
}else{
//enter code here
alert(data);
}
}
});
});
SERVER SIDE
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
if(isset($_POST)){
$subscriber = mysql_real_escape_string(strip_tags($_POST['subscriber']));
$query = "INSERT INTO subscribers('email','timestamp') VALUES('$subscriber',NOW())";
$sendmessage = mysql_query($query) or die(mysql_error());
echo 'true';
}
}
The simplest thing to do would be changing the type of your #subscribe element to button instead of submit.
<div id="subsc">
<form class="navbar-form navbar-right" id="SubsForm">
<div class="form-group">
<input type="email" placeholder="Email" class="form-control" name="subscriber" id="subs" required="required">
</div>
<input type="button" class="btn btn-success" id="subscribe" value="subscribe">
</form>
</div>
And JavaScript -
<script type="text/javascript">
$(document).ready(function(){
$("#subscribe").click(function(){
$.ajax({
type: "POST",
url: "includes/parse.php",
data:$('#SubsForm').serialize(),
success: function(html){
if (html=='true') {
$("#subsc").fadeOut("normal");
$("#subsc").html("Thank you for subscriping!");
} else {
$("#subsc").html("Error in subscribing");
}
},
});
});
});
</script>
More about $().serialize can be found here - http://api.jquery.com/serialize/
The .serialize() method creates a text string in standard URL-encoded
notation. It can act on a jQuery object that has selected individual
form controls....

Repopulating div with new form/content using jQuery/AJAX

Are there any jQuery/AJAX functions that when a form (or anything for that matter) is displayed, upon pressing a button the div containing the original form is replaced by a new form? Essentially, a multi-part form without having to reload the page.
Can I use something like this?
$('form#myForm').submit(function(event) {
event.preventDefault();
$.ajax({
type: '',
url: '',
data: $(this).serialize(),
success: function(response) {
$('#divName').html(response);
//somehow repopulate div with a second form?
}
})
return false;
});
I've used this before for adding items to a list, but I've never used it to totally repopulate it with different content. How can I direct it to the second form?
edit - I got it to work, but only when I write '#form2' for the replacement. I alerted the response and I get {"formToShow":"show2"}. I tried doing response.formToShow but it's undefined.
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
</head>
<div id="divName">
<form method="POST" action = "#" id="form1">
<input type="textbox" name="textbox1" value="1"/>
<input type="submit" name="submit1"/>
</form>
<form method="POST" action = "#" id="form2" style="display: none">
<input type="textbox" name="textbox2" value="2"/>
<input type="submit" name="submit2"/>
</form>
</div>
<script>
$('form#form1').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'JSON',
url: 'receiving.php',
data: $(this).serialize(),
success: function(response) {
$('#form1').hide(); //hides
//$('#form2').show(); //this will show
$(response.formToShow).show(); //this does not display form 2
}
})
return false;
});
</script>
Here is receiving.php. When I view this page {"formToShow":"show2"} is displayed
<?php
echo json_encode(array("formToShow" => "#form2"));
?>
Check the JQuery Load Function
This is personal preference, but I'd never send HTML through the response and display it like that, what I'd do is:
Send a JSON array back from the server, such as { formToShow: "#form1" }
Then you can simply do this:
success: function(response) {
$('form').hide();
$(response.formToShow).show();
}
Obviously, using this method, you'd also have to have the second form in your markup like this:
<form method="POST" action = "#" id="form2" style="display: none">
<input type="textbox" name="textbox2"/>
<input type="submit" name="submit2"/>
</form>
You'd also have to change (to pickup the array):
$.ajax({
type: 'JSON'
try this
$('form#myForm').submit(function(event) {
event.preventDefault();
$.ajax({
type: '',
url: '',
data: $(this).serialize(),
success: function(response) {
$('#divName').html(response);
$('#form1').hide();
$('#form2').show();
}
})
return false;
});
<form method="POST" action = "#" id="form1">
<input type="textbox" name="textbox1"/>
<input type="submit" name="submit1"/>
</form>
<form method="POST" action = "#" id="form2" style="dispay:none;">
<input type="textbox" name="textbox2"/>
<input type="submit" name="submit2"/>
</form>

Categories