why is my xml request is coming back undefined - javascript

My code now is incomplete but I tested my xml request and I'm just returning undefined. I am trying to access a folder on a server that contains several folders each named after a book and each containing that books information (cover.jpg, general info txt, reviews txt, etc). Right now I'm just trying to create an XML in my php with the following format:
<books>
<book>
<title>whatever the title of the book is</title>
<folder>whateverthefoldersnameis</folder>
</book>
</books>
but it doesn't seem to be working because in my javascript on line 47 when I try and just get the textcontent of books so I can insert that into my HTML it just says it's undefined. A little lost here.
(function() {
var xml = null;
"use strict";
// sets up onclick handlers
window.onload = function() {
getRequest("books");
var home = document.getElementById("back");
home.onclick = getRequest("books");
};
// sends an ajax request to the passed in address.
// calls the passed in function when the request returns.
function ajax($adress, $function) {
var request = new XMLHttpRequest();
request.onload = $function;
request.open("GET", $adress, true);
request.send();
}
// makes a request for all books.
function getRequest(value) {
ajax("bestread.php?mode=" + value, displayXml("allbooks"));
}
function displayJson() {
$json = JSON.parse(this.responseText);
for($cat in $json.books) {
var book = document.createElement("div");
book.innerHTML = $cat;
book.onclick = choose;
document.getElementById("allbooks").appendChild(book);
}
}
function choose() {
var book = this.innerHTML;
document.getElementById("allbooks").innerHTML = "";
document.getElementById("singlebook").innerHTML = book;
getRequest("info", getInfo);
getRequest("reviews", displayXml("reviews"));
}
function displayXml(id) {
xml = this.responseXML;
document.getElementById(id).innerHTML = xml.querySelector("books").textContent;
}
})();
<?php
$mode = $_GET["mode"];
$book = $_GET["title"];
$url = "../../students/jck789/hw6/books/";
if($mode == "books") {
bookXml($url);
} else if ($mode == "info") {
outputJson($url, $book, "info");
} else if ($mode == "description") {
outputJson($url, $book, "description");
} else if ($mode == "reviews") {
reviewXml($url, $book, "reviews");
}
# outputs the list of available categories in JSON
function outputJson($url, $value) {
$files = glob($url . "*");
$json = array($value => array());
foreach($files as $file) {
$count = count(glob($file."/*"));
$json[$value][basename($file)] = $count;
}
header("Content-type: application/json");
print(json_encode($json));
}
function bookXml($url) {
$files = glob($url . "*");
$index = 0; //currently just trying to grab the first book
list($name, $fold) = file($files[$index]);
$dom = new DOMDocument();
$books = $dom->createElement("books");
$dom->appendChild($books);
$book = $dom->createElement("book");
$books->appendChild($book);
$title = $dom->createElement("title");
$title->appendChild($dom->createTextNode($name));
$folder = $dom->createElement("folder");
$folder->appendChild($dom->createTextNode($fold));
$book->appendChild($title);
$book->appendChild($folder);
header("Content-type: text/xml");
print($dom->saveXML());
}
function reviewXml($url, $book) {
$files = glob($url . "$book/*")
}
?>

Related

Get json encode data from another ajax function

I'm using prestashop 1.6, I have an ajax function where I encode some data which I successfully retrieved on console withecho. Now I have to decode this json data in another ajax function to get a value for a specific variable. Sorry I'm a newbie with prestashop 1.6.
My first ajax function :
public function ajaxProcessAddQrVideo(){
$target_dir = _PS_IMG_DIR_.DS.'video_qr';
$id_product = Tools::getValue('id_product');
$stamp = strtotime('now');
$filename = 'video_qr_'.$id_product.'_'.$stamp.'.jpg';
$target_file = $target_dir.DS.$filename;
$upload = $_FILES['video_qr_attachment_file'];
$err = array();
$uploaded = false;
if($upload['type'] !='image/jpeg'){
array_push($err,"Veuillez entrer un fichier JPG");
}
if(empty($err)){
$uploaded = #move_uploaded_file($upload['tmp_name'], $target_file);
$this->context->smarty->assign('uploaded', $uploaded);
$this->context->smarty->assign('filename', $filename);
}
$this->json =array(
'uploaded'=>$uploaded,
'err'=>$err,
'id_product'=>$id_product,
'stamp'=>$stamp,
'file_name'=>$filename,
);
echo json_encode($this->json);
exit;
}
And I want to get the value of 'file_name' in my second ajax function:
public function ajaxProcessAddVideo(){
$img_path = json_decode($this->json,true);
$filename = $img_path['file_name'];
$id_lang = Context::getContext()->language->id;
$script = Tools::getValue('script');
$id_product = Tools::getValue('id_product');
$id_group_vid = Tools::getValue('cust_group');
//add qr_code video
$qr_code =$filename;
$err = true;
$insert = false;
$videos = array();
$vid = new MpsVideo();
$vid->id_product = $id_product;
$vid->url = $script;
$vid->cust_group = $id_group_vid;
$vid->date_add = date('Y-m-d H:i:s');
$vid->active = 1;
$vid->qrcode = $qr_code;
$is_existing = Db::getInstance()->getValue("SELECT COUNT(id_mps_video) FROM `ps_mps_video` WHERE id_product=$id_product AND url = '$script'");
if($is_existing==0){
$insert = $vid->save();
$id_group = explode(',',$id_group_vid);
$group_name = array();
foreach($id_group as $k){
$group = new Group($k);
$group_name[] = $group->name[$id_lang];
}
$vid->group_names = implode('<br/>',$group_name);
}
echo json_encode(array(
'err'=>$err,
'video_exists'=>$is_existing,
'insert'=>$insert,
'vid'=>$vid,
));
exit;
}
I don't know how to achieve this but I know its possible. If someone can help understand this, I would be very grateful.
the result of the first function is a json, that result must be read from another file and then passed to your second function. Or else the same function should read that json:
$data = file_get_contents("file/file_json_result.php");
$img_path = json_decode($data, true);

Cannot get data passed to a php file using AJAX

I am trying to pass data back to the server and then use the reply to update the browser page.
My code for a SELECT input is as follows;
<select id ="MatchCaptain" name="MatchCaptain" onchange="findTeleNo(this.value)"
<?php
$MC = $_SESSION["MatchCapt"];
player_load($MC);
?>
>
</select>
The script code is as follows;
<script>
function findTeleNo(that){
alert("I am an alert box!" + that);
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("TeleNo").value = this.responseText;
}
}
};
xhttp.open("GET", "findTeleNo.php?q=" + that, true);
xhttp.send();
</script>
The purpose of the script is to take the value selected in the dropdown (variable "that") and submit it to the php file as variable q.
And the PHP file is as follows;
<?php
$MatchCaptain = $_REQUEST["q"];
$teleNo = "";
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementDB";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM `playerstb` ORDER BY `Surname` ASC, `FirstName` ASC";
$result = mysqli_query($db_handle, $SQL);
$ufullName = split_name($MatchCaptain);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['FirstName'];
$uName = trim($uName);
$Surname = $db_field['Surname'];
$Surname = trim($Surname);
$fullName = $uName." ".$Surname;
if ($fullName == $ufullName )
{
$teleNo = $db_field['TeleNo'];
break;
}
}
}
echo $teleNo;
function split_name($name) {
$name = trim($name);
$last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $name ) );
$ufullName = $first_name." ".$last_name;
return $ufullName;
}
?>
The php file requests the q variable from the url and makes it $MatchCaptain.
This will be a name like Joe Bloggs. The next piece of code connects to a MySQL table to extract players first names surnames and telephone numbers. The first names and surnames are concatenated to form the fullname which is compared with the $MatchCaptainWhen a match is made the variable $teleNo is set to the Telephone Number of that player. The echo statement rerurns the value to the script.
The field id I am trying to update is;
<p><b>Telephone Number: </b> <span id="TeleNo"> <?php echo $_SESSION["TeleNo"]; ?></span></p>
The alert in the script function findTeleNo shows me that I have entered the function but nothing happens after that.
Any help as to how I get this working would be grateful.
I have changed my script to
<script>
function findTeleNo(that){
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "findTeleNo.php?q=" + encodeURIComponent(that), true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
// OK
alert('response:'+xhttp.responseText);
document.getElementById("TeleNo").innerHTML = this.responseText;
// here you can use the result (cli.responseText)
} else {
// not OK
alert('failure!');
}
}
};
};
</script>
The response shown by alert('response:'+xhttp.responseText); is correct and the line of code
document.getElementById("TeleNo").innerHTML = this.responseText;
does print the response to the web page.

Database won't connect, no results returned

So I've got three PHP files, and I'm trying to connect my database through these files. It won't seem to connect, I'm trying to connect it so then my ajax in my javascript file will hopefully work.
BaseClass.php:
<?php
require("Conn.php");
require("MySQLDao.php");
$handle = fopen("php://input", "rb");
$raw_post_data = '';
while (!feof($handle)) {
$raw_post_data .= fread($handle, 8192);
}
fclose($handle);
if (empty($raw_post_data))
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "No Data Recieved";
echo json_encode($returnValue);
return;
}
else
{
$dao = new MySQLDao();
if ($dao->openConnection() == false)
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
echo json_encode($returnValue);
}
else
{
//Decodes data, dont change
$body = json_decode($raw_post_data, true);
$recieved = $body["data"];
//Gets the result of a query
//$result = $dao->MySQLDaoMethodName(parameters);
//Return the result of the query
echo json_encode($result);
}
$dao->closeConnection();
return;
}
?>
When I run this in chrome all it shows is:
{"status":false,"title":"Error","message":"No Data Recieved"}
MySQLDao.php:
<?php
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function getResults($data)
{
$sql = "SELECT room.room_description FROM room WHERE room.room_id = 1";
$result = $this->mysqli->query($sql);
//if (mysql_num_rows($result) == 1) {
// $obj = mysql_fetch_object($result, 'obResults');
//}
echo json_encode($result);
echo($result);
}
}
?>
Nothing shows when I run this in chrome. Even when I put echo statements in some of the functions.
Conn.php:
<?php
class Conn
{
public static $dbhost = "***";
public static $dbname = "***";
public static $dbuser = "***";
public static $dbpass = "";
}
?>
part of my test.html:
function callPHP() {
$.ajax ({
type: "GET",
datatype: "application/json",
url: "MySQLDao.php",
data: { action : 'getResults()' },
//error: function(err){console.log(err)},
success: function(output) {
console.log(output);
}
//error, function(err){console.log(err)}
});
}
I basically just want to be able to write query methods and transport the results from these querys to my js, this is because I have a few graphs in my javascript and I want to get data from the database. All this code doesn't produce any errors I believe but it's just not returning anything back.
All help appreciated! Thanks!

Uncaught Syntax Error. Unexpexcted end of input

I have this javascript file that is calling a php file to return a JSON string. Chrome dev tools is throwing the error at line 10 in the javascript code. I know the error relates to a missing bracket but for the life of my and 3 other people who have looked at it the syntax is correct.
var request = new XMLHttpRequest();
var listings = [];
var json;
var url = "getListing.php";
request.open("GET", url, true);
request.send();
request.onreadystatechange = function(e)
{
if(request.readyState == 4){
json = JSON.parse(request.responseText);
for(var x = 0; x < json.length; x++){
var list = new listingInfo();
list.category = json[x].category;
list.date = json[x].dateListed;
list.description = json[x].description;
list.id = json[x].listingID;
list.title = json[x].title;
list.userID = json[x].userID;
listings.push(list);
}
}
console.log(listings);
}
here is the php file
<?php
session_start();
$con = mysql_connect("localhost", "listAdmin", "hermes");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("GregsList", $con)
or die("Unable to select database:" . mysql_error());
$result = mysql_query("SELECT * FROM Listings WHERE userID = '$_SESSION[userID]' ORDER BY dateListed DESC");
#converts to json
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
#If you want to see if correct json is printing use ---> print json_encode($rows);
return json_encode($rows);
?>
request.readyState == 4 is not enough you should add request.status== 200
In your php script replace return json_encode($rows); with print json_encode($rows);

How to get Json data in ajax after a mysql query

For my bookshop, I started to built a cashdesk script. This is a very simple form, with an ajax dynamic search. This is a script for a local PC, so the script will not be publish on the web.
When I scan the EAN code, I've my form fill with title, author, editor and price. The book is ready to add in the basket.
Now I'm trying to introduce Json in this script : but I don't understand how to get the values of the mysql query in the script, and put them in the correct fields of my cashdesk form.
I've tested the Mysql query and the Json.
The query
<?php
header('Content-Type: text/html; charset=ISO-8859-1');
include('connexion.php');
$connect_db = connect();
$i = 0;
$tmp = array();
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$tmp[$i] = $row;
}
echo json_encode($tmp);
close();
?>
A json exemple :
[{"product_id":"7097","product_name":"Paix pour tous - Livre audio","product_author":"Wayne W. Dyer","product_editor":"Ada","product_price":"20.28"}]
The ajax script
var xhr = null;
function getXhr()
{
if(window.XMLHttpRequest) xhr = new XMLHttpRequest();
else if(window.ActiveXObject)
{
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else
{
alert("Not Working");
xhr = false;
}
}
function ajaxEAN()
{
getXhr();
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var data = '{"product_id": "product_id", "product_name":"product_name", "product_author":"product_author", "product_editor":"product_editor", "product_price":"product_price"}';
oData = JSON.parse( data);
for( var i in oData){
document.getElementById( i).value = oData[i];
}
}
}
xhr.open("POST",'ajaxrecupaddr.php',true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
EAN = document.getElementById("EAN").value;
xhr.send("EAN="+EAN);
}
Thanks for any help !
As far as understand, you simply can't take a JSON from response. If so, than you simply should do:
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200) {
oData = JSON.parse(xhr.responseText);
for(var i = 0; i < oData.length; i++) {
for( var key in oData[i]){
document.getElementById(key).value = oData[i][key];
}
}
}
There, xhr.responseText will return a string with JSON received from server.
Also, few notes:
Instead of
header('Content-Type: text/html; charset=ISO-8859-1');
you should better use:
header('Content-Type: application/json;');
Also, in line below you are opened to SQL Injections:
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");
instead of simply doing WHERE product_EAN = '$_POST[EAN]' you should do, at least, WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "':
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "'");
See more about mysql_real_escape_string. It will correctly escape all potentially dangerous symbols and will save you from errors when you have ' symbol in EAN. Also, read warning shown on a page linked above. You should better change your database extension as MySQL extension is deprecated.

Categories