Item deletion using jquery ajax - javascript

Am having a problem with my jquery
i want to delete some products
but the only problem am getting, the deletion works only on first items even if i click the last item
Lets say i want to delete <p>INFO 20002</p> it will delete <p>INFO 2000</p>
i want to be able to delete any item i want
<script>
function callB() {
$("#button1").click(function(event) {
Execute();
});
function Execute() {
$.ajax({
type: 'POST',
url: 'ajax/file.aspx',
data: {
'custId': $("input[name='custId']").val()
},
success: function(response) {
},
error: function() {
alert("error");
}
});
};
}
$(document).ready(function() {
callB();
});
</script>
<div>
<p>INFO 2000</p>
<input type="button" id="button1" value="Erase this">
<input type="hidden" name="custId" value="348700">
</div>
<div>
<p>INFO 20001</p>
<input type="button" id="button1" value="Erase this">
<input type="hidden" name="custId" value="4443487">
</div>
<div>
<p>INFO 20002</p>
<input type="button" id="button1" value="Erase this">
<input type="hidden" name="custId" value="8883487">
</div>
<div>
<p>INFO 20003</p>
<input type="button" id="button1" value="Erase this">
<input type="hidden" name="custId" value="1113487">
</div>

Because all your button have same ids i.e. button1 and when you click any button your function Execute(); executed and inside your ajax data you are sending data with $("input[name='custId']").val() means it will always give you the value of first occurrence and that is why when clicking any button because all your buttons have same ids the Execute() function executed and your first item deleted.So when you click any button send that clicked button value your problem will be solved. Also please try to give the id value unique.
$("[type=button]").on('click', function() {
var custId = $(this).closest('div').find('[name=custId]').val();
Execute(custId);
});
function Execute(custId) {
$.ajax({
type: 'POST',
url: 'ajax/file.aspx',
data: {
'custId': custId
},
success: function(response) {
},
error: function() {
alert("error");
}
});
}

Your input buttons need to have unique id attributes (or no ids at all, in this case).
Give all of them the same class-name.
<input type="button" class="deleteButton" value="Erase this" />
Put the customer id into the 'button' element, instead of its own hidden input.
<input type="button" class="deleteButton" value="Erase this" data-custid="348700" />
Then update your jquery selector for the button click event, and refer to that class-name.
$('input.deleteButton').on('click', function(event) {
var $button = $(this);
// USE THE jQUERY OBJECT'S .data() METHOD TO GET THE BUTTON's CUST-ID
// var customerId = $button.data('custid');
Execute($button);
});
Then, on the 'success' of the ajax request, refer to the '$button' object, and remove its <div> parent.
$button.closest('div').remove();

Related

AJAX request in a looping form

I was wondering how to make an ajax request separately inside the looping form, which able to send the async delete request when I click the specified row deleted button.
not sure how to allocate the identity when I click the button using jquery.
foreach(var item in Model){
<form>
<input type="text" id="id" name="id" value="item.id"/>
<input type="button" id="btn" name="submit" value="Delete"/>
</form>
}
<script>
$("#btn").click(function(){
// alert the id value
});
</script>
You can try with
foreach(var item in Model){
<form>
<input type="text" id="id" name="id" value="item.id"/>
<input type="button" class="btn" data-id="item.id" name="submit" value="Delete"/>
</form>
}
<script>
$(".btn").click(function(){
// alert the id value
alert($(this).attr("data-id"))
});
</script>
I have found the solution based on Agus Friasana method:
$(".btn").click(function () {
// to skip the alert from parent modal button
if ($(this).attr("data-id") != undefined) {
alert($(this).attr("data-id").toString());
$.ajax(
{
url: "your url" + $(this).attr("data-id").toString(),
type: "DELETE",
dataType: "text",
success: function () {
alert('success');
},
error: function () {
alert('fail')
}
}
);
}
});

JavaScript ActiveElement is form not button with Safari

I have a list of forms on my site with JS/AJAX that submits the forms on click. The JavaScript determines the submit type based on the active element. This has been working find across multiple browser.
Problem: Basically Safari (Version 10.0.2) on MAC considers the activeElement the form instead of the button so the getAttribute returns null. Is there a way to get the clicked element? I need to know which button the user clicked.
HTML Stuff:
<div id="#Records">
<form action="update.php" method="post">
...
<input name="submit" type="submit" data-action="send" value="send stuff" />
<input name="submit" type="submit" data-action="update" value="update" />
<input name="submit" type="submit" data-action="delete" value="delete" />
</form>
</div>
JavaScript stuff
$("#Records form").submit(function (e) {
e.preventDefault();
var url = this.action;
var data = $(this).serializeArray();
var action = document.activeElement.getAttribute('data-action');
data.push({ name: 'submit', value: action });
$.ajax({
type: "POST",
data: data,
cache: false,
url: url
}).done(function (data) {
$("#Records").html(data);
}).fail(function (result) {
ShowMessage("Error updating record!");
});
return false;
});
Can't you get the element using e.currentTarget instead of the active element? Something like
var action = $(e.currentTarget).attr('data-action');
(I'm assuming button click leads to the submit)
Ok, based on Tiny Giant and other comments I have changed the code to this. Not sure it is the best method but seems to work everywhere I have tested.
note simplified, comments welcome
HTML
<div id="#Records">
<form action="update.php" method="post">
...
<input type="button" onclick="return $(this).processRequest(this, 'send');" data-action="send" value="send stuff" />
<input type="button" onclick="return $(this).processRequest(this, 'update');" data-action="update" value="update" />
<input type="button" onclick="return $(this).processRequest(this, 'delete');" data-action="delete" value="delete" />
</form>
</div>
JavaScript
jQuery.fn.processRequest =
function(button, action)
{
var form = $(button).parents('form');
var url = form[0].action;
var data = $(form).serializeArray()
data.push({ name: 'submit', value: action });
$.ajax({
type: "POST",
data: data,
cache: false,
url: url
}).done(function (data) {
$("#Records").html(data);
}).fail(function (result) {
ShowMessage("Error updating record!");
});
return false;
}

Submit jQuery ajax Form with multi buttons and PHP

here is my problem:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<form id="roomform" action="room.php" method="POST">
<button name="room" value="Room01">IMG01</button>
<button name="room" value="Room02">IMG02</button>
<button name="room" value="Room03">IMG03</button>
<button name="room" value="Room04">IMG04</button>
<button name="room" value="Room05">IMG05</button>
<button name="room" value="Room06">IMG06</button>
<button name="room" value="Room07">IMG07</button>
<button name="room" value="Room08">IMG08</button>
<button name="room" value="Room09">IMG09</button>
<button name="room" value="Room10">IMG10</button>
</form>
<script type="text/javascript">
var frm = $('#roomform');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
</body>
</html>
PHP using $_POST['room'] to get the room name Room01-Room10(Room100 maybe?) and doing something special.
It works good.
Now I need to do this using Ajax. Above code seems ok, but I cannot get any data(Room01-Room10) from it.
then I found this:
<form action="/vote/" method="post" class="vote_form">
<input type="hidden" name="question_id" value="10" />
<input type="image" src="vote_down.png" class="vote_down" name="submit" value="down" />
<input type="image" src="vote_up.png" class="vote_up" name="submit" value="up" />
</form>
$(".vote_form").submit(function() { return false; });
$(".vote_up, .vote_down").click(function(event) {
$form = $(this).parent("form");
$.post($form.attr("action"), $form.serialize() + "&submit="+ $(this).attr("value"), function(data) {
// do something with response (data)
});
});
but it seems not suitable to my case, my all buttons with same name="room" for $_POST['room'] and no class.
and this not works:
$(function() {
$('input[name=room]').click(function(){
var _data= $('#roomform').serialize() + '&room=' + $(this).val();
$.ajax({
type: 'POST',
url: "room.php?",
data:_data,
success: function(html){
$('div#1').html(html);
}
});
return false;
});
});
anyone know how to solve this problem?
Your (last) code is not sending AJAX requests because you attached the handler to the wrong input selector. Your buttons are button elements, not input elements. This should work:
$('button[name=room]').click(function() { ...
Edit:
Your first code isn't working because your buttons are just buttons. You have to add the type attribute to let your form know you're pressing a submit button: <button type="submit"...>
The serialize() method does not collect the data from a button element. Take a look to the documentation on this link: https://api.jquery.com/serialize/. In your code I would assume that your data object is empty.
Also if you post several form controls (serialized) , they should have different name attributes.

multiple submit buttons different actions with passing variables

I have a form like the code below (called index.php) with multiple submit buttons. I'd like to have different php actions on submit buttons. The 1st button without refreshing the browser's page and of course with passing the variables. The other with normal action which can redirect to a new page (here form_submit.php). I managed to make the 1st button working with the help of this topic but I can't distinguish the 2nd button from the 1st one. Is there any way to switch between functionality of these buttons ?
<? php>
if($_POST['formSubmit'] == "Next") {
$var1 = $_POST['name1'];
$var2 = $_POST['name2'];.
session_start();
$_SESSION['variable1'] = $var1;
$_SESSION['variable2']= $var2;
header("Location: form_submit.php");
exit;
}
?>
<html>
<body>
<form action="index.php" method="post">
<input type="text" name="name1" id="name1" maxlength="50" value="<?=$var1;?>" />
<input type="text" name="name2" id="name2" maxlength="50" value="<?=$var2;?>" />
<input type="submit" name="dataSubmit" value="Insert Data" />
<input type="submit" name="formSubmit" value="Next" />
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'data_submit.php',
data: $('form').serialize(),
});
});
});
</script>
</form>
</body>
</html>
As soon as 1st button doesn't actually need to make submit you can set 'onClick' event handler on it and make it just 'button'. In this case only JS will be triggered when you press the button and browser will not submit the form. Here is what I mean:
<input type="button" id="justButton" name="dataSubmit" value="Insert Data" />
<input type="submit" name="formSubmit" value="Next" />
<script>
$(function () {
$('#justButton').on('click', function (e) {
$.ajax({
type: 'post',
url: 'data_submit.php',
data: $('form').serialize(),
});
});
});
</script>
First, add clicked class to button:
$('.submitButton').click(function(){
$('.submitButton').removeClass('clicked');
$(this).addClass('clicked');
});
Than in submit event check button:
$('form').submit(function(){
var button = $('.submitButton.clicked');
if (button.attr('id') == 'name1') {
...
} else {
...
}
return false;
});

Getting the value of the child of sibling jquery/ajax?

I'm currently trying to make a ajax comment function work once a user clicks "open comments".
Currently I'm getting data back from my php script and the status of the ajax call is "200 OK" so it definetely works but I'm just unable to get the correct value for the current comment which has been clicked on in order to post it to the php script.
What I'm asking is how do I get the value of the ".posted_comment_id" class and then how do I load the data which is returned into the ".commentView" class?
jQuery/AJAX:
$(".closedComment").click(function(){
var $this = $(this);
$this.hide().siblings('.openComment').show();
$this.siblings().next(".commentBox").slideToggle();
$.ajax({
type: "POST",
url: "http://example.dev/comments/get_timeline_comments",
data: {post_id: $this.siblings().next(".commentBox").find(".posted_comment_id").val()},
dataType: "text",
cache:false,
success:
function(data){
$this.closest(".commentView").load(data);
}
});
return false;
});
HTML:
<div class="interactContainer">
<div class="closedComment" style="display: none;">
open comments
</div>
<div class="openComment" style="display: block;">
close comments
</div>
<div class="commentBox floatLeft" style="display: block;">
<form action="http://example.com/comments/post_comment" method="post" accept-charset="utf-8">
<textarea name="comment" class="inputField"></textarea>
<input type="hidden" name="post" value="13">
<input type="hidden" name="from" value="5">
<input type="hidden" name="to" value="3">
<input type="submit" name="submit" class="submitButton">
</form>
<div class="commentView"></div>
<div class="posted_comment_id" style="display:none;">13</div>
</div>
</div>
Replace .val by .html or .text. This will return the innerHTML of the element.
data: {
post_id: $this.siblings().next(".commentBox").find(".posted_comment_id").text()
}
You might need to convert the string to an integer to make it work.
If the query selector fails, this selector might do the job instead:
$this.parent().find(".posted_comment_id")
To add the returned data on your webpage, use the success handler. Here's an example of how it's done:
success: function(json) {
// Parse your data here. I don't know what you get back, I assume JSON
var data = JSON.parse(json),
content = data.whatever_you_want_to_print;
// Assuming your selector works, you put in in the element using .html
$this.closest(".commentView").html(content);
}
});
You probably want to do something like:
$(this).parents('.interactContainer').find(".posted_comment_id").text()

Categories

Resources