Database update field on onclick submit doesn't work - javascript

I am trying to update a column on my database. The user will click the confirm button and an email is sent to the user confirming a list of jobs and at the same time change the field status in column "confirmed" to "Yes".
I am able to send an email to the user but i have no clue as to why the column id like to update in my database doesn't work.
Here is my code
php:
<?php
ini_set("display_errors",1);
error_reporting(-1);
require("../controllers/cn.php");
include("/usr/share/php/Mail.php");
include("/usr/share/php/Mail/mime.php");
// Get the purchase order details
$query = mysql_query("SELECT Jobs.* FROM Jobs where job_status = 'Dispatched'") or die(mysql_error());
// Set the email content
$text = 'Text version of email';
$html .= '<html><body>';
$html .= '<p style="font-family: Arial, Helvetica, sans-serif; font-size: 22px; font-weight: bold; text-transform: uppercase; text-align: center;">Spineless Dispatch Summary</p>';
$html .= '<p style="font-family: Arial, Helvetica, sans-serif; font-size: 13px; text-align: center;">Please find below a summary of all dispatched orders: </p>';
$html .= '<table border="1" cellspacing="0" cellpadding="0" align="center"><tr><th width="200">Order Ref.</th><th width="200">First Name</th><th width="200">Last Name</th><th width="200">Tracking No.</th></tr>';
while($row = mysql_fetch_array($query)) {
$html .= '<tr>';
$html .= '<td style="padding: 10px;">'.$row['order_ref'].'</td>';
$html .= '<td style="padding: 10px;">'. $row['first_name'].'</td>';
$html .= '<td style="padding: 10px;">'.$row['last_name'].'</td>';
$html .= '<td style="padding: 10px;">'.$row['tracking_number'].'</td>';
$html .= '</tr>';
}
$html .= '</table></body></html>';
//$file = "/mnt/Jobs/Purchase_Orders/".date("Y", strtotime($row['created']))."/".date("F", strtotime($row['created']))."/PO".$row['id'].".pdf";
$crlf = "\n";
// Set customers email
$sendAddress = "rachelle#variouk.com";
// Set the from address
$hdrs = array(
'From' => 'rachelle#variouk.com',
'Subject' => 'Spineless System'
);
// Create the email
$mime = new Mail_mime(array('eol' => $crlf));
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
//$mime->addAttachment($file, 'application/pdf');
$body = $mime->get();
$hdrs = $mime->headers($hdrs);
// Send the email
$mail =& Mail::factory('mail');
// Paper company address
$mail->send($sendAddress, $hdrs, $body);
// Production email address (production#variouk.com)
$mail->send("rachelle#variouk.com", $hdrs, $body);
// Update the sent status of the order
$result = mysql_query("UPDATE Jobs SET confirmed = 'Yes' WHERE order_ref = '".$order_ref."' ");
header("location: joblist.php");
?>
HTML:
<div id="buttons" align="center">
<p style="padding-bottom: 15px; font-weight: bold; font-size: 14px;">Please confirm these jobs</p>
<button type="submit" class="btn btn-primary" onclick="javascript:window.location='email.php">Confirm</button>
<button class="btn btn-default btn-wide" onclick="javascript:window.location="'joblist.php'";>Cancel</button>
</div>

Edit2:
$order_refs = array();//array of orders to update in db.
while($row = mysql_fetch_array($query)) {
$html .= '<tr>';
$html .= '<td style="padding: 10px;">'.$row['order_ref'].'</td>';
$html .= '<td style="padding: 10px;">'. $row['first_name'].'</td>';
$html .= '<td style="padding: 10px;">'.$row['last_name'].'</td>';
$html .= '<td style="padding: 10px;">'.$row['tracking_number'].'</td>';
$html .= '</tr>';
$order_refs[]=$row['order_ref'];
}
And to update using ref from array
$result = mysql_query("UPDATE Jobs SET confirmed = 'Yes' WHERE order_ref IN ('". implode("', '", $order_refs) ."') ");
Let me know if it works.
Original:
Try adding
if(!$result){
echo mysql_error();
}
after
$result = mysql_query("UPDATE Jobs SET confirmed = 'Yes' WHERE order_ref = '".$order_ref."' ");
And tell me what does it say. I'll update my answer with a fix for that error. (I cannot comment on Questions yet, still low reputation)
Edit: as #Santik noted $order_ref is not defined in this code, so the fix would be to use $row['order_ref']
$result = mysql_query("UPDATE Jobs SET confirmed = 'Yes' WHERE order_ref = '".$row['order_ref']."' ");

Related

Why my select is not change after i call this.form.submit()?

i have a problem when i want to select dropdown after that the value in option not change and back to normal again. i want to know how to make when i choose an option in dropdown select the value keep on i choose not back to normal ? sorry for my bad english.. look at example below
$out .= '<form method="POST" >';
$out .= ' <table class="table table-bordered table-condensed"><tbody>';
$out .- ' <tr>';
$out .= ' <td class="info" width="5%"><b>Race</b></td>';
$out .= ' <td>';
$out .= ' <select class="form-control" name="race_select" onchange="this.form.submit();">';
$out .= ' <option value selected>All Races</option>';
$out .= ' <option>Accretia</option>';
$out .= ' <option>Bellato</option>';
$out .= ' <option>Cora</option>';
$out .= ' </select>';
$out .= ' </td>';
$out .= ' </tr>';
$out .= ' </tbody></table>';
$out .= '</form>';
$out .= '<br>';
look i have select option when i choose for e.g Accretia. when it render again the value in option still All races, i want to when people choose some option, the value in option keep that people choose not back to All races again.
look at this image
when i choose bellato the option not change to bellato but still All Races

format cells based on value in php

I have 2 text files and read their content into 2 arrays using php. Then I create a table and display it on my site. I now want to color every cell from array 2 (column 2) based on certain values.
For Example:
if a value from array2 contains "busy", it shall be formatted red, if
it contains "available", it shall be formatted green.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form action="" method="post" class="formbody">
<div class="codetable">
<?php
$file1 = "c:/presencetool/ramfile1.txt";
$file2 = "c:/presencetool/ramfile2.txt";
$line1= file($file1, FILE_IGNORE_NEW_LINES);
$line2 = file($file2, FILE_IGNORE_NEW_LINES);
$combine = array_combine($line1, $line2);
$html = "<table align=center>";
$html .= "<tr><td width=300px></td><td></td></tr>";
$i = 1;
foreach ($combine as $file1 => $file2):
$html .= "<tr>";
$html .= "<td>".$file1."</td>";
$html .= "<td>".$file2."</td>";
$html .= "</tr>";
$i++;
endforeach;
$html .= "</table>";
echo $html;
?>
<div class="codelabel">
</div>
</div>
</form>
</body>
</html>
I tried some possible solutions but could not bring it to work.
Any ideas? If there is any Information I should provide, just ask.
edit:
content of ramfile 1&2:
ramfile1:
User#1
User#2
User#3
...
User#n
ramfile2:
Busy
Busy
Available
Busy
...
<?php
$path = $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'demo'.DIRECTORY_SEPARATOR;
$file1 = $path.'ramfile1.txt';
$file2 = $path.'ramfile2.txt';
if(file_exists($file1) && file_exists($file2)) {
$line1= file($file1, FILE_IGNORE_NEW_LINES);
$line2 = file($file2, FILE_IGNORE_NEW_LINES);
$combine = array_combine($line1, $line2);
$html = '<table align="center">';
$html .= '<tr><td width="300px"></td><td></td></tr>';
$i = 1;
foreach ($combine as $key => $value):
$html .= '<tr class="'.$value.'">';
$html .= '<td>'.$key.'</td>';
$html .= '<td>'.$value.'</td>';
$html .= '</tr>';
$i++;
endforeach;
$html .= '</table>';
echo $html;
}
?>
<style>
.Busy { background-color: #f2a179;}
.Available { background-color: #00ff00;}
</style>
foreach ($combine as $file1 => $file2):
This line makes no sense at all. It will probably run but it won't do what you describe. I think you really want something like....
foreach ($file1 as $i=>$value) {
$html .= "<tr>";
$html .= "<td>".$file1[$i]."</td>";
$html .= "<td>".$file2[$i]."</td>";
$html .= "</tr>";
}
But that you are resolving data in one file from another based on the line number is a very bad choice of data structure.
if a value from array2 contains "busy", it shall be formatted red, if it contains "available", it shall be formatted green.
There are lots of ways to do this. You could call a function....
$bgcolor=lookup_css_class($file2[$i]);
$html .= "<td class='$bgcolor'>$file2[$i]</td>";
Or you could use dependancy injection, or you could use an array lookup. Alternatively you could simply declare CSS classes based on the value and inject the value as the class name for the TD (but bear in mind this allows someone with control over the data to inject html/javascript into your page:
td.busy {background-color: red;}
td.free {background-color: green;}
...
$html .= "<td class='$file2[$i]'>$file2[$i]</td>";

How pull innerHTML of element created by javascript function

Question:
I have a div element with id of "tableholder" which is purely to hold the output on a javascript function that pulls data via ajax from a PHP file.
Within the tableholder element, is a list.js table that works if we simply include he php file instead of calling it via ajax and setting it via innerHTML = "".
How do I use the contents of innerHTML of the tableholder div when it has been created dynamically?
Code so far:
PHP File called:
<?php
// Connection details for the database being called.
include 'connection.php';
// Putting the query to the database in a variable called "$assets".
$assets = "SELECT * FROM assetregister.getassets";
$assetPull = $conn->query($assets);
$output = "";
// Pulling all of the details from the database and displaying them on the page within the inidividual divs.
if ($assetPull->num_rows > 0) {
$output .= "<div id='users'>";
$output .= "<input class='search form-control mt-2' placeholder='Search...' />";
$output .= "<div class='m-2'>";
$output .= "<button class='sort btn' data-sort='model'>Sort By Model</button>";
$output .= "<button class='sort btn ml-2' data-sort='domain'>Sort By Domain</button>";
$output .= "<button class='sort btn ml-2' data-sort='location'>Sort By Location</button>";
$output .= "</div>";
$output .= "<table class='table table.hover list'>";
$output .= "<thead>";
$output .= "<th style='text-align: center;'>Model</th>";
$output .= "<th style='text-align: center;'>Serial Number</th>";
$output .= "<th style='text-align: center;'>Asset Number</th>";
$output .= "<th style='text-align: center;'>Domain</th>";
$output .= "<th style='text-align: center;'>Location</th>";
$output .= "<th style='text-align: center;'>Type</th>";
$output .= "</thead>";
while ($row = $assetPull->fetch_assoc()) {
$output .= "<tbody class='list' style='text-align: center;'>";
$output .= "<td class='model'>" . $row['modelName'] . "</td>";
$output .= "<td class='serialNumber'>" . $row['serialNumber'] . "</td>";
$output .= "<td class='assetNumber'>" . $row['assetNumber'] . "</td>";
$output .= "<td class='domain'>" . $row['domain'] . "</td>";
$output .= "<td class='location'>" . $row['locationName'] . "</td>";
$output .= "<td class='type'>" . $row['type'] . "</td>";
}
$output .= "</tbody>";
$output .= "</table>";
$output .= "</div>";
// If there is no rows in the table that is being called then they will display 0 Results... See below.
} else {
$output .= "0 results";
}
echo $output;
$conn->close();
?>
This works:
<div class="container-fluid">
<div class="container">
<div class="row">
<main class="col-12" style="margin-top: 80px;">
<button class="btn btn-primary" onclick="assetSubmit()" style="width: 100%;">Add An Asset</button>
<?php include 'scripts/getAsset.php'; ?>
</main>
</div>
</div>
</div>
<script>
populatetable('tableholder');
window.onload = function () {
var options = {
valueNames: ['model', 'serialNumber', 'assetNumber', 'domain', 'location', 'type']
};
var userList = new List('users', options);
};
</script>
This outputs the table and all of the list.js functions work fine as expected.
This Doesn't Work:
<div class="container-fluid">
<div class="container">
<div class="row">
<main class="col-12" style="margin-top: 80px;">
<button class="btn btn-primary" onclick="assetSubmit()" style="width: 100%;">Add An Asset</button>
<!-- Pulling in the results of the assets (most recent assets) -->
<div id="tableholder"></div>
<!-- end -->
</main>
</div>
</div>
</div>
<!-- PHP include for the footer -->
<?php include 'assets/layout/footer.php'; ?>
<!-- end -->
<script>
populatetable('tableholder');
window.onload = function (){
var options = {
valueNames: [ 'model', 'serialNumber', 'assetNumber', 'domain', 'location', 'type']
};
var userList = new List('users', options);
};
function populatetable(name){
$.ajax({
url: "scripts/getAssets.php",
success: function(data){
document.getElementById(name).innerHTML = data;
}
})
}
</script>
What I can assume:
From the various console.log lines and php echos I have put in to test the code, it would appear that the issue it that the javascript command for initiating the list.js table isn't able to find the "user" table that is created by the document.getElementById(name).innerHTML = data; in the populatetable() function. I know this because the folllowing shows blank:
console.log(document.getElementById(tableholder).innerHTML);
What am I doing wrong, or is it not possible to pull the innerHTML data of a dynamically created element?
The problem is that by the time you're calling List(), the ajax call hasn't finished yet, since it's asynchronous.
Try this instead:
var options = {
valueNames: ['model', 'serialNumber', 'assetNumber', 'domain', 'location', 'type']
};
var userList;
$(document).ready(function() {
populatetable('#tableholder');
});
function populatetable(id) {
$.ajax({
url: "scripts/getAssets.php",
success: function(data) {
$(id).html(data);
userList = new List('users', options);
}
});
}
Here I'm using jQuery everywhere it's useful, and I'm calling List() only after the data is actually inserted.
Also note, that like I mentioned in my comment, you need to move the <tbody> line outside the loop.

Validation Errors on contact.php: How to show more than 1 validation error message?

First of all, I am kind of new with PHP and JavaScript. I am currently working on a contact form using MailHandler.php, TMForm.js and my contact.php file. I would like to know how can my message textarea show more than one validation error (for example, when some symbols are not validated lie #$<> and the min lenght is 5 characters, I want my textarea to show both validation errors one after another).
I added a RegExp at the end of my TMForm.js
regula.custom({
name:'Special'
,validator:function(){
return /^[^\$\%\&\|\<\>\#]*$/.test(this.value)
}
})
This is my contact.php textarea
<label class="message">
<textarea id="message" class="input" name="cf_message"
placeholder="Insert your message:"
data-constraints="#Required #Special #Length(min=5,max=999999)"></textarea>
<span class="empty-message">*This field is required.</span>
<span class="error-message">*The following characters are not allowed: $, %, &, |. <, > y #.</span>
and my MailHandler.php
<?php
session_start();
$count = 0;
if(isset($_POST['cf_email'])) {
$name = $_POST['cf_name'];
$email = $_POST['cf_email'];
$message = $_POST['cf_message'];
$email_to = "email#mail.com";
$email_subject = "You have a new email: ".$name;
$_SESSION['nameErr'] = $nameErr;
$count = $count + 1;
$_SESSION['emailErr'] = $emailErr;
$count = $count + 1;
$_SESSION['messageErr'] = $messageErr;
$count = $count + 1;
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message = "<html><body style='max-width: 800px;'>";
$email_message .= "<div><h1 style='font-weight: 500px; font-size: 2em; text-align: center; padding: 30px 0; border-bottom: 1px solid #1D547B; color: #2a3d51;' >El mensaje fue enviado por: ".clean_string($name)."\n</h1>";
$email_message .= "<p style='font-weight: 900px; font-size: 1em; text-align: justify; padding: 20px 0; font-style: italic; color: grey;'>".clean_string($message)."</p>";
$email_message .= "</div>";
$email_message .= "</body></html>";
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email_from."\r\n" .
'content-type: text/html; charset=ISO-8859-1\r\n'.
'X-Mailer: PHP/' . phpversion();
if ($count > 0) {
$Message = "The Message wasn not sent. Please verify again.";
$_SESSION['Message'] = $Message;
} else {
$Message = "You message was sent. Thank you.";
$_SESSION['Message'] = $Message;
#mail($email_to, $email_subject, $email_message, $headers);
}
$_SESSION['count'] = $count;
header("Location: ../contactenos.php");
}
?>
My question is if its possible to show both validation errors on their own and on the same textarea?
I suggest you to use more php to make things easy to return securely.
something like..
trim(stripslashes($_POST['cf_message']));
This way you can leave error handling for HTML/JS as you like with the UI...

Using AJAX with a contact form to remove page reload

I have seen lots of questions about this on here and have taken the code I have now from several answers.
But for some reason I cant get it to work and I cant figure out why.
I have a HTML form with the code here:
<form id="quick_contact" name="quick_contact" action="" method="POST">
<div class="input-control text">
<input id="name" name="name" type="text" value="" placeholder="Enter name here">
</div>
<div class="space10"> </div>
<div class="input-control email">
<input id="email" name="email" type="email" value="" placeholder="Enter email address here"/>
</div>
<div class="space10"> </div>
<div class="input-control textarea">
<textarea id="comments" name="comments" placeholder="Enter Comments Here"></textarea>
</div>
<div class="space10"> </div>
<button id="quick_submit" name="quick_submit" onclick="quickContact()">Send</button>
</form>
And I have my jquery here UPDATED as of Thomas' answer:
<script type="text/javascript">
function quickContact(){
$.ajax({
type: "POST",
url: "quick-contact.php",
data:
{
name: $('#name').val().trim(),
email: $('#email').val().trim(),
comments: $('#comments').val().trim(),
},
success: function(html) {
var submitted = $.trim(html);
if (submitted) {
alert("Thanks for your submission");
$('#quick_contact')[0].reset();
return;
} else {
alert("Failed to submit.");
return false;
}
}
});
};
</script>
And here is the PHP which handles the email side of things in a file called "quick-contact.php again updated as of Thomas' answer:
if(isset($_POST) == true){
$status = 1 // init to one, assume there will not be an error
//Store the entered values in the variables
$name = mysql_escape_string(trim($_POST['name']));
$email = mysql_escape_string(trim($_POST['email']));
$comments = mysql_escape_string(trim($_POST['comments']));
$comments = str_replace('\r\n','<br>',$comments);
// EMAIL HEADERS
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=utf-8\n";
$headers .= "X-Priority: 3\n";
$headers .= "X-MSMail-Priority: Normal\n";
$headers .= "X-Mailer: php\n";
$headers .= "From: *****<*****#l*****>\n";
//SEND EMAIL TO BRANCH
// EMAIL TITLE
$subject = $name . " " . get_content(3344);
//message
$message1 = "<style type=\"text/css\">";
$message1 .= "div { font-family: Arial, Verdana, Tahoma; font-size: 10pt; line-height: 120%; }";
$message1 .= "h1 { margin: 0; font-size: 14pt; }";
$message1 .= "h2 { margin: 0; font-size: 12pt; }";
$message1 .= "span { font-size: 9pt; font-weight: bold; }";
$message1 .= "</style>\n";
$message1 .= "<div>";
$message1 .= "<p>" . $name . " " . get_content(3344) . "</p>\n";
$message1 .= "<p>" . get_content(3345) . "</p>\n";
$message1 .= "<p><b>" . ucwords(get_content(2869)) . ":</b> " . $name . "<br />";
$message1 .= "<b>" . ucwords(get_content(27)) . ":</b> " . $email . "<br />";
$message1 .= "<b>" . ucwords(get_content(1258)) . ":</b> " . $comments . "<br />";
$message1 .= "</p>\n";
$message1 .= get_content(893); // King Regards,
$message1 .= "<br /><br />";
$message1 .= "<img src=\"***********\" alt=\"*******\">";
$message1 .= "<br />";
$message1 .= "</div>";
//SEND CUSTOMER AN EMAIL
// EMAIL TITLE
$subject2 = get_content(392);
//message
$message2 = "<style type=\"text/css\">";
$message2 .= "div { font-family: Arial, Verdana, Tahoma; font-size: 10pt; line-height: 120%; }";
$message2 .= "h1 { margin: 0; font-size: 14pt; }";
$message2 .= "h2 { margin: 0; font-size: 12pt; }";
$message2 .= "span { font-size: 9pt; font-weight: bold; }";
$message2 .= "</style>\n";
$message2 .= "<div>";
$message2 .= "<p>" . $name . ",</p>\n";
$message2 .= "<p>" . get_content(392) . "</p>\n";
$message2 .= "<p>" . str_replace("{TEL_NUMBER}", $header_branch_details[0]['Tel'], str_replace("{BRANCH_EMAIL}", $header_branch_details[0]['SalesEmail'], get_content(2764))) . "</p>\n";
$message2 .= get_content(893); // King Regards,
$message2 .= "<br /><br />";
$message2 .= "<img src=\"*********\" alt=\"*********\">";
$message2 .= "<br />";
$message2 .= "</div>";
//Send branch email
$success = mail('***#****.com', $subject, $message1, $headers);
//Send customer email
$success2 = mail($email, $subject2, $message2, $headers);
if (!$success) {
$status = 0;
}
echo $status;
}
Sorry about the mass of code I really hope someone can help me here
Change the submit type to a button type with an onClick event that calls doSomething().
Then, have doSomething() run the ajax call, like so:
function doSomething() {
$.ajax({
type: 'post',
url: 'quick-contact.php',
data:
{
name: $('#name').val().trim(),
email: $('#email').val().trim(),
comments: $('#comments').val().trim(),
},
success: function(html) {
var status = $.trim(html);
if (status) {
alert("Thanks for your submission");
$('#quick_contact')[0].reset();
return;
} else {
alert("Failed to submit.");
return false;
}
}
});
}
Then in your PHP, all you have to do is check if $_POST isset.
if (($_POST)) {
$status = 1; // init to one, assume there will not be an error
$name = $_POST['name'];
//etc, but FILTER the data coming from the client
}
Also, you may want to do something like this near your mail() function:
$success = mail(//etc);
if (!$success) {
$status = 0;
}
echo $status;
If you still have questions, let me know. I'm happy to help.

Categories

Resources