Delete Button in a loop giving same ID in Laravel App - javascript

Good day. There is a list of items with two different buttons in my laravel app. One is for updating while the other deletes. I'm using a form (with POST methods) for the two buttons. So, basically, I have two forms on the page. The "update" button works quite well. But the delete button keep on giving me the same ID when I "dd" the request. I am using javascript to submit the "Delete" form because I want to use sweet alert for the user to confirm delete. The code is shown below. Please what may be wrong with it. Also, I'll be glad if I can get a better way of doing it.
This are my forms
<form action="{{route('update.cart')}}" method="POST">
{{csrf_field()}}
<input type="hidden" name="id" value="{{$product->id}}">
<td class="product-quantity"><input type="number" name="quantity" value="{{$product->quantity}}"></td>
<td class="product-subtotal">₦{{$product->price * $product->quantity}}</td>
<td class="product-remove">
<input type="submit" class="login-btn" value="Update" style="width:90px!important;text-transform: none!important;">
</form>
<form style="display: inline!important;" action="{{route('remove.cart')}}" method="POST" name="myForm" id="myForm">
{{csrf_field()}}
<?php
$id = $product->id;
?>
<input type="hidden" name="cart_id" value="<?php echo $id?>">
<button href="#" id="remove" type="button" onclick="removeItem({{$product->id}})"><i class="fa fa-trash" aria-hidden="true"></i></button>
</form>
</td>
My Javascript Code To Submit The Form
function removeItem(clicked){
document.getElementById('myForm').submit();
}
Controller
This gives me the same id in my controller irrespective of the button clicked
$item = $request->cart_id;
dd($item);
}

You are using the id myForm for every delete form. A page is only allowed to have an id once, because you have it multiple times, it always submits the first one.
Either remove the javascript and let the form submit directly or add unique id's for every form.

You can use AJAX to send request to your controller and add sweetalert inside success function provided by ajax.
HTML FORM
<form style="display: inline!important;" action="{{route('remove.cart')}}" method="POST" name="myForm" id="myForm">
{{csrf_field()}}
<?php
$id = $product->id;
?>
<input type="hidden" name="cart_id" value="<?php echo $id?>">
<button href="#" id="remove" type="button" onclick="removeItem({{$product->id}})"><i class="fa fa-trash" aria-hidden="true"></i></button>
</form>
JQUERY
var id = $('cart_id').value();
$('#myForm').onSubmit(function(e){
e.preventDefault();
$.ajax({
method:'POST',
url:"your link",
data:{
id
},
success: function(result)
{
sweetalert();
}
error: function(err) {}
})
})
}

Thanks all.
Changed my form and javascript to reflect the adjustments.
Form
{{csrf_field()}}
<?php
$id = $product->id;
?>
<input type="hidden" name="cart_id" value="<?php echo $id?>">
<button href="#" type="button" onclick="removeItem({{$product->id}})"><i class="fa fa-trash" aria-hidden="true"></i></button>
</form>
And my JS
function removeItem(clicked){
document.getElementById('myForm'+clicked).submit();
}
</script>

Related

Form is auto submitting but the data is not getting passed/received

I have a problem in automating a form with hidden inputs in PHP. Basically I'm doing an input for a barcode scanner where the user will input the barcode and it will auto-submit, just like in a cash registry.
The conflict which I think is the cause of the problem is because of a conditional form. Here is a snippet:
<form method="post" id="form1">
<div class="products">
<input type="text" name="code" class="form-control" autofocus required onchange="submit()" />
</div>
</form>
<?php
$query = 'SELECT * FROM product WHERE PRODUCT_CODE='.$code.' GROUP BY PRODUCT_CODE ORDER by PRODUCT_CODE ASC';
$result = mysqli_query($db, $query);
if ($result):
if(mysqli_num_rows($result)>0):
while($product = mysqli_fetch_assoc($result)):
?>
<form id="form2" method="post" action="pos.php?action=add&id=<?php echo $product['PRODUCT_CODE']; ?>" >
<input type="hidden" name="quantity" class="form-control" value="1" />
<input type="hidden" name="name" value="<?php echo $product['NAME']; ?>" />
<input type="hidden" name="price" value="<?php echo $product['PRICE']; ?>" />
<input type="submit" name="addpos" style="margin-top:5px;width: 462px" class="btn btn-info" value="Add"/>
</form>
<?php
endwhile;
endif;
endif;
?>
<script>
function submit() {
document.getElementById("form1").submit();
}
document.getElementById("form2").submit();
</script>
The data from form1 has no trouble auto-submitting, then the form2 will auto-submit but nothing happens. I need help on how can I make form2 auto-submit correctly too. I have tried different event handling for form2 but nothing happens. I only know a little bit of javascript so that's just how my script turned out.
Thank you, Programming kings!
Because the second form is inside the while loop, if there are multiple results there will be multiple forms with the same id = "form2".
You need an increment variable $incrm = 2 inside the loop,
form id='form<?php echo $incrm;?>',
with $incrm++ before ending it. I also recommend to add ann onchange event to the last input 'price' ; onchange = submit(this).
function submit(inp) {
inp.parentElement.submit();
}

trying to loop HTML buttons using PHP and added an EventListener in JS using querySelector but only first iterated buttons are getting selected

i am looping HTML buttons using PHP and adding EventListener for those buttons in JS using querySelector but only the first set of buttons are getting selected
Need to try querySelectorAll or please suggest something to make it work
[screenshot]
<?php $query='SELECT * FROM `posts`';
$result= mysqli_query( $conn,$query);
if(!$result){
echo "query1 failed";
}
while($rows= mysqli_fetch_assoc($result)){
echo $rows['post_text'];
?>
<br>
<form method="post" action="index.php" id="form">
<button type="submit" name="like" id='like' class="button" > <i class="ion-ios-thumbs-up like icon"></i> </button>
<button type="submit" name="love" id='heart' ><i class="ion-ios-heart icon heart icon"></i></button>
<button type="submit" name="dislike" id='dislike' ><i class="ion-ios-thumbs-down dislike icon"></i></button>
</form>
<br>
<?php
}
?>
<script>
document.querySelector('.like').addEventListener('click', function fn(e) {
e.preventDefault();
document.querySelector('.like').style.color='#3483e6';
document.querySelector('.dislike').style.color='#555';
document.querySelector('.heart').style.color='#555';
});</script>
I want all the buttons under all post should behave like first set of buttons
Check Official Documentation The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors.

passing value when you press button

I am having trouble passing a value
when pressing this button(the code for the button down below).
<div class="timeline-footer">
<button class="btn btn-primary btn-xs" name="onderreact_btn" type="submit">Reageer</button>
</div>
It needs to give a <form> a id from that reaction.
the code for the form to save it in the db. this works just fine but now it needs to give the id from the reaction when pressing the button to this form.
<?php
if(isset($_POST['react_btn'])){
unset($q1);
$q1['reactie'] = $app->check_string($_POST['reactie']);
$q1['topic_id'] = $app->check_string($_POST['topicid']);
$q1['klant_id'] = $app->check_string($_POST['klantid']);
$q1['ledenpagina_id'] = $app->check_string($_POST['ledenpaginaid']);
$app->insert_query('reacties', $q1, 'id');
}
?>
<form action="" method="post">
<div class="form-group">
<label for="comment">Reactie:</label>
<textarea class="form-control" name="reactie" rows="3" id="comment"></textarea>
<input type="hidden" name="klantid" value="<?php echo $_SESSION["klant_id"] ?>">
<input type="hidden" name="topicid" value="<?php echo $actieftopicid ?>"
<input type="hidden" name="ledenpaginaid" value="<?php echo $_SESSION["ledenpagina_id"]; ?>">
<input type="hidden" name="onderreactieID" value="<?php echo $reactie; ?>">
<button type="submit" name="react_btn" class="btn btn-primary">Plaats reactie</button>
</div>
</form>
I think I need to make a hidden input where I post the reactionID in and make some kind of javascript variable with a default set to 0 and when pressing on a button it needs to give that value trough to this variable
If you just need a test, if the button was pressed, check if the button was submittd:
if (isset($_POST['react_btn')) {
// ...
}
But as the value of the button is it's text, you should also add an hidden field, storing your id.
Keep in mind, that you could also submit the form by pressing enter inside a textfield in the form - in this case, the button wasn't pressed!

HTML element passing first value in PHP array

I've got a php page that gets data from mysql database as $certs[] and populates that as a table:
($db is read from file, it is constant)
<?php echo $cert["id"] ?>
<button type="button" class="awe" title="Edit" id="editbtn" onclick="openNewModalWithValue('Modal2')" value =<?php echo $cert["id"] ?> >&#xf019</button>
<form action="sample.php" method="POST">
<input type="hidden" name="id" value=<?php echo $cert["id"] ?>>
<input type="hidden" name="db" value=<?php echo $db ?>>
<button type="submit" name="mission" title="Delete">&#xf00d</button>
</form>
And I try to get id value in Modal window. (Like press 'EDIT' button and you get modal window with values set.) So my Modal window is:
<form id="modal-form" method="POST" action="sample2.php">
<input type="number" id="idb" name="idbase" />
<input type="text" id="nme" name="name"/>
<input type="hidden" name="db" value=<?php echo $db; ?>>
<input type="hidden" id= "idbs" name="idbs" />
<button id="form-submit" type="submit" >Edit</button>
</form>
and the Javascript for opening modal window is:
function openNewModalWithValue(modal){
document.getElementById(modal).style.display = "block";
document.getElementById("idb").value = document.getElementById("editbtn").value;
}
The problem is that even though PHP sends $certs[] values correctly, and table populates correctly, when I hit 'edit' button, I get preserved values of item#1 in PHP array, no matter which row/data I click.
Is there an easier way rather than applying counter to every row and operating with it?
Problem may be idb is multiple id in DOM. document.getElementById find Dom in whole page. so you must provide unique id

submit a form without refreshing the page [duplicate]

This question already has answers here:
Submit form without page reloading
(19 answers)
Closed 7 years ago.
I have a form that is responsible for inserting values in the database. It is working fine but when ever the values are submitted the page gets refreshed, I tried to take help from here, but it didn't worked in my case. can anyone please tell how I can submit the values without refreshing the page.
Code that I have for now is
<?
if($_POST['submit'])
{
$sender_id = mysqli_real_escape_string($con, $_POST['sender_id']);
$receiver_id = mysqli_real_escape_string($con, $_POST['receiver_id']);
$message = mysqli_real_escape_string($con, $_POST['message']);
// execute insert query here
}
?>
<form class="form-horizontal" enctype="multipart/form-data" role="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<input type="hidden" name="sender_id" value="<? echo $recruiterid; ?>">
<input type="hidden" name="receiver_id" value="<? echo $recv_id; ?>">
<textarea name="message" class="form-control" ></textarea>
<button type="submit" value="submit" name="submit" class="btn btn-greensea btn-ef btn-ef-7 btn-ef-7b b-0 br-2"><i class="fa fa-envelope"></i> Send Message</button>
</form>
You need to use AJAX to submit forms without refreshing. Add this in your JavaScript:
$("form").submit(function (e) {
e.preventDefault();
$.post($(this).attr("action"), $(this).serialize(), function () {
alert("Submitted!");
});
});

Categories