multiple forms with jquery serialize method not working - php

I have multiple form and each form is getting submitted but not the first one.
I tried everything like event.preventDefault();
MY CODE :
<?php for($i=0;$i<=5;$i++){ ?>
<form id="form<?php echo $i; ?>>
<td><?php echo $i++ ?><td>
<td><input type="text" name="detention_unloading_charges" value="<?php echo $history[$i]->name; ?>"></td>
<td><input type="text" name="dtn_chrg_per_day" value="<?php echo $history[$i]->dtn_chrg_per_day; ?>"></td>
<td><input type="text" name="dtn_chrg" value="<?php echo $history[$i]->dtn_chrg; ?>"></td>
<td>
<button class="btn btn-secondary" type="button" onclick="save_changes(<?php echo $i ?>);">Save Changes</button></td>
</form>
}
and jquery function:
function save_changes(id)
{
$.ajax({
url: "History/update",
type: "POST",
data: $('#form'+id).serialize(),
success: function(data) {
// Success message
console.log(data);
if(data==1){
$('.success_pop_up').addClass('show').removeClass('d-none');
} else{
$('.failure_pop_up').addClass('show').removeClass('d-none');;
}
}
});
}

You are incrementing $i twice in the beginning itself by echo $i++, which also increments $i apart from for loop , so loop runs only thrice and form id is form0 but corresponding function is save_changes(1) , where that form id does not exist at all , try below code.
<?php for($i=0;$i<=5;$i++){ ?>
<form id="form<?php echo $i; ?>>
<td><?php echo $i?><td>
<td><input type="text" name="detention_unloading_charges" value="<?php echo $history[$i]->name; ?>"></td>
<td><input type="text" name="dtn_chrg_per_day" value="<?php echo $history[$i]->dtn_chrg_per_day; ?>"></td>
<td><input type="text" name="dtn_chrg" value="<?php echo $history[$i]->dtn_chrg; ?>"></td>
<td>
<button class="btn btn-secondary" type="button" onclick="save_changes(<?php echo $i ?>);">Save Changes</button></td>
</form>
<?php } ;?>
Try this code and let me know if it works.

You'll probably want to solve this the following way:
Let the button do a default submit like so:
<button type="submit">Send</button>
Catch the submit event for your form in jQuery:
$('form').on('submit', function(e) {
// Prevent default so the browser doesnt automatically submit it.
e.preventDefault();
var data = $(this).serialize();
// ... send it
});
This way it is much easier to do AJAX form requests.

Related

Delete row by ajax php

Hello I am just learning codeigniter, here I am displaying a database and there are several rows. I made a delete function with ajax, it worked, but it had to be reloaded, how so that when I click delete, the data is deleted and it doesn't have to be refreshed.
<tbody id="tbody">
<?php
$no = 1;
foreach ($temporary as $m) { ?>
<tr>
<input type="hidden" class="form-control" name="id_service" value="<?php echo $m->id_service ?>">
<input type="hidden" class="form-control" name="id_cs" value="<?php echo $m->id_cs ?>">
<input type="hidden" class="form-control" name="jenis" value="<?php echo $m->jenis ?>">
<td>
<input type="hidden" class="form-control" name="id_tmp" value="<?php echo $m->id_tmp ?>">
<input type="text" class="form-control" name="" value="<?php echo $m->tracking_number ?>">
</td>
<td>
<button type="button" class="btn btn-danger" onclick="deletes(<?php echo $m->id_tmp;?>)">Delete</button>
</td>
</tr>
<?php } ?>
</tbody>
ajax
function deletes(id){
if (confirm("Are you sure?")) {
$.ajax({
url: '<?php echo base_url();?>backend/inbound/del',
type: 'post',
data: {id_tmp:id},
success: function () {
alert('ok');
},
error: function () {
alert('gagal');
}
});
} else {
alert(id + " not deleted");
}
}
Another way you can use .closest() for more details Click here
Php Code
<tbody id="tbody">
<?php
$no = 1;
foreach ($temporary as $m) { ?>
<tr class="jsRowDelete">
<input type="hidden" class="form-control" name="id_service" value="<?php echo $m->id_service ?>">
<input type="hidden" class="form-control" name="id_cs" value="<?php echo $m->id_cs ?>">
<input type="hidden" class="form-control" name="jenis" value="<?php echo $m->jenis ?>">
<td>
<input type="hidden" class="form-control" name="id_tmp" value="<?php echo $m->id_tmp ?>">
<input type="text" class="form-control" name="" value="<?php echo $m->tracking_number ?>">
</td>
<td>
<button type="button" class="btn btn-danger" onclick="deletes(<?php echo $m->id_tmp;?>,this)">Delete</button>
</td>
</tr>
<?php } ?>
</tbody>
Jquery Code
function deletes(id,oElem) {
if (confirm("Are you sure?")) {
$.ajax({
url: '<?php echo base_url();?>backend/inbound/del',
type: 'post',
data: {
id_tmp: id
},
success: function() {
//alert('ok');
console.log($(oElem).closest(".jsRowDelete"));
$(oElem).closest(".jsRowDelete").remove();
//or
//$(oElem).closest("tr").remove();
},
error: function() {
alert('gagal');
}
});
} else {
alert(id + " not deleted");
}
}
You can check the working example click here
Since you've mentioned it's deleting on the backend or your database, you could just use jquery to delete that row on the UI. Here's one way without modifying your markup.
First is you add a class to the input field that contains the ID. I used id-input
<input type="hidden" class="form-control id-input" name="id_tmp" value="<?php echo $m->id_tmp ?>">
Then use this ajax to navigate through the input fields with that class and value to delete the row. See my code on success function;
function deletes(id){
if (confirm("Are you sure?")) {
$.ajax({
url: '<?php echo base_url();?>backend/inbound/del',
type: 'post',
data: {id_tmp:id},
success: function () {
// loop through all input with class id-input
$(".id-input").each(function(){
// if it matches the value delete parent row
if($(this).val() == id){
// delete parent row
$(this).parent().parent().remove();
}
});
},
error: function () {
alert('gagal');
}
});
} else {
alert(id + " not deleted");
}
}
EDIT: use .parent().parent() as we need to refer to tr, not td

How to delete multiple using checkbox with Ajax call

i am trying to delete values with check box using ajax call can any one help me out.
unable to find the error and one nore thing this is a template and i hav a feature of check all inbuilt so do need to change anyinbuilt code for check box
This is my listing form:
<form id="stafflistForm">
<input type="hidden" name="checkedids" value="<?php echo $staffResults['id_staff']; ?>">
<button id="deleteChecked"><i class="fa fa-trash-o"></i></button>
</form>
This my Ajax Script:
<script language="JavaScript">
$("#deleteChecked").click(function()
{
$("#delshowMessageDiv").hide();
$("#delshowMessage").html('');
$.ajax({
url: "staffcontroller.php",
method: "POST",
data: { delData : $("#stafflistForm").serialize(), 'action':'delete'},
dataType: "json",
success: function (response) {
if(response["success"]==true)
{
$("#delshowMessageDiv").hide();
$("#delshowSuccessMessageDiv").show();
$("#delshowSuccessMessage").html(response["message"]);
}else{
$("#delshowMessageDiv").show();
$("#delshowMessage").html(response["message"]);
}
},
error: function (request, status, error) {
$("#hshowMessageDiv").show();
$("#hshowMessage").html("OOPS! Something Went Wrong Please Try After Sometime!");
}
});
return false;
});
</script>
And this is my controller page:
else if($_REQUEST['action']=='delete'){
$delids=explode(",",$_REQUEST["checkedids"]);
$count=count($delids);
for($i=0;$i<$count;$i++)
{
$delQuery= $conn->query("DELETE FROM os_staff WHERE id_staff=".$delids[$i]);
}
if($delQuery){
$response['message'] = "<strong>Success!</strong>Staff Deleted Successfully.";
$response['success'] = true;
}else{
$response['message'] = "<strong>Warning!</strong> Staff Not Deleted.Please Check Carefully..";
$response['success'] = false;
}
echo json_encode($response);
exit;
}
First of all: Dont use html attribute id if you using it multipli id="deleteChecked". Use class selector or data attribute instead.
Here is a small script which show you how you can improve your code.
That should be help you to solve your issue.
$(document).ready(function() {
$('.delete-user').on('click', function(e) {
// do here your ajax
// this is just example
$(this).parents('tr').remove();
});
});
.fa-trash-o {
padding: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<form class="stafflistForm">
<input type="hidden" name="checkedids" value="<?php echo $staffResults['id_staff']; ?>">
<button class="delete-user"><i class="fa fa-trash-o"></i></button>
</form>
</td>
<td>Tom</td>
</tr>
<tr>
<td>
<form class="stafflistForm">
<input type="hidden" name="checkedids" value="<?php echo $staffResults['id_staff']; ?>">
<button class="delete-user"><i class="fa fa-trash-o"></i></button>
</form>
</td>
<td>Peter</td>
</tr>
<tr>
<td>
<form class="stafflistForm">
<input type="hidden" name="checkedids" value="<?php echo $staffResults['id_staff']; ?>">
<button class="delete-user"><i class="fa fa-trash-o"></i></button>
</form>
</td>
<td>Son Goku</td>
</tr>
<tr>
<td>
<form class="stafflistForm">
<input type="hidden" name="checkedids" value="<?php echo $staffResults['id_staff']; ?>">
<button class="delete-user"><i class="fa fa-trash-o"></i></button>
</form>
</td>
<td>Gozilla</td>
</tr>
</table>
The PHP script should set the correct mime type via:
header('Content-type: application/json');
Besides that: Why do you have separate DIV containers for the error and success messages? Why not have one "feedback" div, which gets a CSS class which does the formating (based on error or success).

jquery $.post fails to send data on second request

I have a bunch of records from a database that I am displaying on a page. Each record has their own form with an update and delete button. I'm using JQuery ajax to send the data to a PHP page to process the form.
The script works fine the first time I push any one of the buttons on any of the forms, but when I push another button on any of the forms (or even the same button on the same form) the ajax request doesn't send any of the data to the PHP page.
Code I'm using to output data on page:
<?php
foreach($records as $data) {
?>
<form>
<input type="number" name="et" step="0.01" value="<?php echo $data->et; ?>" />
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="hidden" name="id" value="<?php echo $data->et_id; ?>"/>
<input type="submit" name="update" value="Update" />
<input type="submit" name="delete" value="Delete" />
</form>
<?php
}
Javascript:
$(document).ready(function() {
var buttonName;
$('input[type=submit]').click('click', function() {
buttonName = $(this).attr('name');
});
$('form').on('submit', function(e) {
e.preventDefault();
var values = $(this).serializeArray();
console.log(values);
if(buttonName == 'delete') {
var message = confirm('Are you sure you want to delete this record?\n\n You can\'t get it back once you do.');
} else {
message = true;
}
if(message) {
$.post('submit/raw_et.php', {et: values[0].value, token: values[1].value, id: values[2].value, button: buttonName}, function(r) {
console.log(r);
});
}
});
});
PHP Snippet:
echo $_POST['button'];
echo $_POST['et'];
echo $_POST['id'];
The "values" variable in the javascript always has the correct data, but the ajax fails to send any data after the first time a button is pushed and the results return blank.
I don't understand why it won't send the data. Am I missing something really easy, or is it something more complicated?
Edit:
I've taken out the tables in the html, but still get the same results.
you are developing in a completely wrong pattern, instead of defining form inside tr, use record id and register event for clicking buttons:
<?php
foreach($records as $data) {
?>
<tr>
<td><input type="number" name="et" step="0.01" value="<?php echo $data->et; ?>" /></td>
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="hidden" name="id" value="<?php echo $data->et_id; ?>"/>
<td><a class='edit' meta-id="<?php echo $record; ?>">edit</a></td>
<td><a class='delete' meta-id="<?php echo $record; ?>">delete</a></td>
</tr>
<?php
}
?>
And now, try to register all buttons onclick for delete and edit.
$(".edit").click(function() {
var record = $(this).attr("meta-id");
$.post("edit uri" , {record : record , otherparam: valueofit} , function(result) {
alert(result);
});
});
$(".delete").click(function() {
var record = $(this).attr("meta-id");
$.post("delte uri" , {record : record} , function(result) {
alert(result);
});
});
You can expand the concept as you want, for less adding class to buttons or so on.

Get Ajax variable from the PHP foreach loops

I have a simple ajax (jquery version) script and very short php function and they works fine without problem.
When I submit the value from the form input are, the ajax will work to send and get result from
the php script, in this case to get a total amount of the book order.
The Ajax script and html section are as follows:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get field value
var qtyVal = $('#qty').val();
// use HTTP GET get ajax
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
//get xml value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
<body>
Total price:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div>
<form>
<p>
<label>quantity: </label>
<input type="text" id="qty" name="qty"/>
<br/>
<input type="submit" value="submit">
total price:</p>
<p> </p>
</form>
And the following php script serving as xml also works fine with above ajax request:
<?php
// XML document
header("Content-Type: text/xml");
header("Content-Type:text/html; charset=utf-8");
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
echo "<?xml version=\"1.0\" ?>";
echo "<datetime>";
echo "<qty>" . $qty*100 . "</qty>";
$total=$qty*100;
if ($total==0)
echo "<caution>"."please input number!"."</caution>";
else if ($total<=500)
echo "<caution>"."you shoud buy more!"."</caution>";
echo "";
echo "</datetime>";
?>
However when I combine the above scripts with my shopping cart foreach loops, it doesn't work and the ajax script failed to get variables from the form input area. I don't know if it is a variable scope issue (globals or local)? or anything else?
The following is the total script I would like to fixed with:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get value from the form
var qtyVal = $('#qty').val();
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
</head>
<body>
<table border="1" align="center">
<tr>
<th>no</th>
<th>name</th>
<th>price</th>
<th>qty</th>
<th>update</th>
</tr>
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<form action="sessionCartUpdate.php">
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" id="qty" name="qty" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<input type="submit" name="qty"
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
</form>
<?php
}
?>
<tr><td colsan="5">total amount:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div></td></td>
</table>
<p>continue to shop
<p>Put your order
</body>
</html>
I would be very grateful if anyone can offer kind or possible suggestion or advice?
My goal is to put different number (variables) in the "input area" (name or id as "qty") throught the using of ajax to get a total amount of price and show the result in the div box (id="result" or "result1").
You should replace the id attribute with class because id is supposed to be unique in the dom and using class you can do a loop to get all quantities of the items in the cart
Another thing i have noticed that you have made the an individual form foreach item in the cart there should be one form having the multiple fields,also remove this line <input type="submit" name="qty" it doesent makes sense
<form action="sessionCartUpdate.php">
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" class="qty" name="qty[]" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
<?php
}
?>
</form>
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
var qtyVal =0;
$( ".qty" ).each(function() {
qtyVal =qtyVal + parseInt($(this).val());
});
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
Instead of using both $_GET and $_POST, you can use $_REQUEST which will give data from either POST or GET.

Multiple Checkbox Form Issue using Ajax and Jquery

I'm trying to make a form that is in a loop has a unique id.
The issue with this is only the first form is working and all the rest after is not triggering the jquery code.
Form:
<?php foreach( $tasks as $tasks ) : ?>
<tr>
<td><?php echo $tasks->title ?></td>
<td><?php echo $newDate; ?></td>
<td><?php echo $tasks->details ?></td>
<td><?php echo $tasks->category ?></td>
<td>
<form class="noclass">
<input class="hideit id" type="text" name="id" value="<?php echo $tasks->id ?>" />
<input type="checkbox" value="<?php echo $tasks->user ?>" name="value" id="checkbox-2-1" class="regular-checkbox big-checkbox" <?php echo $tasks->user ?> />
</form>
</td>
</tr>
<?php endforeach; ?>
Jquery:
<script>
$(function() {
$('#checkbox-2-1').click(function() {
var id = $(".id").val();
var value = $(".check").val();
var dataString = '?id=' + id + '&value=' + value + '&user=<?php echo $id ?>';
alert(dataString);
$.ajax({
type: "POST",
url: "http://example.com/process.php",
data: dataString,
cache: false,
});
})
})
return false;
</script>
You are using
var id = $(".id").val();
var value = $(".check").val();
and what $(".id") and `$(".check")' will return is object.
So you need to convert it into string of key value pair and then send it.
Also refer Gautam answer for foreach correction.
ONE MORE
You are repeating checkbox-2-1 id for checkbox evert-time loop gets execute and ID for each dom must be unique.
What i suggest
Use code as below.
for checkbox click event use
$('input:ckeckbox[name="value"]').on('change',function(){ });
and inside function(){ } write code for getting value of class id and check as below
$(this).closest('form.noclass').find('.id').val();
$(this).closest('form.noclass').find('.value').val()
Your first form is not closing....close like this
<form class="noclass">
<input class="hideit id" type="text" name="id" value="<?php echo $tasks->id ?>" />
</form>
<form class="noclass">
<input class="hideit id" type="text" name="id" value="<?php echo $tasks->id ?>" />
<input type="checkbox" value="<?php echo $tasks->user ?>" name="value" id="checkbox-2-1" class="regular-checkbox big-checkbox" <?php echo $tasks->user ?> />
</form>
And what is
<?php foreach( $tasks as $tasks ) : ?>
try to give another variable like
<?php foreach( $tasks as $task ) : ?>
and then change the symultanious

Categories