I am attempting to build a website to assist with recording times of events during ems calls. I have replicated our protocols and am using localstorage to record when and what event happens. When the incident is over, all the events that have been clicked are displayed on a report page where the information can be sent via email.
Everything seems to work, however, if another page is opened, the localstorage seem to clear and only the buttons clicked on the most recent page appear. I need every button clicked recorded for the report.
This is my JS:
//GO BACK BUTTON
function goBack() {
window.history.back();
}
// DATE FORMATER
function convertDate() {
var d = new Date();
var a = [(d.getMonth() + 1),
(d.getDate()),
(d.getFullYear()),
].join('-');
var b = [(d.getHours()),
(d.getMinutes()),
(d.getSeconds()),
].join(':');
return (b + ' ' + a);
}
///////////////////button////////////////////////
$(document).ready(function () {
var report = {};
var myItem = [];
$('button').click(function () {
var itemTime = convertDate() + " ___ " ;
var clickedBtnID = $(this).text() + " # " ;
item = {
ITEM: clickedBtnID,
TIME: itemTime ,
};
myItem.push(item);
localStorage.report = JSON.stringify(myItem);
});
});
And this is part of the report page:
<script>
window.onload = function () {
var areport = JSON.stringify(localStorage.report);
console.log(areport);
areport = areport.replace(/\\"/g, "");
areport = areport.replace(/{/g, "");
areport = areport.replace(/}/g, "");
areport = areport.replace(/[\[\]']+/g, "");
areport = areport.replace(/,/g, "");
areport = areport.replace(/"/g, "");
console.log(areport);
document.getElementById('result').innerHTML = areport;
};
</script>
<body>
<div class="container-fluid">
<h1>Report</h1>
<?php
if (isset($_POST["send"])) {
$incident = $_POST['incident'];
$name = $_POST['name'];
$address = $_POST['address'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$reportData = $_POST['reportData'];
if ($incident == '') {
echo $incident = 'No incident number entered.';
echo '<br>';
} else {
echo $incident . '<br>';
}
if ($name == '') {
echo $name = 'No name entered.';
echo '<br>';
} else {
echo $name . '<br>';
}
if ($address == '') {
echo $address = 'No address entered.';
echo '<br>';
} else {
echo $address . '<br>';
}
if ($dob == '') {
echo $dob = 'No birthdate entered.';
echo '<br>';
} else {
echo $dob . '<br>';
}
if ($gender == '') {
echo $gender = 'No gender entered.';
echo '<br>';
} else {
echo $gender . '<br>';
}
if ($reportData == null) {
echo $reportData = 'No report entered.';
echo '<br>';
} else {
echo $reportData . '<br>';
}
//mail
$headers = "From: CCEMP.info <ccemlbaw#server237.web-hosting.com> \r\n";
$reEmail = $_POST['reEmail'];
$reEmail1 = $_POST['reEmail1'];
//$areport = json_decode($_POST['localStorage.report']);
$msg = "Incident: " . $incident . "\n" . "Name: " . $name . "\n" . "Address:
". $address . "\n" . "DOB: " . $dob . "\n" . "Gender: " . $gender . "\n" .
$reportData;
mail($reEmail, 'Incident:' . $incident, $msg, $headers);
mail($reEmail1, 'Incident:' . $incident, $msg, $headers);
}//end of submit
?>
Here is a sample button:
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">General Truama</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" >Continue Assessment</a>
<a class="dropdown-item" href="GATA.php">Go to Truama</a>
</div>
</div>
Thanks.
You are not using localStorage, just setting .report on global localStorage variable. You would see this issue if you used strict mode ("use strict"; at top of the js file).
instead use:
localStorage.setItem("report", JSON.stringify(myItem));
and to get the item
localStorage.getItem("report");
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
This does not set the item to localStorage. In fact, localStorage.report is undefined.
localStorage.report = JSON.stringify(myItem);
This does.
localStorage.setItem('report', JSON.stringify(myItem));
I wasn't adding the localStorage from the previous page to the new one.
var myItem = [];
$(document).ready(function () {
$('button').click(function () {
var itemTime = convertDate() + " ___ " ;
var clickedBtnID = $(this).text() + " # " ;
var item = {
ITEM: clickedBtnID,
TIME: itemTime ,
};
myItem.push(item);
localStorage.setItem('report', JSON.stringify(myItem));
console.log(myItem);
});
var areport = localStorage.getItem("report");
myItem.push(areport);
});
Related
I have a form with a submit button and would like to remove the button and replace it with a loading gif image. I don't want this to happen just on click, since the form is verified I want the button to disappear only when all input fields are correctly filled so that the gif image shows progress. How can I do this?
Note: This is not a event to fire on success either, I want it to be a progress indicator. On success the form fade and display a message: "Thanks for contacting us! We will get back to you very soon..." and the jQuery below already handles this.
Here is the php code:
<?php
// Email address verification
function isEmail($email) {
return preg_match('|^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]{2,})+$|i', $email);
};
if($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'example#gmail.com';
$clientName = addslashes(trim($_POST['name']));
$clientEmail = addslashes(trim($_POST['email']));
$number = addslashes(trim($_POST['number']));
$message = addslashes(trim($_POST['message']));
$subject = 'Query from My Domain';
$sendMessage = 'Hi' . "\n\n";
$sendMessage .= $message . "\n\n";
$sendMessage .= 'From: ' . $clientName . "\n";
$sendMessage .= 'Email: ' . $clientEmail . "\n";
$sendMessage .= 'Contact number: ' . $number . "\n";
$array = array();
$array['nameMessage'] = '';
$array['emailMessage'] = '';
$array['numberMessage'] = '';
$array['messageMessage'] = '';
if($clientName == '') {
$array['nameMessage'] = 'Please enter your full name.';
}
if(!isEmail($clientEmail)) {
$array['emailMessage'] = 'Please insert a valid email address.';
}
if($number == '') {
$array['numberMessage'] = 'Please enter a valid contact number.';
}
if($message == '') {
$array['messageMessage'] = 'Please enter your message.';
}
if($clientName != '' && isEmail($clientEmail) && $message != '') {
// Send email
$headers = "From: " . $clientName . ' <' . $clientEmail . '>' . "\r\n";
$headers .= PHP_EOL;
$headers .= "MIME-Version: 1.0".PHP_EOL;
$headers .= "Content-Type: multipart/mixed;".PHP_EOL;
$headers .= " boundary=\"boundary_sdfsfsdfs345345sfsgs\"";
mail($emailTo, $subject, $sendMessage, $headers);
}
echo json_encode($array);
} else {
header ('location: index.html#contact');
}
?>
and here is the jQuery:
// Contact form
$('.contact-form form').submit(function(e) {
e.preventDefault();
var form = $(this);
var nameLabel = form.find('label[for="contact-name"]');
var emailLabel = form.find('label[for="contact-email"]');
var numberLabel = form.find('label[for="contact-number"]');
var messageLabel = form.find('label[for="contact-message"]');
nameLabel.html('Full name');
emailLabel.html('Email');
numberLabel.html('Contact number');
messageLabel.html('Message');
var postdata = form.serialize();
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.nameMessage !== '') {
nameLabel.append(' - <span class="red error-label"> ' + json.nameMessage + '</span>');
}
if(json.emailMessage !== '') {
emailLabel.append(' - <span class="red error-label"> ' + json.emailMessage + '</span>');
}
if(json.numberMessage !== '') {
numberLabel.append(' - <span class="red error-label"> ' + json.numberMessage + '</span>');
}
if(json.messageMessage !== '') {
messageLabel.append(' - <span class="red error-label"> ' + json.messageMessage + '</span>');
}
if(json.nameMessage === '' && json.emailMessage === '' && json.numberMessage === '' && json.messageMessage === '') {
form.fadeOut('fast', function() {
form.parent('.contact-form').append('<h2 class="text-center"><span class="orange">Thanks for contacting us!</span> We will get back to you very soon.</h2>');
});
}
}
});
});
do an ajax .done() after your ajax call to replace the button back
Here are my files:
Backend Search PHP File:
<?php
require "../sinfo.php";
function chk_phone($orig) {
return preg_replace("/[^0-9]/","",$orig);
}
$s = $_POST["s"];
$sql = "SELECT * FROM requests WHERE id LIKE '%" . $s . "%' OR " .
"lower(firstname) LIKE '%" . strtolower($s) . "%' OR " .
"lower(lastname) LIKE '%" . strtolower($s) . "%' OR " .
"dayphone LIKE '%" . strtolower($s) . "%' ORDER BY id ASC";
$result = $conn->query($sql);
$valid = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if ($row["status"] == "Complete" && date_compare($row["timestamp"]) < 37) {
$valid[] = $row;
}
}
}
if (count($valid) > 0) {
echo "<ul>\n";
foreach ($valid as $row) {
echo "<li onclick=\"javascript: autofill('" . $row["id"] . "', '" .
$row["firstname"] . "', '" .
$row["lastname"] . "', '" .
chk_phone($row["dayphone"]) . "', '" .
chk_phone($row["evephone"]) . "', '" .
$row["email"] . "', '" .
$row["make"] . "', '" .
$row["os"] . "', '" .
htmlspecialchars($row["issue"]) . "', '" .
$row["password1"] . "', '" .
$row["password2"] .
"');\">" . $row["id"] . " - " . $row["firstname"]. " " . $row["lastname"] . "</li>\n";
}
echo "</ul>\n";
} else {
echo "-- No Results Found --";
}?>
Here is the javascript file:
function upsearch(content) {
var xmlhttp;
try{
// Opera 8.0+, Firefox, Safari
xmlhttp = new XMLHttpRequest();
}
catch (e){
// Internet Explorer Browsers
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Something went wrong.!\nError: \n" + e);
return false;
}
}
}
xmlhttp.onreadystatechange = function() {
//if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("results").innerHTML = xmlhttp.responseText;
//}
};
var params = "s=" + content;
xmlhttp.open("POST", "ajax/requestsearch.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params);
}
function autofill(rid, fname, lname, dphone, ephone, email, make, os, issue, password1, password2) {
document.getElementById("searchrid").value = rid;
document.getElementById("searchrid").disabled = true;
document.getElementById("custinfo").style.display = "block";
document.getElementById("firstname").value = fname;
document.getElementById("firstname").disabled = true;
document.getElementById("lastname").value = lname;
document.getElementById("lastname").disabled = true;
document.getElementById("dayphone").value = dphone;
document.getElementById("evephone").value = ephone;
document.getElementById("email").value = email;
document.getElementById("equipinfo").style.display = "block";
document.getElementById("make").value = make;
document.getElementById("make").disabled = true;
document.getElementById("password1").value = password1;
document.getElementById("password2").value = password2;
document.getElementById("originalissue").style.display = "block";
document.getElementById("originalissue").innerHTML = issue;
document.getElementById("os").value = os;
}
On the main PHP page that calls the backend page, I get all the results as expected. It displays as I want and everything. My problem is that all the lines it returns, some of them don't perform the javascript "autofill" function, while others do. It's always the same ones, so it doesn't matter if the search is done in different ways. The only thing that I could think of that could cause problems was the "issue" field from my database can have html elements, but I fix that with the htmlspecialchars() function. Before I switched it to a POST method, I was using the GET method and I would pull that same page up with the same search results and look at the code, and it would all be correct, even those ones that would not perform the function. I switched it to the POST method to see if it would make a difference, but its the exact same problem. This same problem occurs in Chrome and IE. What am I doing wrong? Or what should I do differently.
I would suggest You to use jQuery.
Just use simple ajax request like:
$.ajax({
type: 'POST',
url: 'ajax/requestsearch.php',
data: 'q='+query,
success: function(data){
var r = $.parseJSON(data);
autofill(r[0].lastname,r[0].firstname, r[0].phone, etc);
}
});
and requestsearch.php
$q = $_POST['q'];
$sql="SELECT * FROM DataBase WHERE firstname LIKE '%$q%' ORDER BY firstname asc";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$data[] = $row;
}
echo json_encode($data);
I'm trying about 2 days to fix this I will blow my mind I can't anymore..When I am running it in localhost it's just working fine but when I am trying it online its just returns same values...and all values not returns the search term I can't understand why.
Jquery
$(document).ready(function($){
$('#quick-search-input2').autocomplete({
source:'All/home/directsearch.php',
minLength:2,
autoFocus: true,
select: function(event,ui){
var code = ui.item.id;
if(code != '') {
location.href = 'Movies/' + code;
}
},
html: true,
open: function(event, ui) {
$('ul.ui-autocomplete').slideDown(500)('complete');
$(".ui-autocomplete").css("z-index", 1000);
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("" + item.label + "")
.appendTo(ul);
};
});
PHP
$server = 'localhost';
$user = 'root';
$password = '';
$database = 'search';
$mysqli = new MySQLi($server,$user,$password,$database);
/* Connect to database and set charset to UTF-8 */
if($mysqli->connect_error) {
echo 'Database connection failed...' . 'Error: ' . $mysqli->connect_errno . ' ' . $mysqli->connect_error;
exit;
} else {
$mysqli->set_charset('utf8');
}
$term = stripslashes($_GET ['term']);
$term = mysql_real_escape_string($_GET ['term']);
$a_json = array();
$a_json_row = array();
include '../../connect.php';
/* ***************************************************************************** */
if ($data = $mysqli->query("SELECT * FROM search WHERE (title LIKE '%$term%' or keywords LIKE '%$term%') and serie = '' and visible = '' and complete = '' group by title, year order by clicks desc LIMIT 5")) {
while($row = mysqli_fetch_array($data)) {
$title = $row['title'];
$year = htmlentities(stripslashes($row['year']));
$type = $row['type'];
$customercode= htmlentities(stripslashes($row['link']));
$category= htmlentities(stripslashes($row['category']));
$synopsis= htmlentities(stripslashes($row['synopsis']));
$img= htmlentities(stripslashes($row['img']));
$id= htmlentities(stripslashes($row['id']));
$category = str_replace(" | ",", ", $category);
$shit = "'";
$ltitle = strtolower($title);
if ($type == "DL-HD")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/HD.png">';
}
else if ($type == "Non-HD")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/NonHD.png">';
}
else if ($type == "CAM")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/CAM.png">';
}
else
{
$qualityresponse = "";
}
$stitle = preg_replace("/[^A-Za-z0-9]/", "", $ltitle);
$a_json_row["id"] = $customercode;
$a_json_row["value"] = ''.$term.'';
$a_json_row["label"] = '
'.$qualityresponse.'<span class="titles">'.$title.'</span><p>'.$year.'</p></center>
';
array_push($a_json, $a_json_row);
}
}
$foundnum = mysql_num_rows(mysql_query("SELECT * FROM search WHERE (title LIKE '%$term%' or keywords LIKE '%$term%') and serie = '' and visible = '' and complete = '' group by title, year order by clicks desc LIMIT 5"));
if ($foundnum == 0)
{
$a_json_row["label"] = '
<li class="ac-no-results ac-item-hover ac-item-selected">No Movies found</li>
';
array_push($a_json, $a_json_row);
}
echo json_encode($a_json);
flush();
$mysqli->close();
$term = mysql_real_escape_string($_GET ['term']);
to
$term = mysqli->real_escape_string($_GET ['term']);
Im trying to extract links from an external site using php bot . The link is inside
<td class=" title-col"> News 1 </td>
Notice there is a space before " title-col".
Here is the script Im using which fails to extract the links
function crawl_page($url, $depth = 5) {
static $seen = array();
if (isset($seen[$url]) || $depth === 0) {
return;
}
$seen[$url] = true;
$dom = new DOMDocument('1.0');
//als tried true , but no change in results
$dom->preserveWhiteSpace = false;
#$dom->loadHTMLFile($url);
$xpath = new DOMXpath($dom);
$td = $xpath->query('//td[contains(concat(" ", normalize-space(#class), " "), "title-col")]');
// also tried this, but not working
//$td = $xpath->query('//td[contains(#class,"title-col")]');
//I only get values when I use this
//$td = $dom->getElementsByTagName('td');
foreach( $td as $t ) {
$anchors = $t->getElementsByTagName('a');
foreach ($anchors as $element) {
$href = $element->getAttribute('href');
if (0 !== strpos($href, 'http')) {
$path = '/' . ltrim($href, '/');
if (extension_loaded('http')) {
$href = http_build_url($url, array('path' => $path));
}
else {
$parts = parse_url($url);
$href = $parts['scheme'] . '://';
if (isset($parts['user']) && isset($parts['pass'])) {
$href .= $parts['user'] . ':' . $parts['pass'] . '#';
}
$href .= $parts['host'];
if (isset($parts['port'])) {
$href .= ':' . $parts['port'];
}
$href .= $path;
}
}
crawl_page($href, $depth - 1);
}
}
echo "URL:" . $url . "<br/>";
}
I only get values when I use this
$td = $dom->getElementsByTagName('td');
But I need to query by class .
THanks
I figured out it was due to javascript generated attribute.
I have created a dynamic xml file with php as follows
('Content-Type: text/xml');?>
<?php $newitem = $_GET["book"];
$action = $_GET["action"];
$qty=0;
$isbnVal="XYZ";
if ($_SESSION["Cart"] != ""){
$MDA = $_SESSION["Cart"];
if ($action == "Add"){
if ($MDA[$newitem] != ""){
$tempValue = $MDA[$newitem];
$value=$tempValue["qty"]+1;
$MDA[$newitem] =array("qty" => $value,"isbn" => $isbnVal);
}else{$MDA[$newitem] =array("qty" => 1,"isbn" => $isbnVal);}
}else{$MDA= "";}
}
else{$MDA[$newitem] =array("qty" => 1,"isbn" => $isbnVal);}
$_SESSION["Cart"] = $MDA;
ECHO (toXml($MDA));
function toXml($MDA){
$doc = new DomDocument('1.0');
$cart = $doc->createElement('cart');
$cart = $doc->appendChild($cart);
foreach ($MDA as $a => $b){
//echo "isbn".$b["isbn"];//echo "qty".$b["qty"]; $book = $doc->createElement('book');
$book = $cart->appendChild($book);
$title = $doc->createElement('title');
$title = $book->appendChild($title);
$value = $doc->createTextNode($a);
$value = $title->appendChild($value);
$quantity = $doc->createElement('quantity');
$quantity = $book->appendChild($quantity);
$value2 = $doc->createTextNode($b["qty"]);
$value2 = $quantity->appendChild($value2);
$isbn = $doc->createElement('isbn');
$isbn = $book->appendChild($isbn);
$value3 = $doc->createTextNode($b["isbn"]);
$value3 = $isbn->appendChild($value3);
}
$strXml = $doc->saveXML();
return $strXml;
}
then I'm calling these values in a javaScript file to display. I can get the first and last values from firstChild and lastChild. But I can't get whatever is in the middle. I tried it as follows.
spantag.innerHTML += " " +header[0].firstChild.textContent;
spantag.innerHTML += " " +header[0].getElementsByTagName('qty');
spantag.innerHTML += " " + header[0].lastChild.textContent + " <a href='#' onclick='AddRemoveItem(\"Remove\");'>Remove Item</a> ";
only the second code is not working. Plz tell me what I did wrong.Thanx in advance.