Sending multiple form datePicker data to the same destinations - javascript

I'm having issues with creating multiple unique datepicker instances within one div and then submitting the dates in a form.
My issue is that my div currently has multiple array elements building this form:
<?php foreach($expiredPages as $expiredPage): ?>
<form id="updateTime_<?php echo $expiredPage['id']?>" class="updateTime" method="POST">
<input type="hidden" name="currentPageID" value="<?php echo $expiredPage['id']?>">
<div class="datepick input-group date" id="datetimepicker_<?php echo $expiredPage['id']?>" data-target-input="nearest">
<input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker_<?php echo $expiredPage['id']?>" name="datePicker<?php echo $expiredPage['id']?>" />
<span class="input-group-addon" data-target="#datetimepicker_<?php echo $expiredPage['id']?>" data-toggle="datetimepicker">
<span class="fa fa-calendar"></span>
</span>
<input type="submit" name="Extend Date" class="extendDate">
</form>
<?php endforeach; ?>
WHich means I have 3 forms in the div, each with its own datepicker and submit button. I've fixed this to make sure each datepicker works independently, but I can't figure out how to uniquely pass my two inputs to the PHP.
I'm getting errors of undefined index for both currentPageID and datePicker
The JS:
<script type="text/javascript">
$(".extendDate").click(function(){
event.preventDefault();
var string = $('.updateTime').serialize();
console.log(string);
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "extendTime.php",
data: string,
dataType: 'json',
cache: false,
success: function(response){
location.reload();
}
});
});
</script>
extendTime.php
$pageID = $_POST['currentPageID'];
$dtPick = 'datePicker' . $pageID;
$newTime = $_POST[$dtPick];
$newEndTime = DateTime::createFromFormat('m/d/Y h:i A', $newTime);
$convertedDateTime = $newEndTime->format('Y-m-d H:i:s');
$extendExpiration = "
UPDATE pages
SET end_time = '$convertedDateTime'
WHERE id = '$pageID';
";
if($mysqlConn->query($extendExpiration)=== TRUE){
echo "SUCCESS";
}else{
echo "Could not extend Time";
}

Regarding your php, you don't have post key called datePicker...
$_POST['datePicker'];
doesn't exists...
you add to your input's name an id:
<input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker_<?php echo $expiredPage['id']?>" name="datePicker<?php echo $expiredPage['id']?>" />
A simple fix should be something like this :
$dtpick = 'datePicker' . $pageID;
$newTime = $_POST[$dtpick];

Related

PHP / SQL: Multiple delete data using Select Option

Now I create a system that can delete multiple data using select option. But here I got some issues. When i only select one data, and press button delete, it will delete. But if I choose more than one data, for example, 3 data, it will only delete the latest id of the data. Below is my the image
And below is my code:
index.php
<form method="post" id="multiple_select_form">
<select name="framework" id="framework" class="form-control selectpicker" data-live-search="true" multiple>
<?php foreach ($results as $row2): ?>
<option value= <?php echo $row2["framework_id"]; ?>><?php echo $row2["framework_name"];?></option>
<?php endforeach ?>
</select>
<br /><br />
<input type="hidden" name="framework_id" id="framework_id" />
<input type="submit" name="submit" class="btn btn-info" value="Submit" />
</form>
<script>
$(document).ready(function(){
$('.selectpicker').selectpicker();
$('#framework').change(function(){
$('#framework_id').val($('#framework').val());
});
$('#multiple_select_form').on('submit', function(event){
event.preventDefault();
if($('#framework').val() != '')
{
var form_data = $(this).serialize();
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
//console.log(data);
$('#framework_id').val('');
$('.selectpicker').selectpicker('val', '');
alert(data);
}
})
}
else
{
alert("Please select framework");
return false;
}
});
});
</script>
insert.php
<?php
include("configPDO.php");
$smt = $conn->prepare("DELETE FROM frame_list WHERE framework_id = '".$_POST["framework_id"]."'");
$smt->execute();
if($smt){
echo "Data DELETED";
}else{
echo "Error";
}
?>
Can anyone knows how to solve this problem? Thanks
framework will hold one value every time.
Use input arrays -
Change name="framework" to name="framework[]".
and in query -
WHERE framework_id in ('". implode("','", $_POST["framework_id"]) ."')"
Try to use parameter binding for security.

Unable to set PHP variables as values for input field in form

I have a PHP file which SELECT's all from the row found based on an SQL query. When I put the echo in a div, I get all information, but when I try to echo it into an input box in a form, it does not shows.
What am I doing wrong?
Please also note that I am aware that I am (most likely) making a lot of mistakes when it comes to security practices or programming standards, but this whole thing (PHPDesktop > https://github.com/cztomczak/phpdesktop) will get packed into an EXE file which will run locally only (no need for an online connection as the SQLite3 DB gets packed in with the EXE), and I am still figuring out how to program this in the first place, so efficient and tidy coding are not high on my list yet ;-)
DO_CUSTEDIT.PHP
$custName = $_POST['custName'];
$query = "SELECT * FROM `CustDB` WHERE CustName LIKE '%$custName%'";
$result = $db->query($query);
while ($row = $result->fetchArray()) {
$custID = $row['CustID'];
......;
}
if (!$result) {
echo $db->lastErrorMsg();
$db->close();
exit;
} else {
echo $custID;
echo ......;
$db->close();
exit;
}
EDITCUST.PHP / Javascipt
<script>
$(document).ready(function() {
$("#subeditcust").on('click',function(e) {
e.preventDefault();
$.ajax( {
url: "lib/do_editcust.php",
method: "post",
data: $("form").serialize(),
dataType: "text",
success: function(strMessage) {
if (strMessage == "Customer updated successfully") {
$("#message").text(strMessage);
$("#neweditform").get(0).reset();
} else {
$("#message").text(strMessage);
}
}
});
});
});
</script>
EDITCUST.PHP / HTML
<form id="editcustform" name="editcustform" action="" method="post">
<div class="row">
<div class="column-half" style="background-color:#fff">
<table>
<tr>
<td>
<a>Customer ID</a>
</td>
<td>
<div class="inputb">
<input type="text" name="custID" value="<?php echo (isset($custID)) ? $custID: ''; ?>" readonly/>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<table style="table-layout:fixed">
<td style="background-color: rgb(215,215,215); padding:0 10px;">
<button id="subeditcust" type="submit" class="mainbtn">Create</button>
</td>
<td style="background-color: rgb(215,215,215); padding:0 10px;">
<button id="reseteditcust" type="reset" class="mainbtn">Reset</button>
</td>
</table>
</div>
</form>
<input type="text" name="custID" value="<?php echo (isset($custID) ? $custID: ''); ?>" readonly/>
Replace this line with yours it will work. IA
It seems you have two different files, right? DO_CUSTEDIT.PHP and EDITCUST.PHP
The variables are being created on DO_CUSTEDIT.PHP and the when you are creating the HTML code those variables ($custID) are not setted.
Is one file including or requiring the other?
EDITCUST.PHP is your first page from you are submitting form to DO_CUSTEDIT.PHP
When you land on EDITCUST.PHP variable $custID is not created
When the form is submitted through ajax, the ajax returns the data inform of object or array depending on how you are echoing the data from DO_CUSTEDIT.PHP
I would recommend to use json_encode() php function to return inform of array
To debug the value by logging the data in console (though function console.log())
After returning the value from ajax, you have to populate the value in form through jquery something like $(input[name="custID"]).val( data.custID )
I managed to figure it out!
DO_CUSTEDIT.php / PHP
$results = array($custID, $custName);
echo json_encode($results, JSON_PRETTY_PRINT);
EDITCUST.php / HTML
<input type="text" id="custID" name="custID" value="" readonly/>
<input type="text" id="custName" name="custName" value="" readonly/>
EDITCUST.php / JS
<script>
$(document).ready(function() {
$("#subeditcust").on('click',function(e) {
e.preventDefault();
$.ajax( {
url: "lib/do_editcust.php",
method: "post",
data: $("form").serialize(),
dataType: 'json',
success: function(data){
document.getElementById('custID').value = data[0];
document.getElementById('custName').value = data[1];
}
});
});
});
</script>

Ajax to insert multiple records from form inputs, add counter to hidden input

I've created a page that, based on an array from the database, creates multiple forms. Each form has an input with an 'add' button which dynamically adds new inputs (up to 10 inputs per form)
This works fine, but now I'm getting to where I want to submit andy input values added into the database. I have 2 main issues here:
The hidden input in my form <input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>"> has a non unique ID, so no matter which form I submit from, it has the ticker value belonging to the first form only.
Once I have that value, and serialize with any filled inputs in that form, I call addticker.php to insert. I'm inserting the ticker id and the content from the form inputs, but I need to do this as a foreach I believe, because if 5 inputs were added and filled in, I need a record for each. All 5 would have the same ticker ID and the respective content from the input.
Any help is appreciated
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<?php endforeach;?>
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $('#tickerID').val();
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
<script type="text/javascript">
$("#Items").submit(function(e) {
//variables?
//var tickerID coming from <input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
//var Items[]
$.ajax({
type: "POST",
url: addticker.php,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
addticker.php
$tickerID = $_POST[''];
$content = $_POST[''];
$addTicker = "
INSERT INTO tickerTable (tickerID, content)
values ('$tickerID', '$content');
"
$mysqlConn->query($addTicker)

Filling form with Jquery click function

I'm trying to create a GUI to let the user edit any row that is displayed in my table. I've manage to create a form that pops up when the user clicks an image which symbolize an edit icon. Now I like to use Jquery (if possible) to fill this form with data from my DB. The error code is down bellow and I can't seem to get any results at all
Script
<script type="text/javascript">
$(document).ready(function(){
$('#edit').click(function() {
$.ajax({
url: 'edit.php?itemid=$itemid',
success: function(response) {
$('#itemid').val($itemid);
......
$('#status').val($status);
}
});
});
});
</script>
Edit.php
<?php
$DB = new mysqli("localhost", "root", "", "book1");
$result2 = mysqli_query($DB, "SELECT * FROM booking WHERE itemID='$itemid'");
while($row = mysqli_fetch_array($result2)){
$itemid = $row['itemID'];
......
$status = $row['status'];
}
echo (array($itemid, $userid, $description, $manufacturer, $model, $caldate, $duedate, $shelf, $status);
?>
Form
<div id="light1" class="white_content">
<form id="editform" name="myForm" action="checkout.php" method="POST">
<h2>Edit Instrument</h2>
<label>ItemID:</label>
<input type="text" id="itemid"/>
<br>
......
<a>Status: </a>
<input type="text" id="status"/>
<br>
<input type="submit" value="Accept">
<input href = "javascript:void(1)" onclick = "document.getElementById('light1').style.display='none';document.getElementById('fade').style.display='none'" type="reset" value="Close">
<br>
</form>
</div>
Error
ReferenceError: $itemid is not defined
$('#itemid').val($itemid);
change
$('#itemid').val($itemid);
to
$('#itemid').val('<?php echo $itemid; ?>');

Multiple forms in while loop with ajax

I have a product page whos products are created dynamically from mysql along with "add to cart" buttons and quantity inputs on each item. These items are submitted via AJAX. I'm able to submit the correct product but the success message returned from ajax uses a hidden div which hides the add to cart button then displays text that your item in now in the cart. It hides ALL of the cart button and shows the hidden div containing the success message in every form. Any help to solve this is appreciated!
My PHP/HTML
//inside while loop
?>
<div class="form">
<form action="cart_action.php" method="post" name="form" id="form_<?php echo $item_no; ?>">
<input type="hidden" class="text" name="order_code" value="<?php echo $item_no; ?>" id="order_code<?php echo $item_no; ?>" />
<input type="hidden" class="text" name="minorder" value="<?php echo $min; ?>" id="min_<?php echo $item_no; ?>" />
<br><br><div style="float:left; padding:5px;"><b>Qty</b>: <input class="text" type="text" name="quantity" value="<?php echo $min; ?>" size="3" id="quan_<?php echo $item_no; ?>" ?></div>
<div id="status"></div>
<input type="image" src="images/add_to_cart.png" class="psubmit" alt="submit" name="submit" id="submit_<?php echo $item_no; ?>" />
</div><div class="added"><b><div style="color: rgb(85, 176, 90);"><br /><b>Added to Cart </b>(View Cart)</div></b></div>
</form>
<?php
} //end loop
JAVASCRIPT:
$(document).ready(function() {
$('form').submit(function(){
// Catching the DOM element which trigger the event
var $form = $(this);
var orderCode = $form.find('input[name=order_code]');
var quantity = $form.find('input[name=quantity]');
var minOrder = $form.find('input[name=minorder]');
if (quantity.val() == '') {
quantity.addClass('hightlight');
$form.find("#status").html('<font color="red">Please Enter A Quantity!</font>');
return false;
} else quantity.removeClass('hightlight');
if (quantity.val() % minOrder.val()) {
quantity.addClass('hightlight');
$form.find("#status").html('<font color="red">Invalid Multiple!</font>');
return false;
} else quantity.removeClass('hightlight');
//organize the data properly
var data = 'order_code=' + orderCode.val() + '&quantity=' + quantity.val();
//disabled all the text fields
//$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "cart_action.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.added').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.added').fadeIn('slow');
}
});
//cancel the submit button default behaviours
return false;
e.preventDefault();
});
});
In your success handler, change the selectors to start from $form:
$form.fadeOut('slow');
$form.children('.added').fadeIn('slow');

Categories