Laravel multiple checkboxes to insert into database using ajax - javascript

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){
} }); }); });

Related

How to use same php function for different button clicks

Here is a simple PHP form with a button..
<form method="POST">
<div class="mb-3">
<button type='button' id ="btnnew1" class="btn btn-info" >submit</button>
<p></p>
</div>
</form>
Here is the Jquery functions which executes a PHP file.
$(document).ready(function(){
$("#btnnew1").click(function(e){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
else{
$.ajax({
url: 'test.php',
success: function(data) {
$("p").text(data);
}
});
}
});
});
And the test.php is as follows,
<?php
echo 'Button1 clicked'
?>
My question is how to modify my test.php if I have multiple buttons.
As an example,
<form method="POST">
<div class="mb-3">
<button type='button' id ="btnnew1" class="btn btn-info" >submit</button>
<p></p>
</div>
<div class="mb-3">
<button type='button' id ="btnnew2" class="btn btn-info" >submit</button>
<p></p>
</div>
<div class="mb-3">
<button type='button' id ="btnnew3" class="btn btn-info" >submit</button>
<p></p>
</div>
</form>
Result should be,
If btnnew1 clicks--->echo("Button1 clicked);
If btnnew2 clicks--->echo("Button2 clicked);
If btnnew3 clicks--->echo("Button3 clicked);
Update:
What If I need to run three different php functions(no any pattern)?
Ex:
If btnnew1 clicks--->
sleep(5)
echo("Button1 clicked);
If btnnew2 clicks--->
sleep(15)
echo("Button2 clicked by user);
If btnnew3 clicks--->
sleep(35)
echo("Button3 clicked by user);
In here I am changing little bit your default settings. This will help you as I can understand. You can try as below,
1)Change your button into input type..I have added some inline CSS as well. If you don't like you may neglect it...
<input type="button" style="background-color: #3CBC8D;padding:3px;" class="button" name="fcn1" value="Update My Status"/>
<input type="button" class="button" style="background-color: #3CBC8D;padding:3px;" name="fcn2" value="Update My Status" />
Then go to jquery and use as below, success function change as you wish. Here I have used an alert box...
$(document).ready(function(){
$('.button').click(function(){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
else{
var clickBtnValue = $(this).attr('name');
var fetchdata= 'testme.php',
data = {'action': clickBtnValue};
$.post(fetchdata, data, function (response) {
// Response div goes here.
alert("Updated successfully -"+response);
});
}
});
});
Finally change your testme.php as follows,
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'fcn1':
fcn1();
break;
case 'fcn2':
fcn2();
break;
}
}
function fcn1() {
echo 'Button1 clicked';
exit;
}
function fcn2() {
sleep(5);
echo 'Button2 clicked';
exit;
}
Set the name to each button:
Button 1
Send data using ajax:
Get button text using e.target.text and send using POST method.
$.ajax({
type: 'POST',
url: 'test.php',
data: { buttonTitle: e.target.name},
success: function(data) {
$("p").text(data);
}
});
php:
Inside php use $_GET to get the data which we send from the frontend.
if(isset($_POST['buttonTitle'])) {
$buttonTitle = $_POST['buttonTitle'];
echo $buttonTitle . " clicked";
}

Submit HTML forms that contain dynamic IDs

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

same elements are ready find which on is chosen for deletion

a foreach loop is produce many element with same class in a div(the div is curectly present with id "#show_case" )
foreach ($messages as $key => $value) { ?>
<div class="message">
<p class="username"><?php echo $value['username']; ?></p> <span>say:</span>
<p class="text"> <?php echo $value['message']; ?></p>
<p class="message_id"><?php echo $value['message_id']?></p>
</div> <?php }
}
i built a right click context menu that have a delete button that have id #delete and do this code when is clicked
$('#delete').click(function(e) {
e.preventDefault();
var id = $('.message_id').text();
$.ajax({
url: 'ajax/chat.php',
type: 'POST',
data: {
method: "delete",
id: id,
},
success: function (data) {
alert('successfully deleted');
}
});
});
delete button is here (it is a right click contextmenu will be avilibe after right click on the element)
<div class="menu">
<ul>
<li>
<button id="delete">delete</button>
</li>
</ul>
</div>
i tryed
var id = $('.message_id').text();
for get id but it return all elements ids by class message_id ... i what just the id of element that clicked by delete button
where is your #delete button?
If the delete button contains .message_id, you can use
var id = $(this).find('.message_id').text();
I have created a DEMO to get the id of the element on right click and save this id into an input or hidden element so that the can be retrieved in different functions. Here is the code from the DEMO:
HTML:
<h3>Right click on below messages</h3>
<div class="message" style="border:1px dotted">
<p class="username">Username 1</p> <span>say:</span>
<p class="text"> text 1</p>
<p class="message_id">1</p>
</div>
<br>
<div class="message" style="border:1px dotted">
<p class="username">Username 2</p> <span>say:</span>
<p class="text"> text 2</p>
<p class="message_id">2</p>
</div>
<br>
Selected message id:
<input type="text" id="selected_message_id" />
JS:
$(function () {
$(".message").contextmenu(function() {
alert("clicked message id = "+$(this).find('.message_id').html());
$('#selected_message_id').val($(this).find('.message_id').html());
return false;
});
});
Now in your below function, you can get the message_id like this:
$('#delete').click(function(e) {
e.preventDefault();
var id = $('#selected_message_id').val();//get the message_id from the hidden/text input
$.ajax({
url: 'ajax/chat.php',
type: 'POST',
data: {
method: "delete",
id: id,
},
success: function (data) {
alert('successfully deleted');
}
});
});

jQuery form clone, how to stop values from being copied

I am adding additional form on button click.
In my form, i have one drop down. When user select value from drop down, i am populating other fields value based drop down selection. You can see in my code i am sending ajax call to retrieve the values before setting them in input field.
code
<script>
$(document).ready(function(){
var index = 0;
$("#testButton").click(function() {
$("#jBuyer").clone().appendTo("#jointBuyer");
index++;
});
});
</script>
When clone done, the form fields along with data copied to next form.
I don't want it to happen because it is a problem? How can i stop it?
With my little knowledge i can understand the problem is with duplicate Name or Id but don't how i can generate them dynamically and then can set their values.
If you interested to know my full code, please see below.
full code
<div id="jointBuyer" class="JointBuyerDive" style="display:none">
<div id="jBuyer">
<div id="inner"class="col-lg-6">
<form id="buyerForm" role="form" method="POST" enctype="multipart/form-data">
<label>Buyer</label>
<div class="form-group">
<label>Unit No.</label>
<select class="form-control" name="junitId" id="junitId" onmousedown="this.value='';" onchange="getUnit(this.value);">
<option>Please Select Unit No</option>
<?php
$sql_query= "select * from tble_units";
$run_query =mysqli_query($con, $sql_query);
while($row = mysqli_fetch_array($run_query )){
$unit_no =$row ['unit_no'];
$unit_ID =$row ['unit_ID'];
?>
<option value="<?php echo $unit_ID;?>"><?php echo $unit_no;?></option>
<?php }?>
</select>
</div>
<div class="form-group">
<label>Type</label>
<input type="text" name="unitTypeE" id="unitTypeE" class="form-control" readonly>
</div>
<div class="form-group">
<label>No of Car Parking Purchase</label>
<input type="text" name="noOfCarParkingE" id="noOfCarParkingE" class="form-control" readonly>
</div>
</div>
</div>
<div>
Ajax call
function getUnit(value) {
var dataString = 'id=' + value;
$.ajax({
type: "POST",
url: "getUnitData.php",
data: dataString,
cache: false,
success: function(result) {
var obj = JSON.parse(result);
$('input[name=unitTypeE]').val(obj[0]);
$('input[name=noOfCarParkingE]').val(obj[1]);
$('input[name=floorE]').val(obj[2]);
$('input[name=unitAreaE]').val(obj[3]);
$('input[name=commentsE]').val(obj[4]);
}
});
}
You can reset form after clone it.
Like this code:
var clonedForm = $("#buyerForm").clone();
$("#jBuyer").append(clonedForm);
clonedForm[0].reset();
and then you should set unique id to cloned form:
clonedForm.attr("id","uniqueId");
append after edit:
and then in ajax call you should use this code to change only one dropdown:
first change onchange="getUnit(this)" and then:
function getUnit(obj) {
var currentForm = obj.parents("form");
var dataString = 'id=' + obj.value;
$.ajax({
type: "POST",
url: "getUnitData.php",
data: dataString,
cache: false,
success: function(result) {
var obj = JSON.parse(result);
currentForm.find('input[name=unitTypeE]').val(obj[0]);
currentForm.find('input[name=noOfCarParkingE]').val(obj[1]);
currentForm.find('input[name=floorE]').val(obj[2]);
currentForm.find('input[name=unitAreaE]').val(obj[3]);
currentForm.find('input[name=commentsE]').val(obj[4]);
}
});
}

codeigniter : form validation jquery

i have a form name nama kategori and then when someone input the nama kategorithat already exist, i want the button become unclickable like when the button being clicked it's not gonna do anything, the problem is i manage to get the error message when input the existing nama kategori, but when i click the button it's still send the data and inputting the data, for more info look the images below
Success Display Error Message
Then i clicked button "Tambah"
it's still adding the data into the tables, i want to prevent that, i want when the button clicked it's not gonna do anything below are my code
JQUERY
$(document).ready(function(){
var check1=0;
$("#kategori").bind("keyup change", function(){
var nama = $(this).val();
$.ajax({
url:'cekData/kategori/nama_kategori/'+nama,
data:{send:true},
success:function(data){
if(data==1){
$("#report1").text("");
check1=1;
}else{
$("#report1").text("*choose another kategori");
check1=0;
}
}
});
});
});
VIEW
<div class="row">
<div class="col s12 m8 l6 offset-m2 offset-l3" align="center">
<form action="<?php echo site_url('kategori/insertKategori') ?>" method="post">
<div class="input-field">
<input id="kategori" name="kategori" type="text" maxlength="40" class="validate" required>
<label for="kategori">nama kategori</label> <span class="error" id="report1"></span>
</div>
<br/>
<button type="submit" class="waves-effect waves-light btn blue darken-1">Tambah</button>
</form>
<br/>
</div>
</div>
CONTROLLER
public function cekData($table, $field, $data){
$match = $this->MKategori->read($table, array($field=>$data), null, null);
if($match->num_rows() > 0){
$report = 2;
}else{
$report = 1;
}
echo $report;
}
You need to make following changes to your jquery code:
$(document).ready(function(){
var check1=0;
$("#kategori").bind("keyup change", function(){
var nama = $(this).val();
$.ajax({
url:'cekData/kategori/nama_kategori/'+nama,
data:{send:true},
success:function(data){
if(data==1){
$("#report1").text("");
check1=1;
$('button[type="submit"]').prop('disabled','');
}else{
$("#report1").text("*choose another kategori");
check1=0;
$('button[type="submit"]').prop('disabled',true);
}
}
});
});
});

Categories