getting dynamically created XML values with AJAX in js file - javascript

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.

Related

How to pass variables in a url using javascript and receive them using php?

What I am trying to do is to pass in variables from javascript to a php file using the url. The php is suppose to then parse the url into a json string and then store the json string on a separate text file. The php will then return the json string to the javascript for it to display. After a lot of testing I do believe my code isn't opening the php file or the php isn't parsing the url correctly.
here is the javascript:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
obj = this.responseText;
var data = JSON.parse(obj);
alert(data);
txt += "<tr><th>Student Id</th><th>Student Name</th><th>Type</th></tr>";
for (x in data.student){
txt += "<tr><td>" + data.student[x].id + "</td>";
txt += "<td>" + data.student[x].lname + ", " + data.student[x].fname + "</td>";
txt += "<td>" + data.student[x].type + "</td></tr>";
}
document.getElementById("display").innerHTML = txt;
}
xhttp.open("GET", "assign13.php?type="+type+"&fname="+fname+"&lname="+lname+"&id="+id+"&fname2="+fname2+"&lname2="+lname2+"&id2="+id2, true);
xhttp.send();
alert("all done");
}
Here is the php file:
<?php
class student{
public $type;
public $fname;
public $lname;
public $id;
function setAll($type, $fname, $lname, $id){
$this->$fname = $fname;
$this->$type = $type;
$this->$lname = $lname;
$this->$id = $id;
}
}
$s1 = new student();
$s2 = new student();
$type = $_GET["type"];
$fname = $_GET["fname"];
$lname = $_GET["lname"];
$id = $_GET["id"];
$f2 = $_GET["fname2"];
$l2 = $_GET["lname2"];
$i2 = $_GET["id2"];
$s1->setAll($type, $fname, $lname, $id);
$s2->setAll($type, $f2, $l2, $i2);
if ($type == "duet"){
$directory = array($s1, $s2);
}
else{
$directory = array($s1);
}
$str = json_encode($directory);
file_put_contents("../data/data.txt", $str);
echo $str;
?>
You have errors on your php class, it should be like this.....
<?php
class student{
public $type;
public $fname;
public $lname;
public $id;
function setAll($type, $fname, $lname, $id){
$this->fname = $fname;
$this->type = $type;
$this->lname = $lname;
$this->id = $id;
}
function getAll(){
return [
'fname' => $this->fname,
'type' => $this->type,
'lname' => $this->lname,
'id' => $this->id,
];
}
}
$s1 = new student();
$s2 = new student();
$type = "A";
$fname = "B";
$lname = "C";
$id = "12";
$f2 = "Test";
$l2 = "Test";
$i2 = "10";
$s1->setAll($type, $fname, $lname, $id);
$s2->setAll($type, $f2, $l2, $i2);
if ($type == "duet"){
$directory = array($s1->getAll(), $s2->getAll());
}
else{
$directory = array($s1->getAll());
}
$str = json_encode($directory);
echo $str;
?>

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

Ui Autocomplete return all values online but in localhost works

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

using query in DOMXpath wont work if class name contains white space

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.

No output from hidden Div with javascript

This is the java script function.I want it to make the div "resultss" visible and show the output.
But it's not displaying results, php code is executed without errors. Whys is this not displaying any output.
I'm trying to append the results at the bottom of same page where user submits some data
<script>
function myFunction()
{
var e = document.getElementById("resultss");
e.style.display = "block";
<?php
$format = $_SESSION["ff"];
$ses_id = $_SESSION["id"];
$filena = $_SESSION["filename"];
//$pubquery = $_SESSION["pubquery"];
$result1 = shell_exec("C:\Python27\python.exe C:\Python27\PredictoR\Model_desc.py $format $ses_id $filena 2>&1");
$properties = explode(" ", $result1);
if($properties[0] == 1)
{
$property = "Substrate";
} else {
$property = "Non-substrate";
}
$molwt = trim(preg_replace('/\s+/', ' ', $properties[1]));
$nhd = trim(preg_replace('/\s+/', ' ', $properties[2]));
$nha = trim(preg_replace('/\s+/', ' ', $properties[3]));
$logp = trim(preg_replace('/\s+/', ' ', $properties[4]));
?>
var molwt = <?php echo json_encode( $molwt); ?>;
var nhd = <?php echo json_encode( $nhd); ?>;
var nha = <?php echo json_encode( $nha); ?>;
var logp = <?php echo json_encode( $logp); ?>;
var property = <?php echo json_encode( $property); ?>;
document.getElementById('properties').innerHTML="Molecule is : "+property+" \n\
<br/>Molecular weight is : "+molwt+" \n\
<br/>No. of hydrogen bond donors = "+nhd+"\n\
<br/>No. of hydrogen bond acceptors = "+nha+"\n\
<br/>Log P : = "+logp+";
}
First of all close the script tag </script>
Secondly I can not see you calling your function myFunction(). Try calling it.
I hope it helps.
So you code should look something like:
<script>
function myFunction()
{
var e = document.getElementById("resultss");
e.style.display = "block";
<?php
$format = $_SESSION["ff"];
$ses_id = $_SESSION["id"];
$filena = $_SESSION["filename"];
//$pubquery = $_SESSION["pubquery"];
$result1 = shell_exec("C:\Python27\python.exe C:\Python27\PredictoR\Model_desc.py $format $ses_id $filena 2>&1");
$properties = explode(" ", $result1);
if ($properties[0] == 1) {
$property = "Substrate";
} else {
$property = "Non-substrate";
}
$molwt = trim(preg_replace('/\s+/', ' ', $properties[1]));
$nhd = trim(preg_replace('/\s+/', ' ', $properties[2]));
$nha = trim(preg_replace('/\s+/', ' ', $properties[3]));
$logp = trim(preg_replace('/\s+/', ' ', $properties[4]));
?>
var molwt = <?php echo json_encode($molwt); ?>;
var nhd = <?php echo json_encode($nhd); ?>;
var nha = <?php echo json_encode($nha); ?>;
var logp = <?php echo json_encode($logp); ?>;
var property = <?php echo json_encode($property); ?>;
document.getElementById('properties').innerHTML = "Molecule is : " + property + " \n\
<br/>Molecular weight is : " + molwt + " \n\
<br/>No. of hydrogen bond donors = " + nhd + "\n\
<br/>No. of hydrogen bond acceptors = " + nha + "\n\
<br/>Log P : = " + logp;
}
myFunction();
</script>

Categories

Resources