post image, selected values to php via Javascript - javascript

Hello as part of my website project I am writing an item input form, the website itself is very simple, the user will:
Write item name
Select some values
Write item description in textarea
Upload item image
the page will collect this info using JS and then sent to PHP page where it will be checked and then inserted into database. I am not sure what is wrong with the code --php page gives no errors-- as it is not responding after submission, tried resolving by process of elimination, deleting the image part in JS seems to make the button respond though no output is given.
<!DOCTYPE HTML>
<html>
<header>
<title> Results </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</header>
<body>
<form method="post" enctype="multipart/form-data">
<fieldset>
<legend>Add item form.. </legend>
<p> fill out the below details </p>
<p> Item name will be publicly viewed by users: <input type="text" id="itemID" name="itemName" placeholder="Enter item name.." /> </p>
location:
<select id="locSelect"> //4 options for every select
<option id="mountainID" value="mountain"> Mountain </option>
</select>
Category:
<select id="catSelect">
<option id="appliancesID" value="appliances"> Appliances </option>
</select>
Price range:
<select id="rangeSelect">
<option id="range1ID" value="range1"> 0-$50 </option>
</select>
<p> <input type="textarea" id="descriptionID" name="descriptionName" style="height:185px;width:400px;" placeholder="Please enter any item relevant info in this area..." /> </p>
<p> Upload Image: <input type="file" id="itemImageID" name="itemImage" /> </p>
<p> <input type="button" id="addID" name="add" value="Add item" onClick="runAdd();" /> </p>
</fieldset>
</form>
<div id="addResult"></div>
<script type="text/javascript">
function runAdd()
{
var item = $("#itemID").val();
var location = document.getElementById("locSelect"); //id of select
var selectedLoc = location.options[location.selectedIndex].text;
var category = document.getElementById("catSelect");
var selectedCat = category.options[category.selectedIndex].text;
var range = document.getElementById("rangeSelect");
var selectedRange = range.options[range.selectedIndex].text;
var textArea = document.getElementById("descriptionID").value;
var itemImg = document.getElementById("itemImageID");
$.post("itemDatabase.php", {
itemDB: item,
locationDB: selectedLoc,
categoryDB: selectedCat,
rangeDB: selectedRange,
textareaDB: textArea,
itemImgDB: itemImg },
function(data)
{
if(data == "int echoed by php page"){
$("#addResult").html("item/text is blank..");
//php will echo back to addResult <div> if input is not set
}
}
);
}
</script>
</body>
</html>
I believe I am sending the textarea, select and image parts wrongly, as php echos nothing for them when they are empty. I looked up codes online though they were separate from my case usually involving AJAX or PHP exclusively.
<?php
session_start(); //for userID, different page stores it
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("project_database");
if (isset($_POST['add'])){
if(empty(trim($_POST['itemDB']))) { // if(!($_POST['itemDB'])) not working
echo "0"; }
else { $item = mysql_real_escape_string($_POST['itemDB']); }
if(isset($_POST['locationDB'])){
$location = $_POST['locationDB'];
} else {
echo "1"; }
if(isset($_POST['categoryDB'])){
$category = $_POST['categoryDB'];
} else {
echo "2"; }
if(isset($_POST['rangeDB'])){
$range = $_POST['rangeDB'];
} else {
echo "3"; }
if(empty(trim($_POST['textareaDB']))) {
echo "4"; }
else { $description = mysql_real_escape_string($_POST['textareaDB']); }
if(getimagesize($_FILES['itemImgDB']['tmp_name']) == FALSE)
{
echo "5";
}
else
{
$image = addslashes($_FILES['itemImgDB']['tmp_name']);
$image = file_get_contents($image);
$image = base64_encode($image);
}
$query = "INSERT INTO item (item_name, item_description, item_price_range, item_img, item_location, user_id, category_id) VALUES ('".$item."', '".$description."', '".$range."', '".$image."', '".$location."', '".$_SESSION["userID"]."', '".$category."')";
$itemAdded = mysql_query($query);
if($itemAdded) {
echo " Item " .$item. " has been added successfully "; }
else { echo " something went wrong "; }
}
?>
category_Id and user_id are foreign keys,
Image is stored as BLOB in database (checked code working on different page)
I understand some functions are deprecated, but this is how I was instructed to complete my task, I am using notepad.
I have posted most of the code to ensure I understand what is wrong or how I can improve it in the future, I appreciate any pointers or tips just to get me on the right path at least so I can fix this.
Thank you again for any help in advance.

To answer your question about uploading images via AJAX, this was not possible before but it is now possible via FormData objects (but it is a relatively new feature and is not compatible with older browsers, if that matters to you).
You might either want to upload the image separately (old fashioned), or I suggest you look into using FormData.
This link below should be helpful (I hope):
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
Hope this helps :)

Related

jQuery combine input checkbox, dates and text values into one value string based on name

I am using the following php & jquery to process a simple product form within WordPress Admin which works fine for the input checkboxes. However, I am trying to combine a mix of both checkboxes AND text input fields as well as a date field into the one servicelist[] value.
let values = [];
$("input[name='servicelist[]']:checked").each(function() {
values.push($(this).val());
});
Normally I would use something like servicestartdate: $("#servicestartdate").val(), however I need this to pull through with the servicelist[] value as the results will loop for however many products are selected. The values are then imploded in the email template.
My attempts are not working as I'm not experienced with jQuery and not sure how I can include text inputs with the code below. I have tried removing the :checked as well as replacing with :val yet this breaks the jQuery. I have also tried creating an additional value which also breaks the code.
Hope this makes sense. Any suggestions would be very helpful! Thanks.
Here is the full php, jquery and email code...
Form PHP & JQUERY: (Note: Make sure your path to email.php is correct)
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function sendSupplierForm() {
let values = [];
$("input[name='servicelist[]']:checked").each(function() {
values.push($(this).val());
});
var data = {
ordernumber: $("#ordernumber").val(),
servicelist: values
};
jQuery.ajax({
url: "email.php",
data: data,
dataType:'text',
type: "POST",
success:function(data){
$("#EmailStatus").html(data);
},
error:function (){}
});
}
</script>
<div id="SupplierForm">
<div id="EmailStatus"></div>
<label><input type="text" name="ordernumber" id="ordernumber" value="1234567890">ID</label><br>
<label><input class="list" type="checkbox" name="servicelist[]" id="servicelist1" value="Service1">Service1</label><br>
<label><input class="list" type="checkbox" name="servicelist[]" id="servicelist2" value="Service2">Service2</label><br>
<label><input class="list" type="checkbox" name="servicelist[]" id="servicelist3" value="Service3">Service3</label><br>
<label>Date: <input type="date" name="servicelist[]" id="servicestartdate"></label>
<label>Price: <input type="text" name="servicelist[]" id="supplierpriceperlift" value="£16.75"></label>
<div name="submit" class="btnAction" onClick="sendSupplierForm();">Send</div>
</div>
email.php (Note: Make sure you change the email addresses for it to work)
<?php
$mailto = "info#******.com";
$subject = "Test";
$headers = "From: info#******.com\nMIME-Version: 1.0\nContent-Type: text/html; charset=utf-8\n";
$seperate = implode("<br>",$_POST['servicelist']);
$message = "
<html>
<head>
<title>Supplier Form Details</title>
</head>
<body>
<p>Original Order Number: " . $_POST['ordernumber'] . "</p>
<p>Service List: <br>" . $seperate . "</p>
</body>
</html>
";
$result1 = mail($mailto, $subject, $message, $headers);
if ($result1) {
print "<p class='success'>SUCCESS!!! The details have been sent.</p>";
} else {
print "<p class='Error'>ERROR... Sorry there is a problem sending the details.</p>";
}
?>
Try this
let values = [];
$("input[name='servicelist[]']:checked, #servicestartdate, #servicestartdate").each(function() {
values.push($(this).val());
});
Here I am basically selecting elements with multiple selectors..
input[name='servicelist[]']:checked
#servicestartdate
#servicestartdate
and jQuery will return the full collection, which then you can iterate.

Use AJAX to run PHP script and then return single value

Okay, this question was closed for not being clear enough, so I'm going to completely re-write it in as clear a form as I can...
Project: Room Booking System
Required Function: Check the database for existing bookings matching a criteria, return the result of 'COUNT' SQL query to a textbox which another function then looks to.
The values which need to be inserted into the COUNT criteria are as follows:
<h4>Date:</h4>
<input required type="text" name = "datebox" id = "datebox" ><br/>
<h4>Timeslot:</h4>
<input required type="text" name = "timebox" id = "timebox" ><br/>
<h4>Location:</h4>
<input required type="text" name = "roombox" id = "roombox" ><br/>
<h4>Person:</h4>
<input required type="text" name = "bookerbox" id = "bookerbox" ><br/>
</br>
Problem: I have a functioning php script which counts the number of rows in the database matching a criteria, which will then return the result to a textbox (main function sorted) when set up in a test directory with nothing else on the page. However, when I embed this php into an existing page (the new booking page) it doesn't work when the 'Check Availability' button is clicked. Instead, it reloads the page (as php does) which is not useful when users have already input their data for checking (and would need to re-enter it). I've Googled and have found that I need to use AJAX to run the php function in the background and then return the result to the textbox on the current page. I have never ever used AJAX and are only new to php, js etc. as it is, so I have no idea what I'm doing
How can you help: I need help in converting my existing code into a working solution to the above problem, probably using a combination of AJAX, PHP and JS functions.
Code:
PHP COUNT CODE (works)
<?php
if(isset($_POST['info'])) {
$con = mysqli_connect("x", "x", "x", "x");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT COUNT(*) FROM `Existing_Bookings` WHERE Date = '2019-12-30' AND Time = 'Period 6' AND Room = 'C3'";
if ($result=mysqli_query($con,$sql)) {
// Return the number of rows in result set
$rowcount = mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
echo $rowcount; // echo the data you want to send over ajax
}
?>
Area of php/html in which the result should be returned (id="availresult")
<h2>Check availability</h2>
<h4>Click the button below to check whether your options are available:</h4>
<h4>This will only check against other bookings. It is your responsibility to use the timetable above to check whether the room is actually free.</h4>
<button onclick="soflow()" id="checkAvail" >Check Availability</button>
<input onclick="unhideReview()" type="button" id="continue" value="Continue" disabled />
<input type="text" style="width: 30px;" id="availresult" value="1" />
Test AJAX function, as suggested by an existing reply to my post
<script>
function soflow() {
$.post('checkAvailability.php', {info: 'start'}, function(data) { //if you don't need to send any data to the php file then you can set the value to whatever you want
document.getElementById('availResult').innerHTML = data;
});
}
</script>
I have tried various ways to do this myself, including modifying the suggested AJAX code above, but I'm not sure how to get my values from my various textbox over to the PHP function. Also, I don't know how to tell whether the AJAX function is running, or whether there is an error somewhere. At present, the value shown in my 'availresult' textbox does not change.
I appreciate any help with this, and thank anyone who has tried to help so far. I'm not sure how much clearer I can make this - please don't close the question again.
UPDATE:
(index.php):
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h4>Date:</h4>
<input required type="text" name = "datebox" id = "datebox" ><br/>
<h4>Timeslot:</h4>
<input required type="text" name = "timebox" id = "timebox" ><br/>
<h4>Location:</h4>
<input required type="text" name = "roombox" id = "roombox" ><br/>
<h4>Person:</h4>
<input required type="text" name = "bookerbox" id = "bookerbox" ><br/>
<br/>
<h2>Check availability</h2>
<h4>Click the button below to check whether your options are available:</h4>
<h4>This will only check against other bookings. It is your responsibility to use the timetable above to check whether the room is actually free.</h4>
<button onclick="soflow()" id="checkAvail" >Check Availability</button>
<input onclick="unhideReview()" type="button" id="continue" value="Continue" disabled />
<input type="text" style="width: 30px;" id="availresult" value="1" />
<script>
function soflow() {
var var_date = $('#datebox').val();
var var_time = $('#timebox').val();
var var_room = $('#roombox').val();
$.post('checkAvailability.php', {info: 'start', date: var_date, time: var_time, room: var_room}, function(data) {
document.getElementById('availResult').innerHTML = data;
});
}
</script>
</body>
</html>
(test.php):
<?php
if(isset($_POST['info'])) {
$con = mysqli_connect("x", "x", "x", "x");
if (mysqli_connect_errno()) { // Check connection
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = mysqli_real_escape_string($con, $_POST['date']);
$time = mysqli_real_escape_string($con, $_POST['time']);
$room = mysqli_real_escape_string($con, $_POST['room']);
$sql="SELECT COUNT(*) FROM `Existing_Bookings` WHERE Date = '$date' AND Time = '$time' AND Room = '$room'";
if ($result=mysqli_query($con,$sql)) {
// Return the number of rows in result set
$rowcount = mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
echo $rowcount; // echo the data you want to send over ajax
}
?>
You could also do ajax with pure JavaScript, but this is simpler.
Also note that this is just an example on how to do an ajax connection in the first place.

Output Data From MYSQL Table Into HTML Form Depending On User Choice

I have a MYSQL table (roomcost) that holds the costs of hiring rooms.
costID Room Cost
1 room1 15
2 room2 30
3 room3 50
rsRoomCost SQL is: SELECT * FROM roomcost
The HTML form has checkboxes that allow the hirer to make the choice of Room 1, Room 2 or Room 3. The hirer can hire one, any two or all three rooms.
<input type="checkbox" name="room1" value="room1" onClick="Check()">Room 1</div>
<input type="checkbox" name="room2" value="room2" onClick="Check()">Room 2</div>
<input type="checkbox" name="room3" value="room3" onClick="Check()">Room 3</div>
The form also has an input box (that will be hidden, once I get it working) for each room that will be filled with the appropriate cost from the table. When the form is submitted, the hirers record would hold the choice of room(s) and cost paid by that hirer at the time of hiring.
The JS script that checks if a particular checkbox is selected and would output the cost to the relevant input box.
function Check() {
if (document.forms["bookform"].room1.checked) {
document.forms["bookform"].thisRoom1.value = "<?php echo($row_rsRoomCost['room1']; ?>";
} else if (document.forms["bookform"].room2.checked) {
document.forms["bookform"].thisRoom2.value = "<?php echo($row_rsRoomCost['room2']; ?>";
} else if (document.forms["bookform"].room3.checked) {
document.forms["bookform"].thisRoom3.value = "<?php echo($row_rsRoomCost['room3']; ?>";
}
}
The input boxes for the output are:
Room 1: <input type="text" name="thisRoom1" value="">
Room 2: <input type="text" name="thisRoom2" value="">
Room 3: <input type="text" name="thisRoom3" value="">
As you see, I'm trying to use php to fill in the relevant value from the database table. However, this, of course, only shows the cost from the first record in the costs table regardless of which room is checked.
How do I get the cost of the chosen room from the table into the correct input box on the form?
I've tried <?php echo($row_rsRoomCost['room1']) where ($row_rsRoomCost['costID']) = '1'; ?> but this doesn't work. I thought about 'case' statements but don't know how that would work. The only way I can think of is a seperate SQL statement for each room. eg: SELECT * FROM roomcost WHERE costID = 1
How do I get the cost of the selected room from the table into the correct input box on the form?
Going through your code I find that that would be the long way round of solving it .
The first step to solving it would be to put your data into a reusable front End source like JSON (it easier to work with ).
Example: (Results are in the console log F12)
<?php
$servername = "localhost";
$username = "root";
$password = "jono23";
$dbname = "helpothers";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `roomcost`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// echo "id: " . $row["costID"]. " - Name: " . $row["room"]. " " .$row["cost"]. "<br>";
// data you want to send to json
$data[] = array(
'id' => $row['costID'],
'room' => $row['room'],
'cost' => $row['cost']
);
//}
}
} else {
echo "0 results";
}
$conn->close();
$json_data = json_encode($data);
//print_r($json_data);
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form id='bookform' >
<input type="checkbox" name="room1" value="room1" onClick="Check()">Room 1</input>
<input type="text" name="room1value" readonly><br>
<input type="checkbox" name="room2" value="room2" onClick="Check()">Room 2</input>
<input type="text" name="room2value" readonly><br>
<input type="checkbox" name="room3" value="room3" onClick="Check()">Room 3</input>
<input type="text" name="room3value" readonly><br>
</form >
<script type="text/javascript">
var Rooms = JSON.parse('<?php print_r($json_data) ; ?>');
console.log(Rooms);
function Check() {
//room1
if (document.forms["bookform"].room1.checked)
{
document.forms["bookform"].room1value.value = Rooms[0].cost;
console.log(Rooms[0].cost);
}else{
document.forms["bookform"].room1value.value ='';
}
//room2
if (document.forms["bookform"].room2.checked)
{
document.forms["bookform"].room2value.value = Rooms[1].cost;
console.log(Rooms[1].cost);
}else{
document.forms["bookform"].room2value.value ='';
}
//room3
if (document.forms["bookform"].room3.checked)
{
document.forms["bookform"].room3value.value = Rooms[2].cost;
console.log(Rooms[2].cost);
}else{
document.forms["bookform"].room3value.value ='';
}
}
</script>
</body>
</html>
By encoding the SQL query results into a json array first you able to
close the database connection so not to use up unnecessary resources
on multiple requests
Then By calling that PHP JSON Object into JavaScript you can more easily apply it to your html and JavaScript Needs
Converting PHP Data To JSON and parse with JavaScript Help us work with things like rest api's
This is the main reason why JSON implementation can be found in many languages as its an easy way to share data across different coding languages
Another suggestion that I would make for the handling of the data is not to store the values in a checkboxes . Create another text input for that purpose and store them there . e.g
<input type='text' id='gethandle1'>
<script>
let box1 = document.getElementById('gethandle1');
box1.value = Rooms[0].cost;
</script>
I hope this helps you .

Automatically update another page without refreshing

I have this problem on how I could automatically update my webpage without refreshing. Could someone suggest and explain to me what would be the best way to solve my problem? Thanks in advance
add.php file
In this php file, I will just ask for the name of the user.
<form id="form1" name="form1" method="post" action="save.php">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
save.php In this file, I will just save the value into the database.
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
$sql->execute();
studentlist.php In this file, i want to display the name I enter
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
Problem
When the two pages is open, I need to refresh the studentlist.php before i can see the recently added data.
thanks :D
You'll want to use ajax and jquery. Something like this should work:
add.php
add to the head of the document:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){//loads the information when the page loads
var saveThenLoad = {
url: "save.php",//the file sending data to
type: 'POST',//sends the form data in a post to save.php
dataType: 'json',
success : function(j) {
if(j.error = 0){
$("#student_info").html(j.info);//this will update the div below with the returned information
} else {
$("#student_info").html(j.msg);//this will update the div below with the returned information
}
}
}
//grabs the save.submit call and sends to the ajaxSubmit saveThenLoad variable
$("#save").submit(function() {
$(this).ajaxSubmit(saveThenLoad);
return false;
});
//grabs the submit event from the form and tells it where to go. In this case it sends to #save.submit above to call the ajaxSubmit function
$("#add").click(function() {
$("#save").submit();
});
});
</script>
<!-- put this in the body of the page. It will wait for the jquery call to fill the data-->
<div id="student_info">
</div>
I would combine save and studentlist into one file like this:
$return['error']=0;
$return['msg']='';
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error saving data';
}
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error retrieving data';
}
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
$return['$output'];
echo json_encode($return);
Does this need to be in three separate files? At the very least, could you combine add.php and studentlist.php? If so, then jQuery is probably the way to go. You might also want to use some html tags that would make it easier to dynamically add elements to the DOM.
Here's the combined files:
<form id="form1" name="form1">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
The List of students <br></br>
<ul id="student-list">
<?php
//I assume you're connecting to the db somehow here
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
while($result=$sql->fetch(PDO::FETCH_NUM)) //this might be easier to output than an associative array
{
//Returns will make your page easier to debug
print "<li>" . implode(" ", $result) . "</li>\n";
}
?>
</ul>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
$('#form1').submit(function(event){
event.preventDefault();
//submit the form values
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
//post them
$.post( "test.php", { firstname: firstname, lastname: lastname })
.done( function(data) {
//add those values to the end of the list you printed above
$("<li>" + firstname + ' ' + lastname + "</li>").appendTo('#student-list');
});
});
});
</script>
You might want to do some testing in in the $.post call above to make sure it was handled properly. Read more about that in the docs.
If you really need three files, then you'll might need to use ajax to do some sort of polling on studentlist.php using setTimeout to see if you have any new items.
The cheap-way is using a meta-refresh to refresh your page (or use JavaScript setInterval and ajax).
The more expensive way is having a Realtime JavaScript application. Look at Socket.IO or something like that.

Separating variables for SQL insert using PHP and JavaScript

A grid table is displayed via PHP/MySQL that has a column for a checkbox that the user will check. The name is "checkMr[]", shown here:
echo "<tr><td>
<input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\"
data-info=\"{$Row[BOL_NUMBER]}\" data-to=\"{$Row[TO_NUMBER]}\"
name=\"checkMr[]\" />
</td>";
As you will notice, there is are attributes for id, data-info, and data-to that are sent to a modal window. Here is the JavaScript that sends the attributes to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
var selectedBL = [];
var selectedTO = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
selectedBL.push($(this).attr('data-info'))
selectedTO.push($(this).attr('data-to'))
});
$(".modal-body .containerNumber").val( selectedID );
$(".modal-body .bolNumber").val( selectedBL );
$(".modal-body .toNumber").val( selectedTO );
});
});
</script>
So far so good. The modal retrieves the attributes via javascript. I can choose to display them or not. Here is how the modal retrieves the attributes:
<div id="myModal">
<div class="modal-body">
<form action="" method="POST" name="modalForm">
<input type="hidden" name="containerNumber" class="containerNumber" id="containerNumber" />
<input type="hidden" name="bolNumber" class="bolNumber" id="bolNumber" />
<input type="hidden" name="toNumber" class="toNumber" id="toNumber" />
</form>
</div>
</div>
There are additional fields within the form that the user will enter data, I just chose not to display the code. But so far, everything works. There is a submit button that then sends the form data to PHP variables. There is a mysql INSERT statement that then updates the necessary table.
Here is the PHP code (within the modal window):
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
$to = $_POST['toNumber'];
if(isset($_POST['submit'])){
$bol = mysql_real_escape_string(stripslashes($bol));
$container = mysql_real_escape_string(stripslashes($container));
$to = mysql_real_escape_string(stripslashes($to));
$sql_query_string =
"INSERT INTO myTable (bol, container_num, to_num)
VALUES ('$bol', '$container', '$to')
}
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Saved')
</script>");
}
else{
echo ("<script language='javascript'>
window.alert('Not Saved')
</script>");
}
?>
All of this works. The user checks a checkbox, the modal window opens, the user fills out additional form fields, hits save, and as long as there are no issues, the appropriate window will pop and say "Saved."
Here is the issue: when the user checks MULTIPLE checkboxes, the modal does indeed retrieve multiple container numbers and I can display it. They seem to be already separated by a comma.
The problem comes when the PHP variables are holding multiple container numbers (or bol numbers). The container numbers need to be separated, and I guess there has to be a way the PHP can automatically create multiple INSERT statements for each container number.
I know the variables need to be placed in an array somehow. And then there has to be a FOR loop that will read each container and separate them if there is a comma.
I just don't know how to do this.
When you send array values over HTTP as with [], they will already be arrays in PHP, so you can already iterate over them:
foreach ($_POST['bol'] as $bol) {
"INSERT INTO bol VALUES ('$bol')";
}
Your queries are vulnerable to injection. You should be using properly parameterized queries with PDO/mysqli
Assuming the *_NUMBER variables as keys directly below are integers, use:
echo '<tr><td><input type="checkbox" value="'.json_encode(array('CONTAINER_NUMBER' => $Row[CONTAINER_NUMBER], 'BOL_NUMBER' => $Row[BOL_NUMBER], 'TO_NUMBER' => $Row[TO_NUMBER])).'" name="checkMr[]" /></td>';
Then...
$('a#specifyAnchor').click(function() {
var selectedCollection = [];
$(':checkbox[name="checkMr[]"]:checked').each(function() {
selectedCollection.push($(this).val());
});
$(".modal-body #checkboxCollections").val( selectedCollection );
});
Then...
<form action="" method="POST" name="modalForm">
<input type="hidden" name="checkboxCollections" id="checkboxCollections" />
Then...
<?php
$cc = $_POST['checkboxCollections'];
if (isset($_POST['submit'])) {
foreach ($cc as $v) {
$arr = json_decode($v);
$query = sprintf("INSERT INTO myTable (bol, container_num, to_num) VALUES ('%s', '%s', '%s')", $arr['BOL_NUMBER'], $arr['CONTAINER_NUMBER'], $arr['TO_NUMBER']);
// If query fails, do this...
// Else...
}
}
?>
Some caveats:
Notice the selector I used for your previous $('a').click() function. Do this so your form updates only when a specific link is clicked.
I removed your mysql_real_escape_string functions due to laziness. Make sure your data can be inserted into the table correctly.
Make sure you protect yourself against SQL injection vulnerabilities.
Be sure to test my code. You may have to change some things but understand the big picture here.

Categories

Resources