Trying to open pdf file in new browser window - javascript

Cant get the PDF open in new browser window. There is a php code I use to set the PDF and open it!
<?php
if (($_POST['name_check']=="in") || ($_GET['type']=="in")){
header('Content-Type: application/pdf; charset=windows-1257');
header("Content-Disposition: inline; ");
header('Accept-Ranges: bytes');
$file_type = "in";
$flag = 0;
}
else{
header('Content-Type: application/pdf; charset=windows-1257');
header("Content-Disposition: inline;");
header('Accept-Ranges: bytes');
$file_type = "out";
$flag = 1;
}
?>
<?php session_start();
if (((isset($_SESSION['UserID'])) and (isset($_SESSION['Pin_code']))) and (isset($_COOKIE['CookieMy']))){
$form='<form action="login.php" method="get" style="width: 900px;margin: -1px auto -57px auto;" class="exit_but">
<input type="submit" name="exit" value="EXIT" style="margin-left: 800px;"></form>';
echo $form;
} else {
header("Location: login.php");
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style1.css" />
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
idleTimer = null;
idleState = false;
idleWait = 1200000;
var theElement = document.getElementById("elem");
$(document).ready(function(){
$(document).bind('mousemove keydown scroll click', function(){
clearTimeout(idleTimer);
idleState = false;
idleTimer = setTimeout(function(){
idleState = true;
window.location.href = "login.php"
}, idleWait);
});
});
</script>
</head>
<body>
<?php
function last(){
if (($_POST['name_check'])=="in"){
$type = '"pdf-in"';
$flag=0;
echo "<script>window.flag_in=false;</script>";
}
else{
$type = '"pdf-out"';
$flag=1;
echo "<script>window.flag_in=true;</script>";
}
if (!isset($aircraftid)){
$aircraftid = $_POST['hostcountry'];
$aircraftid='"'.$aircraftid.'"';
}
if (!isset($date)){
$date = $_POST['per1'];
$date=date($date);
}
include ("config.php");
//////////////////////////////////////////
$mysqli = new mysqli($dbconf['host'], $dbconf['user'], $dbconf['password'], $dbconf['dbname']);
if ($mysqli->connect_errno) {
echo "MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$query = mysqli_multi_query( $mysqli, "SELECT dn_get_flight_file_name($date,$aircraftid,$type);") or die( mysqli_error( $mysqli ) );
if( $query )
{
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
$PDF_File_Name=$row[0];
}
$result->free();
}
}
///////////////////////////////////
mysqli_close( $mysqli );
$qwerty=$PDF_File_Name;
///////////////////////////////////
$ftp .='ftp://'.$ftp_user.':'.$ftp_pwd.'#'.$ftp_server;
if($flag==0){
$file_path_ftp = $ftp_path_pdf_in.$qwerty;
$file_path_local = "in/".$qwerty;
}
else{
$file_path_ftp = $ftp_path_pdf_out.$qwerty;
$file_path_local = "out/".$qwerty;
}
$file_path_ftp = trim($file_path_ftp);
$file_path_local = trim($file_path_local);
$file = $file_path_local;
$current_content = file_get_contents($ftp.$file_path_ftp);
file_put_contents($file, $current_content);
$qwerty=$file_path_local;
$date2 = $_POST['date'];
$num = $_POST['num'];
return array ($qwerty,$date2,$num);
}
if (isset($_GET['name'])){
$qwerty=$_GET['name'];
}
else {
list ($qwerty,$date2,$num) = last();
}
if (!file_exists($qwerty)) {
$file_path_local=$qwerty;
$slash_occur = stripos($qwerty, '/');
$file_type = substr($qwerty, 0, $slash_occur);
$file_name = substr($qwerty, $slash_occur+1);
if($file_type=='pdf-in'){
$file_path_ftp = $ftp_path_pdf_in.$file_name;
}
else{
$file_path_ftp = $ftp_path_pdf_out.$file_name;
}
echo "<h2>file_type = ".$file_type.", file_name = ".$file_name."</h2>";
$ftp .='ftp://'.$ftp_user.':'.$ftp_pwd.'#'.$ftp_server;
$current_content = file_get_contents($ftp.$file_path_ftp);
file_put_contents($qwerty, $current_content);
}
if (isset($_GET['date'])){
$date2=$_GET['date'];
}
if (isset($_GET['num'])){
$num=$_GET['num'];
}
?>
<?php
if (($_POST['name_check']=="in") || ($_GET['type']=="in")){
#readfile($ftp_path_pdf_in.$qwerty);
} else {
#readfile($ftp_path_pdf_out.$qwerty);
}
?>
</body>
</html>
I'm trying to open PDF file in the new (Chrome) browser window.
document.action =window.open('date_PDF.php', 'newWindow', 'width=1000, height=1000');
Error is Failed to load PDF document.
When I do document.getElementById("edit").action ="date_PDF.php"; it opens pdf.
I get the PDF file from the ftp server and than display it on date_PDF.php #readfile($ftp_path_pdf_in.$qwerty);
Where is the problem?
Thank you!

You have not defined the name_check html element. Also you have not passed the 'type' parameter in the url. I think the name_check and type are present on the page from where you open the pdf file.
If you want to open the pdf file using window.open then you should use the url: date_PDF.php?type=in
After the readfile statement you should have an exit statement. See the example for the readline function: http://php.net/manual/en/function.readfile.php#refsect1-function.readfile-examples

Related

JavaScript doesn't run after PHP header call

I'm trying to redirect using PHP header/even a JavaScript work around call inside php to my clients.php webpage.
The problem is that PHP header/the work around loads the webpage flawlessly but the Javascript still isn't ran.
Additional notes is that after the header or even Javascript redirect to the page, trying to refresh the page won't have the Javascript load. Only switching between a webpage and coming back to clients.php does the Javascript actually run.
I have also tried this: JavaScript not loading after PHP header() redirect
but to no avail.
Here are parts of my code segmented, just because its quite lengthy.
clients.php
<!-- Bootstrap core JavaScript-->
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Page level plugin JavaScript-->
<script src="vendor/chart.js/Chart.min.js"></script>
<script src="vendor/datatables/jquery.dataTables.js"></script>
<script src="vendor/datatables/dataTables.bootstrap4.js"></script>
<!-- Custom scripts for all pages-->
<script src="js/sb-admin.min.js"></script>
<!-- Custom scripts for this page-->
<script src="js/sb-admin-datatables.min.js"></script>
<script src="js/sb-admin-charts.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" ty pe="text/javascript"></script>
<link href="../../css/toastr.css" rel="stylesheet"/>
<script src="../../js/toastr.js"></script>
<script type="text/javascript">
var tmp = "<?php $tmp = $_SESSION['message_success']; echo "$tmp"; ?>";
alert(tmp + " h");
$( document ).ready(function() {
<?php
if($_SESSION['sysLogin'] == "success") {
$_SESSION['sysLogin'] = "";
$user = $_SESSION['user'];
echo "toastr.success('Welcome $user', 'User has logged in');";
}
if($_SESSION['message_success'] != "") {
$msg = $_SESSION['message_success'];
$_SESSION['message_success'] = "";
echo "toastr.success('$msg', 'Success!');";
}
if($_SESSION['message_error'] != "") {
$msg = $_SESSION['message_error'];
$_SESSION['message_error'] = "";
echo "toastr.error('$msg', 'Error!');";
}
if($_SESSION['message_warning'] != "") {
$msg = $_SESSION['message_warning'];
$_SESSION['message_warning'] = "";
echo "toastr.warning('$msg', 'Warning!');";
}
?>
});
</script>
</div>
</body>
</html>
script.php
if($update_statement) {
$_SESSION['message_success'] = "$_membername's Careplan has been successfully updated.";
echo "<script type='text/javascript'>window.location.href = '../clients.php';</script>";
//header("Location:". $redirect);
//exit();
}
Note that clients.php and script.php are not in the same file.
Per Riggs request
<?php
session_start();
$message="";
if(isset($_POST["login"])) {
$redirect = NULL;
if($_POST['redirect'] != '') {
$redirect = $_POST['redirect'];
}
if(empty($_POST['username']) || empty($_POST['password'])) {
$message = "Both fields must be filled out.";
$_SESSION['sysLogin'] = "$message";
header("location: ../login.php?redirect=" . urlencode($redirect));
} else {
require('server_connection.inc');
$connection = connect_to_db(DB_SERVER, DB_UN, DB_PWD, DB_NAME);
$user=mysqli_real_escape_string($connection, $_POST['username']);
$pass=mysqli_real_escape_string($connection, $_POST['password']);
$statement = "select * from Credentials where UserName='$user' AND Password='$pass';";
$result = $connection->query($statement);
if($result->num_rows == 1) {
// lets determine the type of user that logged in
// if not employee but CEO, Manager, ETC, its an Admin
$employeeid = ($result->fetch_assoc())["EmployeeID"];
$check = "select Employees.Position, Employees.Name, Employees.ID from Credentials, Employees where (Credentials.EmployeeID = Employees.ID) AND Employees.ID = '$employeeid';";
$result_two = $connection->query($check);
if($result->num_rows == 1) {
$the_row = $result_two->fetch_assoc();
if($the_row["Position"] == "Employee") {
$name = $the_row["Name"];
$the_id = $the_row['ID'];
$_SESSION['logon'] = true;
$_SESSION['user'] = "$name";
$_SESSION['type'] = "employee";
$_SESSION['sysLogin'] = "success";
$_SESSION['user_id'] = $the_id;
mysqli_close($conection);
if($redirect) {
header("Location:". $redirect);
} else {
header("location: ../index.php");
}
exit();
} else if($the_row["Position"] == "CEO" || $the_row["Position"] == "Manager") {
$name = $the_row["Name"];
$the_id = $the_row['ID'];
$_SESSION['logon'] = true;
$_SESSION['user'] = "$name";
$_SESSION['type'] = "admin";
$_SESSION['sysLogin'] = "success";
$_SESSION['user_id'] = $the_id;
mysqli_close($conection);
if($redirect) {
header("Location:". $redirect);
} else {
header("location: ../index.php");
}
exit();
}
} else {
$message = "Unable to Parse Employee. Please contact your sites Administrator.";
$_SESSION['sysLogin'] = "$message";
mysqli_close($conection);
header("location: ../login.php?redirect=" . urlencode($redirect));
}
} else if($result->num_rows == 0){
$message = "Incorrect username or password";
$_SESSION['sysLogin'] = "$message";
mysqli_close($conection);
header("location: ../login.php?redirect=" . urlencode($redirect));
} else {
$message = "Database Login Error. Too many retrieved accounts. Please contact your sites Administrator.";
$_SESSION['sysLogin'] = "$message";
mysqli_close($conection);
header("location: ../login.php?redirect=" . urlencode($redirect));
}
}
}
function write_to_log($message) {
$file = fopen("logfile.txt", "w") or die("Unable to open file!");
fwrite($file, "$message\n");
fclose($file);
}
function connect_to_db($server, $username, $pwd, $dbname) {
$conn = mysqli_connect($server, $username, $pwd);
if(!$conn) {
echo "" . mysqli_error($conn);
exit;
}
$dbh = mysqli_select_db($conn, $dbname);
if(!$dbh) {
echo "" . mysqli_error($conn);
exit;
}
return $conn;
}
?>
This script merely links session while also checking for the login validity of the user
The message passing does indeed work with headers to another file 'dashboard.php' but redirecting from script.php to dashboard.php doesn't yield the message, thus an implication still arises.
The tmp JavaScript variable is not being defined since you haven't started the session. Include session_start(); at the top of your code.
<?php session_start(); ?>
<!-- Bootstrap core JavaScript-->
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Page level plugin JavaScript-->
<script src="vendor/chart.js/Chart.min.js"></script>
<script src="vendor/datatables/jquery.dataTables.js"></script>
<script src="vendor/datatables/dataTables.bootstrap4.js"></script>
<!-- Custom scripts for all pages-->
<script src="js/sb-admin.min.js"></script>
<!-- Custom scripts for this page-->
<script src="js/sb-admin-datatables.min.js"></script>
<script src="js/sb-admin-charts.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" ty pe="text/javascript"></script>
<link href="../../css/toastr.css" rel="stylesheet"/>
<script src="../../js/toastr.js"></script>
<script type="text/javascript">
var tmp = "<?php $tmp = $_SESSION['message_success']; echo "$tmp"; ?>";
alert(tmp + " h");
$( document ).ready(function() {
<?php
if($_SESSION['sysLogin'] == "success") {
$_SESSION['sysLogin'] = "";
$user = $_SESSION['user'];
echo "toastr.success('Welcome $user', 'User has logged in');";
}
if($_SESSION['message_success'] != "") {
$msg = $_SESSION['message_success'];
$_SESSION['message_success'] = "";
echo "toastr.success('$msg', 'Success!');";
}
if($_SESSION['message_error'] != "") {
$msg = $_SESSION['message_error'];
$_SESSION['message_error'] = "";
echo "toastr.error('$msg', 'Error!');";
}
if($_SESSION['message_warning'] != "") {
$msg = $_SESSION['message_warning'];
$_SESSION['message_warning'] = "";
echo "toastr.warning('$msg', 'Warning!');";
}
?>
});
</script>
</div>
</body>
</html>
To my surprise, the issue wasn't with the Javascript at all nor positioning like the thread posted suggested. Rather the issue seemed to have been with my PHP and calling $_membersname.
For advice to trouble shoot this later on, make sure no errors are outputted, even if PHP doesn't find any. This is from a variable that hasn't be declared.

Call data back from AJAX

I have a script which saves canvas PNGs to a directory and I need the URL to save on the server.
When I submit, the image saves but the server remains empty. I am trying to return error messages but I am receiving nothing.
JAVASCRIPT:
function doodleSave() {
var drawing = document.getElementById("doodle-canvas");
var drawingString = drawing.toDataURL("image/png");
var postData = "canvasData="+drawingString;
var ajax = new XMLHttpRequest();
ajax.open("POST", 'http://www.website.com/php/doodleSave.php', true);
ajax.onreadystatechange= function() {
if (ajax.readyState === 4) //If it ran smoothly
{$("#doodle-submit-button").html("...");}
};
ajax.send(postData);
ajax.success(function(data) {
{$("#doodle-submit-button").html(""+data+"");}
});
}
PHP:
<?php
session_start();
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
$rawImage = $GLOBALS['HTTP_RAW_POST_DATA'];
$removeHeaders = substr($rawImage, strpos($rawImage, ",")+1);
$url = md5(uniqid(rand(), true));
$decode = base64_decode($removeHeaders);
$fopen = fopen('../images/external/doodles/'.$url.'.png', 'wb');
fwrite($fopen, $decode);
fclose($fopen);
//ADD POST TO DATABASE WITH USER'S ID
/* AUTOMATED VARIABLES */
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = 'images/external/doodles/'.$url;
try
{
$stmt = $pdo->prepare("INSERT INTO `(table name)` (unique_user_id, unique_post_id, nature, image_url, timestamp) VALUES(:unique_user_id, :unique_post_id, :nature, :image_url, :timestamp)");
$stmt->bindParam(":unique_user_id",$profile_unique_user_id);
$stmt->bindParam(":unique_post_id",$unique_post_id);
$stmt->bindParam(":nature",$nature);
$stmt->bindParam(":image_url",$imageUrl);
$stmt->bindParam(":timestamp",$timestamp);
if($stmt->execute())
{
echo "uploaded";
}
else
{
echo "Could not upload";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>

PHP file upload - Not checking the file size

I'm trying to make a file upload form from two days but cant seem to get this to work. My code is checking the extension of the file but not checking the file size. I googled, tried different methods but unable to get this to work. Can someone help?
Here's the code -
<?php
if(isset($_POST['carsubmit']))
{
foreach($_POST as $key=>$val)
${$key}=addslashes($val);
$allowed_filetypes = array('.jpg','.gif','.bmp','.png');
$max_filesize = 2097152;
$upload_path = "resumes/";
$filename = $_FILES['attachresume']['name'];
$file_tmp =$_FILES['attachresume']['tmp_name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
$cardupcheck = "select * from `careers` where `email` = '$email'";
$cardupresult = mysql_query($cardupcheck);
if(mysql_num_rows($cardupresult)==1)
{
?>
<script type="text/javascript">
notification('You have already sent us!','error');
</script>
<?php
}
else
{
if(!in_array($ext,$allowed_filetypes)){
?>
<script type="text/javascript">
notification('Please check the file extension. Only jpg, png and gif are allowed!','error');
</script>
<?php
}
else if($file_tmp > $max_filesize){
?>
<script type="text/javascript">
notification('too large!','error');
</script>
<?php
}
else
{
move_uploaded_file($file_tmp,"resumes/".$filename);
$carquery = "INSERT INTO `careers` (`name`, `email`, `phone`, `aoi`, `qual`, `resume`) VALUES ('$name', '$email', '$phone', '$aoi', '$qual', '$filename')";
$carresult = mysql_query($carquery);
if($carresult)
{
?>
<script type="text/javascript">
notification('Thank you! We will get back to you soon!','success');
</script>
<?php
}
else
{
?>
<script type="text/javascript">
notification('There was an error. Please try after some time!','error');
</script>
<?php
}
}
}
}
?>
You are comparing file size with the file name. Get the size of the uploaded file by $_FILES["attachresume"]["size"].Use this code instead
<?php
if(isset($_POST['carsubmit']))
{
foreach($_POST as $key=>$val)
${$key}=addslashes($val);
$allowed_filetypes = array('.jpg','.gif','.bmp','.png');
$max_filesize = 2097152;
$upload_path = "resumes/";
$filename = $_FILES['attachresume']['name'];
$file_tmp =$_FILES['attachresume']['tmp_name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
$file_size = $_FILES["attachresume"]["size"]; // Here is the size of the uploaded file
$cardupcheck = "select * from `careers` where `email` = '$email'";
$cardupresult = mysql_query($cardupcheck);
if(mysql_num_rows($cardupresult)==1)
{
?>
<script type="text/javascript">
notification('You have already sent us!','error');
</script>
<?php
}
else
{
if(!in_array($ext,$allowed_filetypes)){
?>
<script type="text/javascript">
notification('Please check the file extension. Only jpg, png and gif are allowed!','error');
</script>
<?php
}
else if($file_size > $max_filesize){
?>
<script type="text/javascript">
notification('too large!','error');
</script>
<?php
}
else
{
move_uploaded_file($file_tmp,"resumes/".$filename);
$carquery = "INSERT INTO `careers` (`name`, `email`, `phone`, `aoi`, `qual`, `resume`) VALUES ('$name', '$email', '$phone', '$aoi', '$qual', '$filename')";
$carresult = mysql_query($carquery);
if($carresult)
{
?>
<script type="text/javascript">
notification('Thank you! We will get back to you soon!','success');
</script>
<?php
}
else
{
?>
<script type="text/javascript">
notification('There was an error. Please try after some time!','error');
</script>
<?php
}
}
}
}
?>
Hope this helps you
This one worked -
else if(($_FILES['attachresume']['size'] >= $max_filesize) || ($_FILES["attachresume"]["size"] == 0))

Providing php generated xml file to javascript parser

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!

AJAX, jQuery, javascript for a chatroom

So I was following a tutorial and I came across the current problem. This is my first time using the ajax method. I copied and saved jQuery version 1.7.2.min.js in a folder. My php code seems to be working fine, the only thing that seems off is the code for the ajax part.
This code is in a folder called "includes"
<div id="messages">
<!--Javascript-->
<script type= "text/javascript" src= "script/jquery-1.7.2.min.js"></script>
<script type= "text/javascript" src= "script/auto_chat.js"></script>
</div><!-- Messages -->
This is the javascript in a folder called "script" named auto_chat
$(document).ready(function() {
var interval = setInterval(function() {
$.ajax({
url: 'script/Chat.php' ,
success: function(data) {
$('#messages').html(data);
}
});
}, 1000);
});
There is a file called Chat.php containing code that links to the database.
When it runs it should show all the messages inside of the database. Instead it gives me blank and not even errors. Can someone tell me whats wrong with my method?
This is the my Chat.php
<?php
require('../includes/database/connect.db.php')
function get_msg(){
$query = "SELECT `Sender`,`Message` FROM `chat`.`chat` ORDER BY `Msg_ID` DESC";
$run = mysql_query($query);
$messages = array();
while($message = mysql_fetch_assoc($run)){
$messages[] = array('sender' => $message['Sender'],
'message' => $message['Message']);
}
return $messages;
}
function send_msg($sender, $message) {
if(!empty($sender) && !empty($message)) {
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO `chat` . `chat` VALUES (null,'{$sender}','$message')";
if ($run = mysql_query($query)){
return true;
}else{
return false;
}
}else {
return false;
}
}
if(isset($_POST['send'])){
if(send_msg($_POST['sender'],$_POST['message'])){
echo 'Message Sent';
}else{
echo 'Message Failed to sent';
}
}
$messages = get_msg();
foreach($messages as $message) {
echo '<strong>' . $message['sender'] .' Sent</strong><br />';
echo $message['message']. '<br /><br />';
}
?>
And this is all of my index.php
<!DOCTYPE html>
<?php
require('includes/core.inc.php');
function get_msg(){
$query = "SELECT `Sender`,`Message` FROM `chat`.`chat` ORDER BY `Msg_ID` DESC";
$run = mysql_query($query);
$messages = array();
while($message = mysql_fetch_assoc($run)){
$messages[] = array('sender' => $message['Sender'],
'message' => $message['Message']);
}
return $messages;
}
function send_msg($sender, $message) {
if(!empty($sender) && !empty($message)) {
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO `chat` . `chat` VALUES (null,'{$sender}','$message')";
if ($run = mysql_query($query)){
return true;
}else{
return false;
}
}else {
return false;
}
}
if(isset($_POST['send'])){
if(send_msg($_POST['sender'],$_POST['message'])){
echo 'Message Sent';
}else{
echo 'Message Failed to sent';
}
}
?>
<html lang = "en">
<head>
<!--Page TItle --!>
<title>Chat Application </title>
<link type="text/css" rel= "stylesheet" href= "includes/main.css" />
</head>
<body>
<div id="input">
<form action = "index.php" method = "post">
<label>Enter Name:<input type = "text" name = "sender"/></label>
<label>Enter Message:<input type = "text" name = "message"/></label><br />
<input type = "submit" name = "send" value = "Send Message"/>
</form>
</div>
<div id="messages">
<?php
$messages = get_msg();
foreach($messages as $message) {
echo '<strong>' . $message['sender'] .' Sent</strong><br />';
echo $message['message']. '<br /><br />';
}
?>
<!--Javascript-->
<script type= "text/javascript" src= "script/jquery-1.7.2.min.js"></script>
<script type= "text/javascript" src= "script/auto_chat.js"></script>
</div><!-- Messages -->
</body>
</html>
After a lot of trial and error, we found out that the problem was a simple missing semicolon on chat.php:
require('../includes/database/connect.db.php');
:)

Categories

Resources