I have 2 HTML forms that contain dynamic ID attributes. What I want is to store data with AJAX call from each HTML form separately. Currently AJAX call works only for one HTML form when I use static ID name "surveyImage".
I don't know how I can with jQuery to call method submit() individually for each form. Is there any way to resolve this issue?
Form with id="surveyImage13"
<form method="POST" action="http://localhost/1/467/survey" accept-charset="UTF-8" id="surveyImage13" role="form" class="form-material m-t-40" novalidate="novalidate">
<div class="row">
<div class="col-lg-12">
<input name="questionnaire_pivot_id" id="questionnaire_pivot_id13" class="questionnaire_pivot_id" type="hidden" value="13">
<input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="1">
<input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">
...
<div class="row" style="margin-bottom: 5%;">
<div class="col-xl-2 col-lg-3 col-md-3">
<button id="add" class="btn btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>
</div>
</div>
</form>
Form with ID="surveyImage18"
<form method="POST" action="http://localhost/2/467/survey" accept-charset="UTF-8" id="surveyImage18" role="form" class="form-material m-t-40" novalidate="novalidate">
<div class="row">
<div class="col-lg-12">
<input name="questionnaire_pivot_id" id="questionnaire_pivot_id18" class="questionnaire_pivot_id" type="hidden" value="18">
<input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="2">
<input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">
...
</div>
</div>
<div class="row" style="margin-bottom: 5%;">
<div class="col-xl-2 col-lg-3 col-md-3">
<button id="add" class="btn btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>
</div>
</div>
</form>
AJAX call
<script type="text/javascript">
$("#surveyImage13").validate({
rules: {
'responses[]': {
required:true
}
},
// change name of error class that is assigned to input fields
errorClass: 'error_validate',
errorPlacement: function (label, element) {
// default
if (element.is(':radio')) {
label.insertAfter(element.parent('.form-check-inline'));
}
else {
label.insertAfter(element);
}
}
});
</script>
<script type="text/javascript">
$("#surveyImage13").submit(function(e) {
e.preventDefault();
var route=$('#surveyImage13').attr('action');
var pivot_id = $("#questionnaire_pivot_id").val();
// Get values of checked checkboxes
var responses = $('.form-check-inline input').filter(':checked').map(function() {
return this.value;
}).get();
var isFormValid = $("#surveyImage13").valid();
if(isFormValid){
$.ajax({
type: "POST",
url: route,
data: {'responses': responses, 'pivot_id': pivot_id},
success: function(response){
$("#surveyImageForm").css("display", "none");
$("#surveyImageAjax").css("display", "block");
$('#SurveyTableAjaxColumn1').append(response[1]);
$('#SurveyTableAjaxColumn2').append(response[0]);
},
error: function(){
console.log('Error');
}
})
}
});
</script>
Why not give your forms a common class
$('.myClass').validate({ ...
})
$('.myClass').submit(...
Based on your provided configuration, it should not be possible for jQuery to perform the submit action. The jQuery selector is #surveyImage, which does not match any id attributes in the provided HTML.
<form id="surveyImage13">...</form>
<form id="surveyImage18">...</form>
$("#surveyImage").submit...
I think you may be able to resolve the issue by using a different query selector string.
$('#surveyImage13 #surveyImage18').submit...
or...
$('form[id^="surveyImage"]').submit...
1.Instead of submit event use button click event
2.Get form id and store it
3.use this variable where you need id
$(".btn").click(function(e) {
e.preventDefault();
var formId = '#'+ $(this).parents('form').attr('id');
var route=$(formId).attr('action');
var pivot_id = $("#questionnaire_pivot_id").val();
// Get values of checked checkboxes
var responses = $('.form-check-inline input').filter(':checked').map(function() {
return this.value;
}).get();
var isFormValid = $(formId).valid();
if(isFormValid){
$.ajax({
type: "POST",
url: route,
data: {'responses': responses, 'pivot_id': pivot_id},
success: function(response){
$("#surveyImageForm").css("display", "none");
$("#surveyImageAjax").css("display", "block");
$('#SurveyTableAjaxColumn1').append(response[1]);
$('#SurveyTableAjaxColumn2').append(response[0]);
},
error: function(){
console.log('Error');
}
})
}
});
Thanks for all answers but I found solution. Im working in LARAVEL therefore I used foreach loop based on which i was able to assign dynamic ID on HTML forms.
#foreach($questionnaire_by_images as $t)
<form id="surveyImage{{$t->id}}">...</form>
<form id="surveyImage{{$t->id}}">...</form>
#endforeach
script
#foreach($questionnaire_by_images as $t)
<script type="text/javascript">
$( document ).ready(function() {
$("#surveyImage{{$t->id}}").validate({
rules: {
'responses[]': {
required:true
}
},
// change name of error class that is assigned to input fields
errorClass: 'error_validate',
errorPlacement: function (label, element) {
// default
if (element.is(':radio')) {
label.insertAfter(element.parent('.form-check-inline'));
}
else {
label.insertAfter(element);
}
}
});
$("#surveyImage{{$t->id}}").submit(function(e) {
e.preventDefault();
var route=$('#surveyImage{{$t->id}}').attr('action');
var survey_image_pivot = $("#survey_image_pivot{{$t->id}}").val();
// Get values of checked checkboxes
var responses = $('.form-check-inline .radio{{$t->id}}').filter(':checked').map(function() {
return this.value;
}).get();
var isFormValid = $("#surveyImage{{$t->id}}").valid();
if(isFormValid){
$.ajax({
type: "POST",
url: route,
data: {'responses': responses, 'survey_image_pivot': survey_image_pivot},
success: function(response){
$("#surveyImageForm{{$t->id}}").css("display", "none");
$("#surveyImageAjax{{$t->id}}").css("display", "block");
$('#SurveyTableAjaxColumn1{{$t->id}}').append(response[1]);
$('#SurveyTableAjaxColumn2{{$t->id}}').append(response[0]);
},
error: function(){
console.log('Error');
}
})
}
});
});
</script>
</script>
#endforeach
Related
I have several forms on a page and i want to utilize the same ajax function. It works great for one form since I am grabbing the id with getElementById and then passing it to my ajax function. What I am trying to do is pass down the id of the form onSubmit dynamically.
form
<form id="postData" name="business" method="post" action="{{ path('location_graph', {'location_id': location.getId }) }}"
class="m-form m-form--fit m-form--label-align-right">
<div class="form-group m-form__group row">
<label class="col-2 col-form-label required" for="description">Business
Description</label>
<div class="col-7">
<input type="text" class="form-control m-input" id="description"
name="extra[description]">
</div>
</div>
...
<div class="form-group m-form__group row">
<button type="submit" class="btn m-btn--square btn-outline-primary">
Submit
</button>
</div>
</form>
script
document.getElementById('postData').addEventListener('submit', postData);
function postData(event) {
event.preventDefault();
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
data: $(this).serialize(),
success: function (data) {
console.log(data);
$('#success__para').html("You data was saved");
}
});
}
You can attach a submit event handler to each of the forms and pass event and this.id (the id of the form element) as arguments.
Javascript:
function postData(event, id) {
event.preventDefault();
var elem = $('#'+id);
$.ajax({
type: elem.attr("method"),
url: elem.attr("action"),
data: elem.serialize(),
success: function (data) {
console.log(data);
$('#success__para').html("You data was saved");
}
});
}
HTML:
<form id="someid" onsubmit="postData(event, this.id)">
I need someone to help me please to insert multiple products to cart, adding single one is working fine but I have one product which inserting with no issue and related products which have checkboxes where I need to add it but dont know how
enter image description here
ajax for adding product:
<script>
$(function(){
$('.add_to_cart').on("click", function () {
var id = ($("#item_id").val());
$.ajax({
url: 'cart/' + id+'/edit',
type: "get",
success: function (data) {
$('#myModal').modal('hide');
$('#cart_product').html(data);
}
});
});
});
</script>
add in controller
public function edit(Request $request,$id)
{
$quantity=$request->quantity;
$product=Product::find($id);
Cart::add($id,$product->product_title,$quantity,$product->product_price);
$products = Cart::content();
foreach($products as $Product){
echo '<div class="OrderItem_root styles_base styles_spacing-base">
<div class="OrderItem_quantity styles_just-right styles_base styles_spacing-base">'.$Product->qty.'</div>
<div class="OrderItem_container">
<div class="OrderItem_category"></div>
<div class="OrderItem_itemHeader">
<div id="cartprice" class="OrderItem_total">$'.$Product->price*$Product->qty.'</div>
<input id="mycartprice" type="text" name="mycartprice" value="'.$Product->price.'" hidden="">
</div>
<div>
</div>
<div>
<button class="remove_item OrderItem_action Button_root" data-id="'.$Product->rowId.'" data-price="'.$Product->price*$Product->qty.'" data-qty="'.$Product->qty.'" type="submit">Remove</button>
</div>
</div>
</div>';
}
}
related items
foreach($products as $Product){
echo '<div class="SuggestedItem_container">
<label>
<input id="ppleadd" type="checkbox" onchange = "AutoCalculateMandateOnChange(this)">
<span id="related_item" class="SuggestedItem_name">'.$ProductDetails->product_title.'</span><span class="SuggestedItem_price styles_small styles_base styles_spacing-base">+$'.$ProductDetails->product_price.'</span></div></div>
</div>
</label>';
}
to solve this issue use this
<input id="ppleadd" type="checkbox" class="get_value" data-id="'.$ProductDetails->product_id.'" >
$(document).ready(function(){
$('.testbtn').on("click", function (){
var insert=[];
$('.get_value').each(function(){
if($(this).is(":checked"))
{
insert.push($(this).attr('data-id'));
}
});
insert=insert.toString();
$.ajax({
url:"add-to-cart",
method:"get",
data:{insert:insert},
success:function(data){
} }); }); });
This question already has answers here:
Getting data from post array in CodeIgniter
(5 answers)
Closed 6 years ago.
I have a problem to send multiple data to controller.
$target is result from post('warna'). How do I get all data?
<form action="http://localhost/starsc/trueaccon2194/opsional" id="form" method="post" accept-charset="utf-8">
<div class="row">
<div class="col-md-12 input group kolom">
<div id="warna1" style="padding-left:0;padding-right:0;" class="col-md-12 col-sm-12 col-xs-12">
<input type="text" id="warna1" name="warna[]" class="joss form-control">
<br>
</div>
<div id="warna2" style="padding-left:0;padding-right:0;" class="col-md-12 col-sm-12 col-xs-12">
<input type="text" id="warna2" name="warna[]" class="joss form-control">
<br>
</div>
<div id="warna3" style="padding-left:0;padding-right:0;" class="col-md-12 col-sm-12 col-xs-12">
<input type="text" id="warna3" name="warna[]" class="joss form-control">
<br>
</div>
<button type="button" class="simpan_warna btn btn-primary">Simpan</button>
</form>
$('.simpan_warna').click(function() {
var UrlToPass = $("#form").serialize();
$.ajax({ // Send the credential values to another checker.php using Ajax in POST menthod
type: "POST",
data: UrlToPass,
url: baseURL + "trueaccon2194/opsional/proses_tambah_opsi_warna",
beforeSend: function() {
$('.simpan_warna').prop('disabled', true);
$('.simpan_warna').html('sedang menyimpan...'); //Loading button text
},
success: function(success) { // Get the result and asign to each cases
$('.simpan_warna').prop('disabled', false);
$('.simpan_warna').html('Simpan'); //reset button text to original text
alert('Data Berhasil disimpan!');
$('#modal_form').modal('hide');
location.reload();
},
error: function() {
$('.simpan_warna').prop('disabled', false);
$('.simpan_warna').html('Simpan'); //reset button text to original text
alert('Data gagal disimpan!');
}
});
return false;
});
my controller is :
function proses_tambah_opsi_warna(){
$target = $this->input->post('warna[]');
if($this->input->post()){
$data = $this->input->post();
$data['nama_depan'] = $this->data['nama_depan'];
$this->opsional_adm->add_warna($data);
log_helper("warna", "Menambah Warna ".$target."");
}else{
log_helper("warna", "Gagal Menambah warna baru");
}
}
Try to get the 'warna' post value, not the 'warna[]' :
$target = $this->input->post('warna');
With this, $target will be an array and you'll able to access values with a loop like this :
foreach ($target as $id => $value) {
echo $value;
}
Here is my form's markup
<form name="contactForm" id="contactForm" role="form">
<div style="width: 190px">
<div class="form-group">
<input type="text" placeholder="fullname" name="fullname" id="formFullname" class="form-control">
</div>
<div class="form-group">
<input type="email" placeholder="email" name="email" id="fromEmail" class="form-control">
</div>
<div class="form-group">
<input type="text" placeholder="company" name="company" id="fromCompany" class="form-control">
</div>
</div>
<div class="clear"></div>
<div class="form-group">
<textarea placeholder="message" name="message" id="formMessage" rows="3" class="form-control"></textarea>
</div>
<button class="btn btn-success" type="submit" name="submit" id="formSubmit">send</button>
</form>
Using jquery 1.10.2
And here is JS
var form = $('#contactForm');
form.submit(function () {
console.log("form ", $(this).serialize());
$.ajax({
type: "POST",
url: url + "ajax/sendmail",
data: $(this).serialize(),
success: function (response) {
console.log(response);
}
});
return false;
});
I know that function fires, tested with alert. But console.log doesnt return anything, and during ajax call I don't see anything in POST (Watching with firebug's XHR).
BTW: role="form" is because i'm using Twitter Bootstrap framework
What am I doing wrong?
UPDATE
data: $(form).serialize() didn't help also
If you try this :
form.submit(function () {
console.log("form ", $(this).serialize());
return false;
});
it works just fine. So I think the problem
form.on('submit',function () {
event.preventDefault();
console.log("form ", $(this).serialize());
$.ajax({
type: "POST",
url: url + "ajax/sendmail",
data: $("form").serialize(),
success: function (response) {
console.log(response);
}
});
return false;
});
Because $(this) in your code doesn't refer to the form but instead refers to jQuery on which the ajax method is called
Try the following code, but first modify your form HTML so that is has an "action" attribute. The nice thing about this code is that it can be used on any form which has a submit button and an action attribute. (i.e. it is not coupled to any specific IDs)
$(function() {
$('input[type="submit"]').click(function(event) {
event.preventDefault();
var form = $(this).closest('form');
var url = form.attr('action');
var data = form.serialize();
$.post(url, data)
.done(function() {
alert('Yay! your form was submitted');
})
.fail(function() {
alert('Uh oh, something went wrong. Please try again');
});
});
Cheers.
I want to submit a form using ajax in the background. I tried:
<div class="form-horizontal" id="form">
<label for="name" class="control-label">Username</label>
<div class="controls">
<span id="name_input"><input type="text" name="name" id="medium" class='input-medium input-square'></span>
<span class="help-inline" id = "ajax_load"></span>
</div>
<div class="form-actions">
<button class="btn btn-red5" onclick="resolve()">Login</button>
<input type="reset" class='btn btn-danger' value="Reset">
</div>
</div>
And the Javascript:
<script type="text/javascript">
var resolve = function () {
jAlert('test', 'test');
$('#ajax_load').html('<img src="templates/img/ajax-loader.gif" alt="">');
$.ajax( {
url : 'plugin.php?plugin=test',
type : 'post',
data: $("#form").serialize(),
success : function( resp ) {
if(resp.ajax_success == false) {
} else {
jAlert('test', 'test');
}
}
});
};
</script>
I get an alert, but there is no form submit. I checked that with Live http headers.
Why does it not submit the form?
If it doesn't submit the form, because, the #form is not a form.
Change:
<div class="form-horizontal" id="form">
To:
<form class="form-horizontal" id="form">
You need to replace the resp.ajax_success with resp. Let us also know the response of the plugin.php?plugin=test URL.
If you don't want the <form> to get submitted on clicking on the Submit button, add a return false; at the end of the resolve function this way:
var resolve = function () {
jAlert('test', 'test');
$('#ajax_load').html('<img src="templates/img/ajax-loader.gif" alt="">');
$.ajax( {
url: 'plugin.php?plugin=test',
type: 'post',
data: $("#form").serialize(),
success: function( resp ) {
if(resp.ajax_success == false) {
} else {
jAlert('test', 'test');
}
}
});
return false;
};
its because you haven't used the form you are serializing the data from div
<div class="form-horizontal" id="form">
not form the form
should be
<form class="form-horizontal" id="form">