I have forms being created in a foreach loop with php.
Each form has a lpformnum that increases
<form lpformnum="1"><button class="update" /></form>
<form lpformnum="2"><button class="update" /></form>
<form lpformnum="3"><button class="update" /></form>
etc.
I am using jquery/ajax to prevent the default action of the forms so I can submit the forms via ajax.
<script>
$(document).ready(function(){
$('.alert').on('click', 'button[class=update]', function(e) {
e.preventDefault();
e.stopPropagation();
var checkValues = $("#update").val();
var checkCred = $("#ucredits").val();
var checkPost = $("textarea").text();
var checkType = $("i").text();
$.ajax({
type: "POST",
url: "update_social_cred.php",
data: { id: checkValues, credits: checkCred, text: checkPost, type: checkType },
success:function(result) {
alert (checkCred);
}
});
});
});
</script>
The problem is, every button submits the first form drawn on the page. How would I do this so each button is set to each form keeping in mind there are an unknown number of forms being drawn?
I suppose you should clarify what data you want to submit with find() method.
$('.alert').on('click', 'button[class=update]', function(e) {
e.preventDefault();
e.stopPropagation();
// find parent form of a button
var form = $(this).closest( "form" );
// I suppose these are unique fields.
var checkValues = $("#update").val();
var checkCred = $("#ucredits").val();
var checkPost = $("textarea").text();
// if they are not you should use classes instead:
// something like:
// var checkCred = form.find(".ucredits").val();
// find values in a `form` with `find` method
var checkType = form.find("i").text();
// pass your data to ajax.
Related
I am adding a text area on click of a particular div. It has <form> with textarea. I want to send the jquery variable to my php page when this submit button is pressed. How can this be achievable. I am confused alot with this . Being new to jquery dizzes me for now. Here is my code,
`
<script type="text/javascript">
$(document).ready(function(){
$('.click_notes').on('click',function(){
var tid = $(this).data('question-id');
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'><textarea cols ='50' class='span10' name='notes' rows='6'></textarea><br><input class='btn btn-primary' name= 'submit_notes' type='submit' value='Add Notes'><input type='hidden' name='submitValue' value='"+tid+"' /></form><br></div>");
});
});
</script>`
Your code works fine in the fiddle I created here -> https://jsfiddle.net/xe2Lhkpc/
use the name of the inputs as key of $_POST array to get their values.
if(isset($_POST['submitValue'])) { $qid = $_POST['submitValue']; }
if(isset($_POST['notes'])) { $notes = $_POST['notes']; }
You should send your data after form submitted, something like this
:
$(".comment_form form").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
you can assign event after insert your form.
// handling with the promise
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'></form><br></div>").promise().done(function () {
// your ajax call
});;
I store multiple data in a table for enquiry basis.. which is successfully stored in my table. but now i also want to store those same data in Booking basis.
So i used onClick function for storing enquiry data. and now i want to store booking data in table from form submit button.
here is my form submit button code:
<button type="submit" class="booking-btn" onclick="btn_booking_hour();" id="btn_booking_hour">Book Now</button>
Here is my form action:
<?php echo form_open('booking/'.$product->id); ?>
And here my function:
function btn_booking_hour()
{
var date = $('#datehour').val();
var renter_id = $("#ownerid").val();
var guests_quantity = $('#no_of_guests').val();
var property_id = $('#property_id').val();
var selectedIds="";
var selectedObject = document.getElementsByClassName('hour_slots_available slot_activated');
for(var i=0;i<selectedObject.length;i++)
selectedIds+=selectedObject[i].id+",";
if(selectedIds == ""){
alert("Please select Hour-Slot(s) before Booking");
}
else{
$.ajax({
type: 'POST',
dataType:'json',
url:baseURL+'site/rentals/ajaxhourshow',
data:{'selectedHours':selectedIds,'property_id':property_id,'date':date,'guests_quantity':guests_quantity,'renter_id':renter_id},
success: function(responce){
var myJSON = JSON.stringify(responce);
var packet = $.parseJSON(myJSON);
var prd_id=packet.property_id;
var hour_slots=packet.hour_slots;
window.location.href = baseURL+'booking/'+prd_id;
}
});
}
}
Please suggest me how can i submit a form with data within their onClick function. Thanks..
Not sure if you are using a form, if you are using it you can can use onsubmit handler and return the action. In that case you wont need onclick handler in the button
<form onsubmit = "return btn_booking_hour()">
// Rest of code
</form>
You can also do like this
$('#form').on('submit',function(e){
e.preventDefault();
// rest of the code
})
you can use this code
function btn_booking_hour(){
// your other code
document.getElementById('formid').submit();
// formid = form id
}
or also use jquery
function btn_booking_hour(){
// your other code
$('#formid').submit();
// formid = form id
}
i got your point so you can also use it
$(function() {
//hang on event of form with id=myform
$("#myform").submit(function(e) {
//prevent Default functionality
e.preventDefault();
rest of your code
});
});
I have 10 form in a page & there data is submitted through ajax, Now i don't want to create ajax script for each form. So here is what i tried
var form_id = $(this).closest("form").attr('id');
$(document).on("submit", "#"+form_id, function(e){
e.preventDefault();
var postData = $("#"form_id).serialize()
var send = true;
var ptel = 1;
$("#"+form_id).find("input").each(function () {
if ($(this).val() === '') { send = false; ptel = 0; }
});
if(ptel == 0) { bootbox.alert('Please Fill All fields'); }
if(send){
$('form_id').trigger("reset");
$.ajax({
type: "POST",
url: "/ajax/X-Profile",
data: postData,
cache: false,
success: function(msg)
{
bootbox.alert('Your Profile has been updated.');
}
});
}
return false;
});
var form_id results in undefined because when page loads no attribute was defined to it
Above codes are just to make you understand,
So my question is how can i make 10 forms submit through single ajax function
You can create a function such as SendForm() and attach it to the forms onsubmit attribute
<form id="yourid" onsubmit="SendForm(this);return false;">
inside the SendForm() function place your script
for instance:
function SendForm(form) {
var postData = form.serialize();
// .......etc
}
To know which form was submitted in PHP, you can place a hidden input inside the form or have a second parameter on SendForm which gets sent through, such as SendForm(node,formtype)
if the form isn't submitting or page reloads, remove the onsubmit attribute and add this to your JS instead
$(document).on("submit","form", function(e){
e.preventDefault();
SendForm($(this));
return false;
});
Have javascript function like below
<script type="text/javascript">
function submitForm(formID) {
data = $('#'+formID).serialize();
//your ajax code
}
</script>
Now use input button with onclick like below, and pass form Id as a parameter
<input type="button" value="Submit" onclick="submitForm({formID})">
This will work without refreshing the page. And on success you can trigger reset() function to form that particular form values.
within the form element I send data with a href. Using the JavaScript (as defined below), it works perfectly.
I want to send the forms now with Ajax, unfortunately it does not work. Do you have a solution for me. jQuery is included on the page.
Thank You!
function sendData(sFm, sID, sFn, sCl) {
var form = document.getElementById(sFm);
form.sid.value = sID;
form.fnc.value = sFn;
form.cl.value = sCl;
form.submit();
}
Send Data
My new Code:
function sendData(sFm, sID, sFn, sCl) {
var form = $("#"+sFm);
form.submit( function() {
var sid = $('input[name="sid"]').val(sID);
var fnc = $('input[name="fnc"]').val(sFn);
var cl = $('input[name="cl"]').val(sCl);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: {sid: sid, fnc: fnc, cl: cl}
}).done(function( e ) {
});
});
form.submit();
}
$("form").submit(function() { // for all forms, if you want specially one then use id or class selector
var url = $(this).attr('action'); // the script where you handle the form input.
var method = $(this).attr('method');
$.ajax({
type: method,
url: url,
data: $(this).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // handle response here
}
});
return false; // avoid to execute the actual submit of the form.
});
:) , Thanks
Just because we don't want to submit all form by ajax so we can set a data-attribute to form tag to indicate, will it should be submit by ajax or normally ,, so ,,
$("form").submit(function() { ...
if($(this).attr('data-ajax') != "true") return true; // default hanlder
...
so If form is written like this :-
<form action="/dosomething" method="post" data-ajax="true"> </form> // will be sumit by ajax
<form action="/dosomething" method="post" data-ajax="false"> </form>
// will be sumit by default method
This is very consistent, but firebug is showing that my saveForm function is not being defined form my 'button.save' event handler, but it works for my 'button.deleteForm' event handler:
function saveForm(form)
{
var $form = form;
var url = $form.attr('action');
$.ajax({
type: "POST",
enctype: 'mutipart/form-data',
url: url,
data: $form.serialize(), // serializes the form's elements.
success: function(data)
{
// data is the server response.
// change this function to tell the
// user whether their submission
// is correct or what fields have
// bad data.
var response = JSON.parse(data);
return true;
}
});
return false; // avoid to execute the actual submit of the form.
}
// Do not use event handlers like .click(). This is the
// only viable solution for handling events on dynamically
// generated HTML elements. This handles the saving of data
// to the server.
$(document).on('click', 'button.save', function(e){
var $form = $(this).closest('form');
saveForm(form);
});
// This event handler is responsible for deleting data.
// For Joey's job: Please make sure that this calls save
// after the user hits delete. This will save the data in
// the database.
$(document).on('click', 'button.deleteForm', function(e){
// Get the form to update before deleting our embedded form
var $form = $(this).closest('form');
var str = $(this).attr('id');
// Get the table id in review to delete
var deleteForm = str + '_review';
$('table#' + deleteForm).remove();
// Get the collection form id to delete
var idArray = str.split('_');
idArray.pop();
divId = '#' + idArray.join('_');
$(divId).remove();
saveForm($form);
});
you missed $ in saveform
$(document).on('click', 'button.save', function(e){
var $form = $(this).closest('form');
saveForm($form);
//------^----here
});