So I have a database of vehicles and I made a form where a user can update the information of vehicles and then confirming if he/she wants to save the changes. Problem is I feel like I am still not understanding how AJAX works and here's what Iv done so far.
This is the form the users use to edit a vehicles information.
<html>
<body>
<table align = 'center' cellspacing='2'>
<tr>
<th> Enter Vehicle Information </th>
</tr>
<form enctype = 'multipart/form-data' method = 'post' action = '' >
<?php
if($v = $Vehicle->fetch())
{
?>
<input type = "hidden" id='vID' value = '<?php echo $v['Vehicle_N'];?>'/>
<img src = "Vehicles/<?php echo $v['Image']?>" height = 100 width = 100 > </img>
<tr>
<td>Vehicle Manufacturer
<select id = "Manufacturer" value = '<?php echo $v['Manufacturer'];?>'>
<?php
foreach($Manu as $m)
{?>
<option value = '<?php echo $m['Manufacturer'] ?>'> <?php echo $m['Manufacturer'] ?></option>
<?php
}
?>
<option> <a href='test.php'> + Add New</a></option>
</select>
</td>
</tr>
<tr>
<td>Vehicle Model <input id = "Model" value = '<?php echo $v['Model'];?>'/> </td>
</tr>
<tr>
<td> Model Year <input type = 'number' id = "modelYear" min='1990' max='2020' value = '<?php echo $v['Model_Year'];?>'/> </td>
</tr>
<tr>
<td> State of Vehicle <input id = "State" value = '<?php echo $v['State'];?>'/> </td>
</tr>
<tr>
<td> Color <input id = "Color" value = '<?php echo $v['Color'];?>'/> </td>
</tr>
<tr>
<td>
Vehicle Type
<select id = "Type" value = '<?php echo $v['Type'];?>'>
<?php
foreach($vehicleTypes as $vt)
{?>
<option value = '<?php echo $vt ?>'> <?php echo $vt ?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td> License plate No. (If there is one) <input type = 'number' id = "licensePlate" value = '<?php echo $v['License_Plate_N'];?>' /> </td>
</tr>
<tr>
<td> Sale Price <input type = 'number' id = "salePrice" value = '<?php echo $v['Sale_Price'];?>'/> </td>
</tr>
<tr>
<td> Rent Price <input type = 'number' id = "rentPrice" value = '<?php echo $v['Rent_Price'];?>'/> </td>
</tr>
<tr>
<td> Stock <input type = 'number' id = "Stock" value = '<?php echo $v['Stock'];?>' /> </td>
</tr>
<tr>
<td><p>Vehicle Description<textarea id="Description" rows="2" cols="18" > <?php echo $v['Description'];?> </textarea></p> </td>
</tr>
<tr>
<td>Vehicle Image <input id = "i" type = 'file' /> </td>
</tr>
<tr>
<td> Update </td>
</tr>
<?php
}
?>
</form>
</table>
<script>
function confirm_edit(){
if(confirm("Save changes?") === true){
var vehicleID = document.getElementById("vID");
var Manufacturer = document.getElementById("Manufacturer");
var Model = document.getElementById("Model");
var modelYear = document.getElementById("modelYear");
var State = document.getElementById("State");
var Color = document.getElementById("Color");
var Type = document.getElementById("Type");
var salePrice = document.getElementById("salePrice");
var rentPrice = document.getElementById("rentPrice");
var Stock = document.getElementById("Stock");
var i = document.getElementById("i");
var Description = document.getElementById("Description");
$.ajax({
url: 'ajax.php',
method: 'post',
data: {vehicleID : vehicleID, Manufacturer : Manufacturer},
success: function(response){
console.log(response);
}
});
}else{
return false;
}
}
</script>
This is just some code I wrote to test if it is working before I try updating the table in my database, but it is not printing the variable so I am assuming it is not working.
<?php
extract($_POST);
if(isset($Manufacturer))
{
echo $Manufacturer;
}
?>
If someone can show me my mistakes because I am still having trouble with AJAX because I am new to it. I want the user to confirm if he/she wants to save the changes then through AJAX update the table on my database.
You over-complicated your code and therefore it makes it much harder to understand and handle.
First of all, instead of declaring every form input by finding it's ID, you should just user jQuery's built in serialize() function, which will collect all of the form data and make a simpler string to work with.
$.ajax({
data: $('form').serialize(),
success: function(data){
console.log(data);
}
});
Also, do not use extract on user data (like $_POST or $_GET) since it is extremely insecure way to handle user data. Simply use:
<?php
if(isset($_POST['manufacturer']))
{
echo $manufacturer;
}
?>
Related
I'm asking this question again and hope I get the answer this time, I have an array of number that adds and subtract on button click which works withonclick and a function created. I will like the sum up of the array 21998 and 11999 when this same button is click and will like to display the value in <p id=""sumTotal></p> find screenshot of what my array looks like:
I have an onClick function that multiple quantity with total every time - and + are clicked. I will like the sum-up of 21,998 and 11,999 when - and + are clicked. Below is what my HTML code and PHP script look like:
<p id = "sumTotal"></p>
<table class="table table-cart table-mobile">
<thead>
<tr>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<? for($i=0;$i<count($_SESSION['img_src']);$i++){ ?>
<tr>
<td class="price-col" id="<? echo $_SESSION['id'][$i].'_price' ?>" >₦<?php echo $_SESSION['price'][$i] ?></td>
<td>
<div onclick="clickMe(<?php echo $_SESSION['id'][$i]; ?>)">
<input type="number" value="1" min="1" max="10" step="1" data-decimals="0" required id = "<? echo $_SESSION['id'][$i].'_quantityCount' ?>">
</div><!-- End .cart-product-quantity -->
</td>
<td id = "<? echo $_SESSION['id'][$i].'_totalPrice' ?>">₦<?php echo $_SESSION['price'][$i] ?></td>
</tr>
<?
}
?>
<tbody>
</table>
And my javascript onclick looks like below code:
<script>
function clickMe(id) {
var price = document.getElementById(id+"_price").innerHTML;
let finalPrice = price.replace(/[^a-zA-Z0-9]/g, '')
var quantity = document.getElementById(id+"_quantityCount").value;
var totalPrice = quantity * finalPrice;
document.getElementById(id+"_totalPrice").innerHTML = "\u20A6"+totalPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>
I will like to get the sum total of 21,998 and 11,999to <p id = "sumTotal"></p>
Call this function in the end of clickMe function.
function total() {
const priceElements = document.querySelectorAll('[id$="_totalPrice"]');
return [...priceElements].reduce((acc, curr) => acc + +curr.innerText, 0);
}
I was able to solve this myself, at first on the load of the page I sum up the all prices to get my initial sumTotal and did that in PHP with $subTotal_sum = array_sum( str_replace(",", "", $_SESSION['price']));. So <p id = "sumTotal"></p> will be <p id = "sumTotal">echo array_sum( str_replace(",", "", $_SESSION['price']));</p> And inside my javascript I made the changes with the script, I get the value of sumTotal subtracted it from Price and add the sumTotal and new price after + or - to get the new sumTotal below is my update code:
<p id = "sumTotal">$subTotal_sum = array_sum( str_replace(",", "", $_SESSION['price']));</p>
<table class="table table-cart table-mobile">
<thead>
<tr>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<? for($i=0;$i<count($_SESSION['img_src']);$i++){ ?>
<tr>
<td class="price-col" id="<? echo $_SESSION['id'][$i].'_price' ?>" >₦<?php echo $_SESSION['price'][$i] ?></td>
<td>
<div onclick="clickMe(<?php echo $_SESSION['id'][$i]; ?>)">
<input type="number" value="1" min="1" max="10" step="1" data-decimals="0" required id = "<? echo $_SESSION['id'][$i].'_quantityCount' ?>">
</div><!-- End .cart-product-quantity -->
</td>
<td id = "<? echo $_SESSION['id'][$i].'_totalPrice' ?>">₦<?php echo $_SESSION['price'][$i] ?></td>
</tr>
<?
}
?>
<tbody>
</table>
<script>
function clickMe(id) {
var sumTotal = document.getElementById("sumTotal").value;
var price = document.getElementById(id+"_price").innerHTML;
var initialSumTotal = parseInt(sumTotal) - parseInt(price);
let finalPrice = price.replace(/[^a-zA-Z0-9]/g, '')
var quantity = document.getElementById(id+"_quantityCount").value;
var totalPrice = quantity * finalPrice;
document.getElementById(id+"_totalPrice").innerHTML = "\u20A6"+totalPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
var sumTotal= parseInt(initialSumTotal)+parseInt(totalPrice);
// parsing the value to display on sub total
document.getElementById("sumTotal").value ="\u20A6"+sumTotal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>
I have a form and calculation formula. I need to get my result in inpute string.
my table
<table class="vel_sum_table" style="font-size: 9pt;">
<tr>
<td><?php echo __( 'In package м<sup>2</sup>:', 'wqc' ); ?></td>
<td> <span><?php echo number_format((get_post_meta($post->ID,"_calculatorscript_value",true)),2,",",""); ?> </span>
</td>
</tr>
<tr>
<td><?php echo __( 'Total:', 'wqc' ); ?></td>
<td><input type="text" value="" name="quantity2" id="quantity_product_input" disabled style="border: none;color: #000;font-weight: bold;"/>
</td>
</tr>
</table>
I need to get my result in quantity_product_input inpute. My script, I think, works. input[name=quantity] are on the page. It is product page woocommerce.
<script>
jQuery(document).ready(function($){
var pakket_variable = <?php echo $calculatorValue; ?>;
$('input[name=quantity]').on( 'input change', function(){
var productQty = $(this).val() == '' ? 1 : $(this).val();
meterM2 = (pakket_variable * productQty);
$('#quantity_product_input').val(meterM2);
}
}}
</script>
I am trying to run a form that stores an Id in a hidden input tag so that I can retrieve it in the next page using php. For some reason I can't retrieve the value using the php file. Echoing orderId.value and order number are working fine.
main_page.php
<script>
function EditValues(orderNumber) {
var orderId = document.getElementById("orderId");
orderId.value = orderNumber;
document.forms["form1"].submit();
}
</script>
<body>
<form action="edit-form.php" id="form1">
<div class="container">
<!--use the hidden input variable to save the order number clicked -->
<input id="orderId" type="hidden" name="orderId"/>
<?php
require("config.php");
$con = new mysqli(DB_Host, DB_User, DB_Password, DB_Name);
if ($con->connect_error) {
die("Connection failed");
}
echo '<table id="tblOrders" name ="OrderTable" style="width: 100%">
<tr>
<th>Sno</th>
<th>Order Number</th>
</tr>';
$displayTableDataQuery = "SELECT id, orderNumber, customerName, deliveryDate FROM orderTable";
if ($tableData = $con-> query($displayTableDataQuery)) {
while($row = $tableData-> fetch_assoc()) {
$id = $row['id'];
$orderNumber = $row["orderNumber"];
echo '<tr >
<td>'.$id.'</td>
<td id = "orderNumber">'.$orderNumber.'</td>
<td><input type = "button" id ="editButton'.$id.'" value = "Edit" onclick = "EditValues('.$orderNumber.');"/> </td>
<td><input type = "button" id = "printInvoice'.$id.'" value="Print" onclick = "PrintInvoice('.$orderNumber.');" /> </td>
</tr>';
}
} else {
echo $con->error;
}
$tableData->free();
?>
</div>
</form>
</body>
In edit-form.php
<?php
$xyzabc = $_POST['orderId'];
echo $xyzabc;
?>
There is nothing echoed for $xyzabc
I would prefer if there was some way to do this without jQuery as I'm kind of new to this and haven't really gotten a hang of how everything works together as of now.
You can store value directly to the hidden input field.
<!--use the hidden input variable to save the order number clicked -->
<input id="orderId" type="hidden" name="orderId" value="<?=$variable_name;?> />
So that when you submit the form
<?php
$xyzabc = $_POST['orderId'];
echo $xyzabc;
?>
will fetch the data.
Or you can pass the hidden value in url. For example
<a href="localhost:8000/edit-form.php?orderId="<?=$variable_name;?>
Then in you form-edit.php
<?php
$xyzabc = $_GET['orderId'];
echo $xyzabc;
?>
I'm currently building a form, and using a PHP loop to build the elements in a table which hold the values I'm submitting after clicking a checkbox.
<form id="saveLineup">
#foreach($lists as $list)
<tr style="text-align:center;">
<td id="groupNumber">{{$list['product']}} - {{$list['product_NAME']}}</td>
<td id="detailColor">{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}</td>
<td id="category">{{$list['CATEGORY']}}</td>
<td><input id="addToLineup"> type="checkbox" <?php if ($list['LINE_UP'] == 1) echo "checked='checked'"; ?>></td>
</tr>
#endforeach
</form>
My issue is, I have an id on the checkbox and id's on the values so I can only get the console log when I click the very first checkbox and it only logs the very first item. How can I change this so that I can submit with any checkbox in the table and it's associated values?
$("#addToLineup").click(function (e) {
var productNumber = document.getElementById("productNumber").innerHTML = productNumber;
var detailColor = document.getElementById("detailColor").innerHTML = detailColor;
var category = document.getElementById("category").innerHTML = category;
updatedata.productNumber = productNumber;
updatedata.detailColor = detailColor;
updatedata.category = category;
$.ajax({
url: "/test/addToLineup",
data: updatedata,
_token: phpVariables.csrfToken,
type: "POST",
beforeSend: function () {
showLoading(element);
},
success: function (data) {
location.reload();
},
});
});
Here is the solution to your problem, you need to use classes instead of IDs.
#foreach($lists as $list)
<tr style="text-align:center;">
<td class="groupNumber">{{$list['product']}} - {{$list['product_NAME']}}</td>
<td class="detailColor">{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}</td>
<td class="category">{{$list['CATEGORY']}}</td>
<td><input class="addToLineup"> type="checkbox" <?php if ($list['LINE_UP'] == 1) echo "checked='checked'"; ?>></td>
</tr>
#endforeach
Now, in your JS section, you can fetch them by their class:
var productNumber = document.getElementsByClassName("productNumber").innerHTML = productNumber;
var detailColor = document.getElementsByClassName("detailColor").innerHTML = detailColor;
var category = document.getElementsByClassName("category").innerHTML = category;
Note: If you're applying CSS styles to those elements via their ID, you can change #productNumber to .productNumber in your CSS or you can leave the ID tag with the same name as your previous code.
In PHP code
<form id="saveLineup">
<?php $i=0; ?>
#foreach($lists as $list)
<?php $i+=1; ?>
<tr style="text-align:center;">
<td id="groupNumber<?php echo $i ?>">.
{{$list['product']}} - {{$list['product_NAME']}}
</td>
<td id="detailColor<?php echo $i ?>">.
{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}.
</td>
<td id="category<?php echo $i ?>">.
{{$list['CATEGORY']}}
</td>
<td>
<input id="addToLineup<?php echo $i ?>"> type="checkbox" <?php if ($list['LINE_UP'] == 1) echo
"checked='checked'"; ?>>
</td>
</tr>
#endforeach
<input id="listcount"> type="hidden" value="<?php echo $i; ?>" >
</form>
Js function
$("#addToLineup").click(function (e) {
for(var i=1 ; i <= parseInt(document.getElementById("listcount").value); i++) {
Console.log(document.getElementById("productNumber"+i).innerHTML);
Console.log(document.getElementById("detailColor"+i).innerHTML);
Console.log(document.getElementById("category"+i).innerHTML);
}
});
I have to generate some text boxes after each line of row sent from database, so I have this user who have 2 rows:
And of course each row belongs to an id:
<td><?php echo $counter--; ?></td>
<td><?php echo $installment['date_now'] ?></td>
<td><?php echo $installment['payment'] ?> $</td></tr>
</tr>
<?php } ?>
<tr><th colspan="10" style="text-align: right;">Remaining:</th>
<th><?php echo ($cash['project_cost'] - $sum) ?> $</th>
</tr>
<tr id="<?php echo $cash['infoid']; ?>"><td colspan="8" style="text-align: right;">Add Payment</td>
<td><input type="date" class="form-control" id="date_pay_now[]"/></td>
<td><input class="form-control" type="text" id="pay_now"/></td>
<td><button id="add_payment" class="btn btn-success glyphicon glyphicon-plus"></button>
</tr>
<tr><td></td></tr><tr><td></td></tr>
<?php $sumCash = $sumCash + $cash['project_cost']; } ?>
<tr>
<th colspan="10">Cash Total</th><th id="final_cash"><?php echo $sumCash ?> $</th>
</tr>
</table>
</div>
<?php } else { ?>
No Payments available
<?php } ?>
Now, when select a date and type an amount, I should send those values into AJAX and but first I need to get the id of the row so I can send it too.
$("#add_payment").click(function()
{
var date_of_pay = $("#date_pay_now").val();
var pay_now = $("#pay_now").val();
var id_pay = $(this).closest('tr').attr('id');
console.log(id_pay);
if(date_of_pay == "" || pay_now == "")
{
$("#date_pay_now").css('border-color', 'red');
$("#pay_now").css('border-color', 'red');
}
if(date_of_pay != "" && pay_now != "")
{
$.ajax
({
//Still not typed
});
}
});
If you see the image, when I click on the first button, I see the id correctly at the console and if they are empty I can see the red color, but when I refresh the page and click directly on the second row button, I can't see any value at the console and no css color due to empty text box shown.
And here when I click on the next button, no color and no id at the console: