I have a webpage that displays a list of my local files, and I have a search bar that goes through the list of files and highlights the first match.
However, how can I display the files only when a user searches for a filename. So instead of all the files showing, I'd only like the files that match the search criteria to be returned.
PHP, JavaScript, jQuery is totally an option here if anyone can help in that area.
testexec.php:
<?php
$path = '/var/www/html/'; //get list of files
$files = scandir($path);
//display the links
foreach($files as $file) {
if($file != '.' && $file != '..') {
echo '<div> '.$file.'</div>';
}
}
?>
readfile.php:
<?php
// PHP script to allow the file to be downloaded
$filename = $_GET['file'];
if (file_exists($filename)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;
filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($filename);
exit;
}
?>
//JavaScript for searchbar
function FindNext() {
var str = document.getElementById ("livesearch").value;
if (str == "") {
alert ("Please enter some text to search!");
return;
}
var supported = false;
var found = false;
if (window.find) { // Firefox, Google Chrome, Safari
supported = true;
// if some content is selected, the start position of the search
// will be the end position of the selection
found = window.find (str);
} else {
if (document.selection && document.selection.createRange) { // Internet Explorer, Opera before version 10.5
var textRange = document.selection.createRange ();
if (textRange.findText) { // Internet Explorer
supported = true;
// if some content is selected, the start position of the search
// will be the position after the start position of the selection
if (textRange.text.length > 0) {
textRange.collapse (true);
textRange.move ("character", 1);
}
found = textRange.findText (str);
if (found) {
textRange.select ();
}
}
}
}
if (supported) {
if (!found) {
alert ("The following text was not found:\n" + str);
}
}
else {
alert ("Your browser does not support this example!");
}
}
This is the simplest idea.
Frontend
index.html
$('input').keydown(function(e) {
var str = $(this).val();
alert(str);
$.get("/search.php?query=" + str, function(data) {
$('.result').html(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>File search and download</h3>
<input name="filename" placeholder="file name" class="kw"/>
<div class="result">
</div>
Backend
search.php
<?php
// You need code search file
// after search $files
$str = '';
foreach($files as file) {
$str .= ''.$file.' <br>'
}
return $str;
?>
readfile.php
<?php
// PHP script to allow the file to be downloaded
$filename = $_GET['file'];
if (file_exists($filename)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;
filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($filename);
exit;
}
?>
this really easy. you just need to use event keyup and some code fix
index.php
<input type="text" id="searchbar" placeholder="search file"> <span id="loading" style="display:none;">loading</span>
<div id="result"></div>
<script src="../../vendor/jquery/jquery-3.2.1.min.js"></script>
<script>
$(function(){
$('#searchbar').keyup(function(){//event after user release keyboard
var val = $(this).val();
if(val.length >= 2){//min 2 words to start find
$.ajax({
url: 'search.php',
type: 'POST',
dataType: 'json', //we use json
data: {keyword: val},
beforeSend: function(){
$('#loading').show();
},
success: function(d){
if(d.ok==1){
$('#result').html(d.list);
}else{
alert(d.msg);
}
$('#loading').hide();
},
error: function(d){
alert('error');
$('#loading').hide();
}
});
}
})
});
</script>
search.php
<?php
$path = 'C:/xampp/htdocs/';
$keyword = isset($_POST['keyword']) ? $_POST['keyword'] : '';
$scan = scandir($path);
$result = array('ok'=>0); //prepare output cz we will use json instead text/html
if($scan !== false){
$result['ok']=1;
$list = array();
foreach($scan as $file){
if(is_file($path.$file)){ //only file
if(preg_match('/'.$keyword.'/', $file)) //is file containts keyword?
$list[] = '<div>'.$file.'</div>';
}
}
$result['list'] = count($list) == 0 ? 'no file match': $list;
}else
$result['msg'] = "failed open dir";
echo json_encode($result);
readfile.php
<?php
// PHP script to allow the file to be downloaded
$filename = $_GET['file'];
$path = 'C:/xampp/htdocs/';
$fullPath = $path.$filename; //you need this
if (file_exists($fullPath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fullPath));
readfile($fullPath);
exit;
}
?>
There are many ways to do that.
I would suggest that:
Make your PHP answer a JSON with the files that match a given criteria. So you will ask to the PHP, passing in POST data ou QUERY string the "text" that is being search. It will give you only the files that matches.
In you html file (could be another PHP as well), you will call ajax (you can use jQuery) to the page above everytime user changes the search text. It's good thing to "throttle" (see lodash/underscore library) (wait some time waiting for more key presses).
After receiving the JSON with the files that matches, build dynamically you table (or another way you want).
search.php:
<?php
header('Content-Type: application/json');
$path = '/var/www/html/'; //get list of files
$files = scandir($path);
$search = $_GET['search'];
$links = array();
foreach ($files as $file) {
if($file != '.' && $file != '..' && strpos(strtolower($file), strtolower($search)) !== false) {
array_push($links, array(
"name" => $file,
"url" => "readfile.php?file=" . urlencode($file)
));
}
}
echo json_encode($data);
?>
index.php / index.html
<html>
<head>
<script src="http://code.jquery.com/jquery-2.2.4.min.js">
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js">
</head>
<body>
<input id="searchbox" type="text" placeholder="search for files" />
<div id="results">
</div>
<script>
$(function () {
var searchbox = $("#searchbox");
var results = $("#results");
var doSearch = _.throttle(function () {
var searchtext = searchbox.val();
$.ajax({
type: 'get',
url: 'search.php',
dataType: "json",
data: {
search: searchtext
}
}).done(function (response) {
results.html(response.reduce(function (html, item) {
return html + '<div>' + item.name + '</div>';
}, ''));
});
}, 200);
searchbox.on('keydown', doSearch);
});
</script>
</body>
</html>
Related
This question already has answers here:
Download CSV file using "AJAX"
(6 answers)
Closed 3 years ago.
I have the following problem:
I'm upgrading a working system, so I have to create code that fits in.
I want to create a csv file on a php page and a mysql database. I'm also using Ajax to stay on the same page while running other php-Files. Here are the Code snippets:
PHP/HTML-Page with Button
<div class="btn" id="export">Export</div>
Javascript Ajax
$("#export").click(function() {exportInfos();});
function exportInfos() {
$.ajax({
type: "POST",
url: "functions/exportInfos.php",
data: { searchterm: $("#search").val(), filterbycat: $("#filterbycat").val(), filterbytype: $("#filterbytype").val()},
success: function(response){
console.log("success_export");
},
});
}
PHP-File to create csv(exportInfos.php):
<?php
include ('../../config.php');
$searchterm = $_POST["searchterm"];
$filterbycat = $_POST["filterbycat"];
$filterbytype = $_POST["filterbytype"];
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=export.csv');
$output = fopen("php://output", "w");
$query = "SELECT * FROM database";
$result = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_assoc($result))
{
fputcsv($output, $row);
}
fclose($output);
?>
I'm not sure where the Problem is but in the console I only see that the php script is called and the success_export text from the log, but no file is opened or downloadable. I think the problem could be with the AJAX part because thats the part Im not sure about the most.
The data values in the Ajax part are there to edit the query as soon as i get some output File.
$mysqli is the connection defined in the config file.
I think you need the change download methodology. Maybe it can be as follows.
Static Page :
<!doctype html>
<html lang="en">
<body>
<div class="btn" id="export">Export</div>
</body>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('#export').click(function() {exportInfos();});
function exportInfos() {
$.ajax({
type: 'POST',
url: 'functions/createCSV.php',
data: {
searchterm: $('#search').val(),
filterbycat: $('#filterbycat').val(),
filterbytype: $('#filterbytype').val(),
},
success: function(response) {
if (response.filename != undefined && response.filename.length > 0) {
window.open('functions/downloadCSV.php?filename='+response.filename);
}
},
});
}
</script>
</html>
createCSV :
<?php
include('../../config.php');
$searchterm = $_POST["searchterm"];
$filterbycat = $_POST["filterbycat"];
$filterbytype = $_POST["filterbytype"];
//header('Content-Type: text/csv');
//header('Content-Disposition: attachment; filename=export.csv');
$outputPath = '/path/to/save/outputFile.csv';
$output = fopen($outputPath, "w");
$query = "SELECT * FROM database";
$result = mysqli_query($mysqli, $query);
while ($row = mysqli_fetch_assoc($result)) {
fputcsv($output, $row);
}
fclose($output);
header('Content-Type: application/json');
echo json_encode(
[
"filename" => basename($outputPath),
]
);
downloadCSV :
<?php
if (!empty($_GET['filename'])) {
http_send_status(404);
}
$filepath = "/path/to/save/" . $_GET['filename'];
if (!is_file($filepath) || !is_readable($filepath)) {
http_send_status(404);
}
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=" . $_GET['filename']);
echo file_get_contents($filepath);
Good afternon, i have a form that in determined field it open a window or windows to display a specific PDF. The folder where is the path, it can there is just a PDF or a ZIP file with multiples PDF's inner according to the input filled value.
This is blur() event part on the whole my code that calls the windows and pass the values to the "arquivo.php" and "pdf.php", one is to check if is just a PDF or a ZIP, if was a PDF this return on my form informing that is a PDF just and after open just a window to display, this part is ok
JavaScript/HTML code:
///////////PASS THE VALUES TO "arquivo.php"////////////////
$.post("arquivo.php", {nprocesso: document.getElementById("processo").value}, function(data){
$( "#content3" ).html( data ); /*<-- return in this content if is a PDF or a ZIP(when is a zip it returns how many PDF's there are inner ZIP file too)*/
////////////THIS PART IS TO CREATE JUST A WINDOW OR MULTIPLES WINDOWS PASSING THE VALUES RETURNED IN THE "content3" TO "pdf.php" TO DISPLAY IT/THEM//////////////////
setTimeout(function(){
if(document.getElementById("content3").innerText == "PDF"){
window.open("pdf.php/"+document.getElementById("processo").value, '_blank', "toolbar=yes,scrollbars=yes,resizable=yes,width=800,height=800");
}else{
var QuantPDF = Number(document.getElementById("content3").innerText.slice(Number(document.getElementById("content3").innerText.lastIndexOf(','))+1, document.getElementById("content3").innerText.length));//Number(document.getElementById("content3").innerText.replace(/[^0-9]/g, ""));
var NomesPDFS = []; NomesPDFS = document.getElementById("content3").innerText.slice(3, document.getElementById("content3").innerText.length-2).split(',');
if(QuantPDF > 1){
for(var i = 0; i < QuantPDF; i++){
window.open("pdf.php/"+document.getElementById("processo").value+"/"+NomesPDFS[i], '_blank', "toolbar=yes,scrollbars=yes,resizable=yes,width=800,height=800");
}
}else{
window.open("pdf.php/"+document.getElementById("processo").value, '_blank', "toolbar=yes,scrollbars=yes,resizable=yes,width=800,height=800");
}
}
document.getElementById('closeBtn').click();
}, 1000);
}
This is the "arquivo.php", where check if is just a PDF or a ZIP file, and extract if was a zip
Arquivo.php code:
<?php
session_start();
//////////THIS PART CHECK THAT FILE IS A PDF AND RETURN TO MY JAVASCRIPT CODE/////////
if(file_exists('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'.pdf')){
echo 'PDF';
$_SESSION['file'] = "PDF";
}else{
//////////THIS PART CHECK THAT FILE IS A ZIP AND RETURN TO MY JAVASCRIPT CODE/////////
echo 'ZIP';
$_SESSION['file'] = "ZIP";
$zip = new ZipArchive;
$path = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'.zip';
///////////////////////////////////////////////////////////////////
if($zip->open($path) === true){
//////////THIS PART IT OPENS THE ZIP AND EXTRACT/////////
if(!file_exists('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'])){
mkdir('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'], 0777, true);
}
for($i = 0; $i < $zip->numFiles; $i++){
$zip->extractTo('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'], array($zip->getNameIndex($i)));
$path = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'];
$files = scandir($path); array_shift($files); array_shift($files);
$file = array(); $filename = array();
///////NOW I CATCH THE PDF's NAMES AND THE QUANTITY AND RETURN TO JAVASCRIPT CODE///////
$file[$i] = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'/'.$files[$i];
$filename[$i] = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'/'.$files[$i];
$nomes_pdfs = array();
$nomes_pdfs[$i] = substr(substr($filename[$i], strpos($filename[$i], $_POST['nprocesso'])+26, strlen($filename[$i])), 0, strpos(substr($filename[$i], strpos($filename[$i], $_POST['nprocesso'])+26, strlen($filename[$i])), '.pdf')).',';
echo $nomes_pdfs[$i];
}
$zip->close();
$path = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'];
$files = scandir($path);
array_shift($files); array_shift($files); $_SESSION['quantidade_pdf'] = count($files);
echo $_SESSION['quantidade_pdf'];
}
}
?>
My problem actually is partially on "pdf.php" where the window load with the values returned of the "content3". When is a single PDF, the window display normally, but when is a ZIP file with multiples PDF's, the first PDF display correctcly, but starting in the second and on, it doesn't display. show a this error: "Failed to load PDF document".
pdf.php code:
<?php
header ('Content-type: text/html; charset=utf-8');
if(file_exists('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1).'.pdf') && is_file('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1).'.pdf')){
$processo = substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1);
$file = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$processo.'.pdf';
$filename = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$processo.'.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
#readfile($file);
}else{
/////////////////////HERE IS THE PART WHEN IS A ZIP////////////////////////
///////*This part it's only to check if the folder extract exists*/////////
function folder_exist($folder){ $path = realpath($folder); return ($path !== false AND is_dir($path)) ? $path : false; }
chdir('//dsbimrj16/Vinculacao_Cadastro_Gestor/');
$folder = '/'.substr(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), 0, strpos(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), '/')).'/';
if(FALSE !== ($path = folder_exist($folder))){
/////*Here start the part where the code catch the PDF's and display*/////
$pasta = substr(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), 0, strpos(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), '/'));
$processo = substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1);
$file = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$pasta.'/'.$processo.'.pdf';
$filename = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$pasta.'/'.$processo.'.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
#readfile($file);
}else{
die('<h2 style="background-color:#FA5858"><center>Não foi encontrado a inicial do processo. Verifique se o mesmo encontra-se na pasta.</center></h2>');
}
}
?>
What i'm doing wrong ? I've already checked the folder, the file is in and the name and the path is the same that the code are putting to display
I'm trying to write a script to download a file. But when I click "Download" nothing happens. I'm using Laravel for my project. This is the function:
public function downloadUserFile(){
$userid = Auth::id();
$result = $_POST['filename'];
$query = File::where('filename', $result)->where('userid', $userid)->get();
foreach($query as $queryResult){
$mimeType = $queryResult->mimetype;
$filepath = $queryResult->filePath;
$filesize = $queryResult->filesize;
if (file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: ' . $mimeType);
header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . $filesize);
ob_clean();
flush();
readfile($filepath);
exit;
}
}
}
And the ajax:
if(key === "download") {
var classElements = document.querySelectorAll("tr.ui-selected td.filename");
var csrf = $('input[name=_token]').val();
for(var x = 0;x < classElements.length;x++){
var result;
result = classElements[x].innerHTML;
$.ajax({
async: true,
method: 'POST',
url: '../public/downloadfile',
data: { filename: result, "_token": csrf }
});
};
}
The ajax response and the PHP don't give me errors and I can't understand why nothing actually happens. What could be the problem?
I have some files on my PHP server inside uploads folder. My problem is the following: I want to send a JSON asynchronous request from my client as to choose one of these files and create with this an image element as to display it in the browser.
JS code
var file_name="test.jpg";
$.ajax({
method:"POST",
dataType:"json",
url:"retrieve_photo.php",
data:{name:file_name},
success: function(data) {
var new_thumb = document.createElement("img");
document.getElementById('dragarea').appendChild(new_thumb);
...
}
})
PHP code (retrieve_photo.php):
<?php
$ds = DIRECTORY_SEPARATOR;
$storeFolder="uploads";
$file_name=$_POST[name];
$files = glob($storeFolder.$ds.$file_name);
if ( false!==$files ) {
....
}
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($result);
?>
I do not know what to write as $result feeds data the right way. I 've tried
$result=readfile($storeFolder.$ds.$file_name);
but maybe not correctly.As to conclude I want to use data as to display an image to my browser.
Thank you
Maybe will be better do something like that?:
var image = new Image();
image.src = "blabla";
$(image).on('load', function(){
//do what you want
})
Why do you even use AJAX? Maybe i don't understand)
Since you don't use algorithm or functions in your PHP, you can do everything by Javascript / Jquery :
var img = $("<img />").attr('src', 'uploads/'+ file_name)
.on('load', function() {
if (!this.complete || typeof this.naturalWidth == "undefined") {
alert('Image not found');
} else {
$("#dragarea").append(img);
}
});
document.getElementByI('dragarea').appendChild(new_thumb);
Мaybe you mean? document.getElementById('dragarea').appendChild(new_thumb);
document.getElementById('dragarea').appendChild(new_thumb);
try this in your retrieve_photo.php
$filename = "test.jpg";
//Make sure $filename contains the appropriate path of the photo
$size = getimagesize($filename);
$file = $filename;
if ($size) {
header("Content-type:". $size['mime']);
header("Content-Length: " . filesize($file));
header("Content-Disposition: attachment; filename=$filename");
header('Content-Transfer-Encoding: base64');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Type: application/force-download");
readfile($file);
exit;
}
I am developing a smart tv app that plays live streams. App itself works fine, when i provide a valid xml playlist to it.
But when i use php to generate xml file (wich also generates fine), it doesnt work.
I get an error:
TypeError: 'null' is not an object (evaluating 'this.XHRObj.responseXML.documentElement')
Here is my php file that generates videoList.xml, it works 100%.
In short words, this script checks if MAC address in database, and if it is, then it writes videoList.xml with walid live streaming links.
SamsungAPI.php
<?php
$MAC = $_GET['MAC'];
require_once('../config.php');
//Remove brackets form array
$_INFO = preg_replace('/[{}]/', '', $_INFO);
$mysqli = new mysqli($_INFO['host'], $_INFO['db_user'], $_INFO['db_pass'], $_INFO['db_name']);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql="SELECT * FROM users WHERE admin_notes = '$MAC' ";
$rs=$mysqli->query($sql);
$rows=mysqli_num_rows($rs);
if ($rows == 1) {
//MAC FOUND
$row = mysqli_fetch_array($rs);
$username = $row['username'];
$password = $row['password'];
$file = "videoList.xml";
$txt_file = file_get_contents('http://' . $_SERVER['HTTP_HOST'] . '/get.php?type=starlivev3&username=' . $username . '&password=' . $password . '&output=hls');
$rows = explode("\n", $txt_file);
if(empty($rows[count($rows)-1])) {
unset($rows[count($rows)-1]);
$rows=array_map('trim',$rows);
}
$handle = fopen($file, "w+") or die('Could not open file');
fwrite($handle, "<?xml version=\"1.0\"?>"."\n");
fwrite($handle, "<rss version=\"2.0\">"."\n");
fwrite($handle, "<channel>"."\n");
foreach($rows as $row => $data)
{
//get row data
$row_data = explode(',', $data);
//replace _ with spaces
$row_data[0] = str_replace('_', ' ', $row_data[0]);
//generate playlist content
fwrite($handle, "<item>"."\n");
fwrite($handle, "<title>{$row_data[0]}</title>"."\n");
fwrite($handle, "<link>{$row_data[1]}</link>"."\n");
fwrite($handle, "<description> Reserved for EPG </description>"."\n");
fwrite($handle, "</item>"."\n");
}
fwrite($handle, "</channel>"."\n");
fwrite($handle, "</rss>");
fclose($handle);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
//MAC NOT FOUND
echo "MAC NOT FOUND";
}
mysqli_close($mysqli); // Closing Connection
?>
Then in samsung smart tv videoplayer app, i have xml parser like this:
Server.js
var Server =
{
/* Callback function to be set by client */
dataReceivedCallback : null,
XHRObj : null,
url : "http://myvalidhost.com/samsungAPI.php?MAC=02000027000b"
}
Server.init = function()
{
var success = true;
if (this.XHRObj)
{
this.XHRObj.destroy(); // Save memory
this.XHRObj = null;
}
return success;
}
Server.fetchVideoList = function()
{
if (this.XHRObj == null)
{
this.XHRObj = new XMLHttpRequest();
}
if (this.XHRObj)
{
this.XHRObj.onreadystatechange = function()
{
if (Server.XHRObj.readyState == 4)
{
Server.createVideoList();
}
}
this.XHRObj.open("GET", this.url, true);
this.XHRObj.send(null);
}
else
{
alert("Failed to create XHR");
}
}
Server.createVideoList = function()
{
if (this.XHRObj.status != 200)
{
Display.status("XML Server Error " + this.XHRObj.status);
}
else
{
var xmlElement = this.XHRObj.responseXML.documentElement;
if (!xmlElement)
{
alert("Failed to get valid XML");
}
else
{
// Parse RSS
// Get all "item" elements
var items = xmlElement.getElementsByTagName("item");
var videoNames = [ ];
var videoURLs = [ ];
var videoDescriptions = [ ];
for (var index = 0; index < items.length; index++)
{
var titleElement = items[index].getElementsByTagName("title")[0];
var descriptionElement = items[index].getElementsByTagName("description")[0];
var linkElement = items[index].getElementsByTagName("link")[0];
if (titleElement && descriptionElement && linkElement)
{
videoNames[index] = titleElement.firstChild.data;
if(linkElement.firstChild.data.substring(0,4) !="http"){
alert("asdasdasd "+linkElement.firstChild.data.substring(0,4));
var rootPath = window.location.href.substring(0, location.href.lastIndexOf("/")+1);
var Abs_path = unescape(rootPath).split("file://")[1]+linkElement.firstChild.data;
videoURLs[index] = Abs_path;
}
else{
videoURLs[index] = linkElement.firstChild.data;
}
videoDescriptions[index] = descriptionElement.firstChild.data;
}
}
Data.setVideoNames(videoNames);
Data.setVideoURLs(videoURLs);
Data.setVideoDescriptions(videoDescriptions);
if (this.dataReceivedCallback)
{
this.dataReceivedCallback(); /* Notify all data is received and stored */
}
}
}
}
Does anyone have any idea why doesnt it accept my generated xml file?
Regards
M
I figured it out, in php headers content type was wrong.
Changed
header('Content-Type: application/octet-stream');
to
header('Content-Type: application/xml');
Now it works perfect!