Я пытаюсь нажать на кнопку оплаты, чтобы обновить оплату определенной компании. Ниже мой пользовательский интерфейс
нажатие на кнопку оплаты показывает это
Я хотел бы отобразить название компании, в которую будет осуществляться платеж, а также иметь возможность обновлять платеж в столбце «Общий перевод», а также уменьшать задолженность.
Я давно застрял на этой странице. Ниже мой код: запрос
error_reporting( E_ALL );
try{
$sql='select c.catid, c.`category`,
ifnull(sum( s.`stock_in` * s.`stock_price` ),0) as `debt`, c.`remitted`
from `tbl_category` c
left outer join `tbl_stock_in` s on s.`category_name` = c.`category`
group by c.`category` order by catid desc;';
$stmt=$pdo->prepare( $sql );
$stmt->execute();
}catch( PDOException $e ){
echo $e->getMessage();
}
код для таблицы
<?php
while( $rs=$stmt->fetch(PDO::FETCH_OBJ ) ){
echo'
<tr>
<td>'.$rs->catid.'</td>
<td>'.$rs->category.'</td>
<td>
'.number_format($rs->debt,2).'
</td>
<td>'.number_format($rs->remitted,2).'</td>
<td>
<button id='.$rs->catid.' class = "btn btn-info btnremit"><span class = "glyphicon glyphicon-eye-open" style = "color:#ffffff" data-toggle = "tooltip" title = "Pay Company"></span></button>
</td>
<td>
<a href = "#.php?id='.$rs->catid.' class = "btn btn-info" role = "button"><span class = "glyphicon glyphicon-edit" style = "color:#ffffff" data-toggle = "tooltip" title = "Edit Category"></span></a>
</td>
<td>
<button id='.$rs->catid.' class = "btn btn-danger btndelete" ><span class = "glyphicon glyphicon-trash" style = "color:#ffffff" data-toggle = "tooltip" title = "Delete Category"></span></button>
</td>
</tr>
';
}
?>
вот мой аякс
<script>
$(document).ready(function() {
$('.btnremit').click(function() {
//var tdh = $(this);
var id = $(this).attr("id");
swal("Enter Amount:", {
buttons: true,
closeModal: true,
content: "input",
})
.then((amount) => {
if (amount === "") {
swal("Oops!! You need to enter value.");
return false
}else{
$.ajax({
type: 'POST',
url: 'remit.php',
data:{rid: id, pay: amount,
<?php
echo ' currentDate : "'.$savedate.'", //working
compnyName : "'#'", //how do i call the company name that is clicked
old_remit : "'#'",//how do i fetch the old remit from the table
'
?>
},
success: function(data){
swal(`Paid: ${amount}`);
},
error: function(data){
swal(`Error remitting: ${amount}`);
}
});
}
});
});
});
</script>
код для remit.php*
<?php
#stock-in.php
/*
If you are using sessions you need to start a session!
*/
error_reporting( E_ALL );
session_start();
if ( empty( $_SESSION['useremail'] ) OR empty( $_SESSION['role'] ) OR $_SESSION['role']= = "Admin" ){
exit( header('Location: index.php') );
}
/*
Check that all fields that are required in the sql have been submitted
*/
if ( isset(
$_POST['rid'],
$_POST['pay'],
$_POST['currentDate'],
$_POST['compnyName'],
$_POST['old_remit']
) ){
try{
include_once 'connectdb.php';
/*
When inserting, updating multiple tables there is some sense in using a transaction
so that if one part fails the db is not littered with orphan records
*/
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$pdo->beginTransaction();
$remitID = $_POST['rid'];
$new_remit = (double)$_POST['pay'];
$current_date = $_POST['currentDate'];
$company = $_POST['compnyName'];
$old_rem = (double)$_POST['old_remit'];
$paid = $new_remit + $old_rem;
/*
The sql command should use placeholders rather than embedded variables - the names are arbitrary
*/
$sql='INSERT INTO `tbl_category_remits` ( `payment_date`, `category`, `remitted` )
VALUES
( :pay_date, :comp, :remit, :price, :cost, :current_times )';
$stmt=$pdo->prepare( $sql );
$args=array(
':pay_date' => $current_date,
':comp' => $company,
':remit' => $new_remit
);
if ( !$stmt->execute( $args ) )echo 'stmt#1 failed';
$sql='UPDATE `tbl_category` SET `remitted` =:payment WHERE `catid`=:rid';
$stmt=$pdo->prepare( $sql );
$args=array(
':payment' => $paid,
':rid' => $remitID
);
if ( !$stmt->execute( $args ) )echo 'stmt#2 failed';
/*
If it all went well, commit these statements to the db
*/
if ( !$pdo->commit() )echo 'commit failed';
}catch( PDOException $e ){
/*
Any problems, rollback the transaction and report issues -
not necessarily with the full `getMessage()` ~ perhaps just
'Error!' etc
*/
$pdo->rollBack();
echo $e->getMessage();
}
}
?>
Пожалуйста, как мне получить название компании и старый перевод из таблицы, когда я нажимаю на оплату. Мне нужна ваша помощь!!
Спасибо за быстрый ответ. На модальном я бы хотел, чтобы название компании отображалось. Я также хотел бы, чтобы название компании и старая задача были отправлены через ajax.
покажи свой код remit.php.
я обновил его
см. мой этот ответ, если он поможет вам. stackoverflow.com/questions/62468814/…
Я думаю, что щелчок по идентификатору будет работать для определенной строки таблицы. Я сделал это при подтверждении удаления, но основная проблема здесь заключается в том, чтобы разместить данные строки в моем ajax, в частности, название компании и старую задачу.
Давайте продолжим обсуждение в чате.






вы можете отправить название страны и старый перевод из php в качестве объекта, а с помощью obj jquery использовать их в правильном элементе
Пожалуйста, как мне это сделать? Я новичок в этом.
в php вы можете вернуть данные с помощью функции json_encode, например json_encode(['name' => 'test' , 'remit' => 2]), затем вы можете проанализировать этот ответ с помощью jquery var obj = jQuery.parseJSON( '{ "name": "test","remit":2 }' ); и установить obj для элемента ("#countryName").html(obj.name). если это ввод, вы можете использовать ("#countryName").val(obj.name)
Вместо
$(document).ready(function() {
$('.btnremit').click(function() {
//var tdh = $(this);
var id = $(this).attr("id");
})
})
Вы можете использовать функцию, в которой вы можете передать идентификатор, имя и т. д.
function yourFunction(id,companyName,oldRemit){
swal("Enter Amount:", {
buttons: true,
closeModal: true,
content: "input",
})
.then((amount) => {
if (amount === "") {
swal("Oops!! You need to enter value.");
return false
}else{
$.ajax({
type: 'POST',
url: 'remit.php',
data:{
rid: id,
pay: amount,
compnyName : companyName,
old_remit : oldRemit,
<?php
echo 'currentDate : "'.$savedate.'"'
?>
},
success: function(data){
swal(`Paid: ${amount}`);
},
error: function(data){
swal(`Error remitting: ${amount}`);
}
});
}
});
}
И из строки вашей таблицы html вызовите эту функцию, например
<td>
<button onclick = "yourFunction('.$rs->catid.','.$rs->category.','.$rs->remitted.')" id='.$rs->catid.' class = "btn btn-info btnremit"><span class = "glyphicon glyphicon-eye-open" style = "color:#ffffff" data-toggle = "tooltip" title = "Pay Company"></span></button>
</td>
как вы повторяете compnyName , old_remit в модальном режиме.
Вы можете установить название swal как companyName. @КУМАР
Спасибо за эти усилия; Я реализовал это, но получил сообщение об ошибке: Uncaught ReferenceError: Pinnacle не определен.
Попробуйте эту <td> <button onclick = "yourFunction(\''.$rs->catid.'\',\''.$rs->category.'\',\''.$rs-> передано.'\')" id='.$rs->catid.' class = "btn btn-info btnremit"><span class = "glyphicon glyphicon-eye-open" style = "color:#ffffff" data-toggle = "tooltip" title = "Pay Company"></span></ кнопка> </td>
На самом деле он выбрал имя и все указанные данные, но не смог обновить базу данных введенным мной значением.
в модальном вы хотите
company name and old remit??