Issue with AJAX/Live Search - javascript

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);

Related

localstorage data not persisting between pages

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);
});

Json working for certain vars but not for others

I've made a script that requests information via Json. For some variables this works just fine, for others it doesn't.
When I use alert() for the variable neighbour1 it says the variable is undefined, when doing the same for the variables number and colour it works just fine.
This is the request script:
function getcolours() {
var hr = new XMLHttpRequest();
hr.open("GET", "camp_map_script.php", true);
hr.setRequestHeader("Content-type", "application/json");
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
for (var obj in data) {
number = data[obj].number;
colour = data[obj].colour;
neighbour1 = data[obj].n1;
alert (neighbour1);
window["colour" + number] = colour;
var x = document.getElementsByClassName(number + ' ' + colour);
x[0].style.display = "block";
}
}
}
hr.send(null);
}
This is the php part:
<?php
include_once("../php_includes/check_login_status.php");
?><?php
$number = "";
$sql = "SELECT camp_id FROM users WHERE username='$log_username'";
$query = mysqli_query($connect, $sql);
$row = mysqli_fetch_row($query);
$campid = $row[0];
$sql = "SELECT players FROM campaigns WHERE id='$campid'";
$query = mysqli_query($connect, $sql);
$row = mysqli_fetch_row($query);
$players = $row[0];
$number = ($players*2)-1;
$sql = "SELECT number, colour, player, n1, n2, n3, n4, n5, n6, n7, n8 FROM lands WHERE camp_id='$campid' ORDER BY number";
$query = $connect->query($sql);
$jsonData = '{';
if ($query->num_rows > 0) {
while($row = $query->fetch_assoc()) {
$jsonData .= '"obj'.$row["number"].'":{"number":"'.$row["number"].'", "colour":"'.$row["colour"].'", "player":"'.$row["player"].'", "n1":"'.$row["n1"].'"},';
}
}
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
$connect->close();
?>
Also when I check the php document the variable n1 is echoed correctly. So the error must be on the java script side or the transit.
It is probably something stupid that I'm overlooking but I just don't see it. I've copy pasted the working parts and changed them to work with other variables but it still doesn't work. :/

Receiving a responseText using xmlHttpRequest that i'm unsure about

I am using this code to add data to a database using ajax. Here is the html:
<form>
Product Name:</br>
<input type=text name=productName id="addProductName"></br>
Product Description:</br>
<input type=text name=productDescription id="addProductDescription"></br>
Product Quantity:</br>
<input type=number name=productQuantity id="addProductQuantity"></br>
<button id="addProduct" type=button>Add Product</button>
</form>
<div id="productAdded">test</div>
<script language="JavaScript" type="text/javascript" src="../javascript/test.js"></script>
Here is the javascript file test.js:
var xmlhttp;
function getXmlHttpRequest(){
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function addProduct(){
getXmlHttpRequest();
var productName = document.getElementById("addProductName");
var productDescription = document.getElementById("addProductDescription");
var productQuantity = document.getElementById("addProductQuantity");
var url = "insert.php?a=" + productName + "&b=" + productDescription + "&c=" + productQuantity;
xmlhttp.open("GET", url, false);
xmlhttp.send();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("productAdded").innerHTML = xmlhttp.responseText
}
};
}
var button;
button = document.getElementById("addProduct");
button.addEventListener("click", addProduct);
Here is the php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "products";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$productName = $_GET['a'];
$productDescription = $_GET['b'];
$productQuantity = $_GET['c'];
$sql = "INSERT INTO Product (ProductName, ProductDescription, ProductQuantity) VALUES ('$productName','$productDescription','$productQuantity')";
$conn->exec($sql);
echo 'Product ' . $productName . ' with quantity: ' . $productQuantity . ' Added';
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
I am getting all of the results that i expect except when i look at my database table i am seeing this instead of the data that was entered into the form:
[object HTMLInputElement]
When you do getElementById an HTMLInputElement is returned. After that you need to get the value of this element:
var productName = document.getElementById("addProductName").value;
var productDescription = document.getElementById("addProductDescription").value;
var productQuantity = document.getElementById("addProductQuantity").value;
You aren't actually getting the values from the input fields, use the value property to get it.
var productName = document.getElementById("addProductName").value;
var productDescription = document.getElementById("addProductDescription").value;
var productQuantity = document.getElementById("addProductQuantity").value;
also you should encode the date incase there ar any special characters in then
var url = "insert.php?a=" + encodeURIComponent(productName) + "&b=" + encodeURIComponent(productDescription) + "&c=" + encodeURIComponent(productQuantity);

Retrieving a JSON result

Hi I have used a code snippet from a tutorial for a chat application all of its scripts are working fine but after I tweak it to make the code work based on my requirements almost all of the scripts are working except for retrieving the conversation
The error I'm having is it doesn't retrieve the conversation from my database
here is the modified script
//Create the JSON response.
$json = '{"messages": {';
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
$json .= '"message":[ {';
$json .= '"id": "0",
"user": "Admin",
"text": "You are not currently in a chat session. <a href="">Enter a chat session here</a>",
"time": "' . date('h:i') . '"
}]';
} else {
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_POST['name'];
//Validation if msgid exists before creating a new table on the 2nd database
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd . "chat_conversation";
$sql7 = "SELECT msgid, message_content, username , message_time FROM $tblpre WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( ':chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
//Loop through each message and create an XML message node for each.
if(count($message_query) > 0) {
$json .= '"message":[ ';
while($message_array = $stmt7->fetch(PDO::FETCH_ASSOC)) {
$json .= '{';
$json .= '"id": "' . $message_array['msgid'] . '",
"user": "' . htmlspecialchars($message_array['username']) . '",
"text": "' . htmlspecialchars($message_array['message_content']) . '",
"time": "' . $message_array['message_time'] . '"
},';
}
$json .= ']';
} else {
//Send an empty message to avoid a Javascript error when we check for message lenght in the loop.
$json .= '"message":[]';
}
}
//Close our response
$json .= '}}';
echo $json;
Here is the code for calling this script
//Gets the current messages from the server
function getChatText() {
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
receiveReq.open("GET", 'includes/getChat.php?chat='+uid+'&last=' + lastMessage, true);
receiveReq.onreadystatechange = handleReceiveChat;
receiveReq.send(null);
}
}
function sendChatText() {
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.open("POST", 'includes/getChat.php?last=' + lastMessage, true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = handleSendChat;
var param = 'message=' + document.getElementById('txtA').value;
param += '&name='+user;
param += '&uid='+uid;
param += '&rid='+document.getElementById('trg').value;
sendReq.send(param);
document.getElementById('txtA').value = '';
}
}
//When our message has been sent, update our page.
function handleSendChat() {
//Clear out the existing timer so we don't have
//multiple timer instances running.
clearInterval(mTimer);
getChatText();
}
function handleReceiveChat() {
if (receiveReq.readyState == 4) {
//Get a reference to our chat container div for easy access
var chat_div = document.getElementById('clog');
var response = eval("(" + receiveReq.responseText + ")");
for(i=0;i < response.messages.message.length; i++) {
chat_div.innerHTML += response.messages.message[i].user;
chat_div.innerHTML += ' <font class="chat_time">' + response.messages.message[i].time + '</font><br />';
chat_div.innerHTML += response.messages.message[i].text + '<br />';
chat_div.scrollTop = chat_div.scrollHeight;
lastMessage = response.messages.message[i].id;
}
mTimer = setTimeout('getChatText();',20000); //Refresh our chat in 2 seconds
}
}
Am I missing something here or doing something wrong?
You should rewrite using json_encode:
$messages = array();
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
$message_object = (object) array(
"id"=>"0",
"user"=>"Admin",
"text"=>"You are not currently in a chat session. <a href=\"\">Enter a chat session here</a>",
"time"=>date('h:i')
);
$messages[] = (object) array("message"=>$message_object);
} else {
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_POST['name'];
//Validation if msgid exists before creating a new table on the 2nd database
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd . "chat_conversation";
$sql7 = "SELECT msgid, message_content, username , message_time FROM $tblpre WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( ':chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
//Loop through each message and create an XML message node for each.
if(count($message_query) > 0) {
$message_object = (object) array(
"id"=>$message_array['msgid'],
"user"=>htmlspecialchars($message_array['username']),
"text"=>htmlspecialchars($message_array['message_content']),
"time"=>$message_array['message_time'
);
$messages[] = (object) array("message"=>$message_object);
} else {
//Send an empty message to avoid a Javascript error when we check for message lenght in the loop.
$messages[] = (object) array("message"=>array());
}
}
//Close our response
$result = (object) array('messages'=>$messages);
$json = json_encode($result);
echo $json;

AJAX responseXML error: Uncaught TypeError

I am having the following code:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
result = xmlhttp.responseXML.getElementsByTagName("tr");
if(result)
console.log(result);
showTable(result);
isClicked = false;
}
}
xmlhttp.open("GET", "php_includes/getResult.php?search=" + document.getElementById("search").value, true);
xmlhttp.send();
my file will produce something like:
<tr><td>1</td><td>APPLES</td><td> 0000000000414</td><td>$0.79</td></tr>
<tr><td>2</td><td>Apple Sauce</td><td> 0000000000528</td><td>$1.92</td></tr>
<tr><td>3</td><td>Apple</td><td> 0000000000540</td><td>$0.59</td></tr>
<tr><td>4</td><td>Snapple</td><td> 0000000000543</td><td>$0.69</td></tr>
By running the code I get the following error:
"Uncaught TypeError: Cannot call method 'getElementsByTagName' of null"
However, when I use the xmlhttp.responseText it get the result. Any idea?
This is my PHP file:
$x = 1;
$count = 0;
$result2 = array();
$result .= "<search>";
while ($row = sqlsrv_fetch_array($stmt)) {
// $class = ($x % 2 !== 0) ? 'whiteBackground' : 'graybackground';
//echo "OOMAD INJA";
//$name = sqlsrv_get_field( $stmt, 0);
//echo "$i $name<br/>";
//setlocale(LC_MONETARY, 'en_US');
$plu = $row["F01"];
$result2[] = $row['F02'];
//$result .= "<tr class='$class' onclick = 'clicked($plu);' onmouseover='ChangeColor(this, true);' onmouseout='ChangeColor(this, false);' ><td>" . $x . "</td><td class='searchtable'>" . $row["F02"] . "</td><td> " . $row["F01"] . "</td><td height= '40px'>\$" . number_format((float) $row["F30"], 2, '.', '') . "</td></tr>";
$result .= "<tr1><td1>" . $x . "</td1><td2>" . htmlentities($row["F02"]) . "</td2><td3> " . $row["F01"] . "</td3><td4>\$" . number_format((float) $row["F30"], 2, '.', '') . "</td4></tr1>";
$x++;
}
$result .="</search>";
echo $result;

Categories

Resources