jQuery load PHP that display flash content - javascript

What my php side does is load data use 'id' from database, and then show the raw data of swf files.
The code of php like this:
<?php
if(isset($_GET['id']))
{
include ('database.php');
$record = mysql_query("SELECT `Flash`, `FlashBlob` FROM `information` WHERE `id` = '". $_GET['id'] ."'; ", $link);
$swf = mysql_fetch_array($record);
mysql_close($link);
header("Content-type: " . $swf['Flash']);
echo $swf['FlashBlob'];
exit;
}
So if I just load the php in the web link, it goes well( the whole php page will show the flash I stored in database).
In my main page, I want to load the page into my div($("#gameArea")), I have tried:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", 'api/swfInfo.php?id=' + id,true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('gameArea').innerHTML=xmlhttp.responseText;
}
}
but the result is it load only raw data( binary data) not the flash(swf file to be shown), what should I do?
I even not sure whether I should find a flash plugin for my flash or not
because I put my flash(swf file) in the database for some reason......
Please help me for the direction, thanks in advance!

Your overcomplicating the problem. If in-fact your swfInfo.php is outputting the swf file's bytes with a content type of application/x-shockwave-flash all you need to do is set the data attribute of your <object> tag to that URL.
<object type="application/x-shockwave-flash" data="api/swfInfo.php?id=7">
<param /> <!-- parameters -->
</object>
I would also recommend a content-length declaration to ensure your connection closes properly when loading files this way.
header('Content-length: ' . mb_strlen($swf['FlashBlob']));
header('Connection: close');

Try the following:
header('Content-Type: application/x-shockwave-flash');
header("Content-Disposition:attachment; filename="test.swf");
My questions are:
What is $swf['Flash'] ? Maybe there is the error?
Have you tried your script with a file_read_content() just for debugging reasons?

Related

Failed to Send data with external file.js to php using XMLHttpRequest()

put the javascript code directly in the HTML page, it does work. Howcome it does not work if I reference the script using the src attribute on the script
This is my HTML page:
<html>
<head></head>
<body>
<script src="file.js"></script>
</body>
</html>
I can not get the following javascript code to send data to a PHP page:
this is inside file.js
var http = new XMLHttpRequest();
var url = 'server.php';
var params = 'a=use&b=12345678';
http.open('POST', url, true); // error javascript stop always here
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200)
{ alert(http.responseText); } }
http.send(params);
and this is inside server.php:
<?php
$username = $_POST['a'];
$password = $_POST['b'];
echo 'username :' . $username;
?>
When I put the javascript code directly in the HTML page, it does work. Howcome it does not work if I reference the script using the src attribute on the script tag?
for example when i put the file.js script in online compiler like 'playcode.io' it does not work
It doesn't matter whether you put the javascript code directly in the HTML page or add it to the script using the src attribute on the script. The problem is, you aren't setting a request header with setRequestHeader(). Add the following line of code just after http.open(), but before http.send() and it'll definitely work:
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
The application/x-www-form-urlencoded format provides a way to encode name-value pairs.

PHP Video Stream Seekbar Unusable in Chrome

This is somewhat related to my other PHP video streaming post, but this time the issue is that the seekbar for the videos do not work in Chrome.
I have found several different posts about it here at Stack Overflow, but none of them have resolved the issue. I would link all of them, but I can't seem to find the same posts I found yesterday.
I am going to list two versions of the PHP code. I should also point out what exactly I'm doing before the PHP loads the video data. On an HTML page, I have a <video> tag without <source> tags. I use Javascript to make an AJAX call to a PHP file that has the source tags. The source tags themselves don't contain direct links to the video source files. Instead, they reference yet another PHP file that loads the data.
Top level HTML For Video. Super simple.
<video id="showvideo" height="540" width="864" controls></video>
Now for the AJAX call
function showVideo() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("showvideo").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/firstphpfile.php", true);
xmlhttp.send();
}
The Javascript function loads when the page loads.
Here's the contents of firstphpfile.php
<?php
echo "
<source src=\"http://example.com/video1.php?type=stuff.mp4\" type=\"video/mp4\">
<source src=\"http://example.com/video2.php?type=stuff.ogv\" type=\"video/ogg\">
";
?>
Again, not a big deal. Now I am going to post a couple different versions of the video1.php file that actually grabs the file resource.
Version 1:
<?php
$file = video.mp4;
$filesize = filesize($file);
$offset = 0;
$length = $filesize;
if ( isset($_SERVER['HTTP_RANGE']) ) {
// if the HTTP_RANGE header is set we're dealing with partial content
$partialContent = true;
// find the requested range
// this might be too simplistic, apparently the client can request
// multiple ranges, which can become pretty complex, so ignore it for now
preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches);
$offset = intval($matches[1]);
$length = intval($matches[2]) - $offset;
} else {
$partialContent = false;
}
$file = fopen($file, 'r');
// seek to the requested offset, this is 0 if it's not a partial conten request
fseek($file, $offset);
$data = fread($file, $length);
fclose($file);
if ( $partialContent ) {
// output the right headers for partial content
header('HTTP/1.1 206 Partial Content');
header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $filesize);
}
// output the regular HTTP headers
header("Content-Type:video/mp4");
header('Content-Length: $filesize');
header('Accept-Ranges: bytes');
// don't forget to send the data too
print($data);
?>
Version 2 (I like this one better for what it does in Firefox, but still no dice in Chrome)
<?php
$file = video.mp4;
$mime = "video/mp4"; // The MIME type of the file, this should be replaced with your own.
$size = filesize($file); // The size of the file
// Send the content type header
header('Content-type: ' . $mime);
// Check if it's a HTTP range request
if(isset($_SERVER['HTTP_RANGE'])){
// Parse the range header to get the byte offset
$ranges = array_map(
'intval', // Parse the parts into integer
explode(
'-', // The range separator
substr($_SERVER['HTTP_RANGE'], 6) // Skip the `bytes=` part of the header
)
);
// If the last range param is empty, it means the EOF (End of File)
if(!$ranges[1]){
$ranges[1] = $size - 1;
}
// Send the appropriate headers
header('HTTP/1.1 206 Partial Content');
header('Accept-Ranges: bytes');
header('Content-Length: ' . ($ranges[1] - $ranges[0])); // The size of the range
// Send the ranges we offered
header(
sprintf(
'Content-Range: bytes %d-%d/%d', // The header format
$ranges[0], // The start range
$ranges[1], // The end range
$size // Total size of the file
)
);
// It's time to output the file
$f = fopen($file, 'rb'); // Open the file in binary mode
$chunkSize = 8192; // The size of each chunk to output
// Seek to the requested start range
fseek($f, $ranges[0]);
// Start outputting the data
while(true){
// Check if we have outputted all the data requested
if(ftell($f) >= $ranges[1]){
break;
}
// Output the data
echo fread($f, $chunkSize);
// Flush the buffer immediately
#ob_flush();
flush();
}
}
else {
// It's not a range request, output the file anyway
header('Content-Length: ' . $size);
// Read the file
#readfile($file);
// and flush the buffer
#ob_flush();
flush();
}
?>
So, while both play the video without problems, only the Firefox version will let me do any kind of seeking. The second version makes it so you can only seek backwards, which I prefer.
There was another version I tried, but I had already deleted the code before writing this and haven't found it again.
I am not sure what I'm doing wrong and no solutions I have found solved the issue of allowing the Chrome version of the video to seek.
Ok, so I finally got it to work. I decided to not load in the php files with javascript.
Also, I got rid of the mime type variable and just set the header properly. I found that using a variable for the mime type cause my browsers to load the wrong mime type for the content type header thus causing the video resource to fail.

How do i post variables inside a .js file to a php file without including jquery?

I'm abit confused as to how i will go about doing this, so i'm making a .js file to collect data on a page(100% with js) and i want to POST it to a php file which will then take care of it and insert it into the db etc..
How will i go about doing this? I know you can use jquery in a html document, but i want to use it in a .js file not a .html file.
I've successfully done it using a .html file and importing the jquery file, but i want to do it all in a .js file.
Any help is greatly appreciated. Thank you very much (:
I'd comment, but I can't. Can you post some samples of your code?
What I got is that you are using JavaScript (jQuery) to POST (form data?) over to a PHP file. If you want to use jQuery inside of a .js file, all you have to do is include the jQuery library before you include your .js file, like so:
<script src="jquery.js"></script>
<script src="myExternalScript.js"></script>
And then, inside of myExternalScript.js, you can use jQuery methods.
The external script is aware of your DOM elements, really, just like inline JavaScript would be, so you can still do whatever you want with your form or wherever you are getting the data to POST from.
EDIT: (in accordance to what you commented on this answer)
EDIT 2: I had forgotten to add the request header for POST
If you want to send an AJAX POST request (notice that I set the Content-Type request header, so that the data gets sent correctly):
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","http://zegita.tk/stargazer/magic.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("n="+user);
If you want to send an AJAX GET request:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://zegita.tk/stargazer/magic.php?n="+user, true);
xmlhttp.send();
It is important that you use the correct method, depending on whether you are using $_GET or $_POST in your magic.php file.
Clicking on the button runs this SCRIPT (which further passes 3 JS-variables to the abc.php)
<script type="text/javascript">
function sendJSValsToPHP(){
var xmlhttp;
//These are the variables i am going to post to illustrate the example, what you want
var var_1toPost = 1;
var var_2toPost = 2;
var var_3toPost = 3;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//You can get the response text from abc.php file and process it in any of the tags you want by javascript code
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","abc.php?recieve_1="+var_1toPost+"&recieve_2="+var_2toPost+"&recieve_3="+var_3toPost,true);
xmlhttp.send();
}
</script>
The echo'ed data in abc.php will come in the div="myDiv" //as a response.
<body>
<div id="myDiv" style="border: 1px solid BLUE; height: 100px;">
the things echo'ed in abc.php will come in this div
</div>
<button onclick="sendJSValsToPHP();">Click Me To Send JS-Values to abc.php</button>
</body>
and then in abc.php //file
<?php
$recieved_1 = $_GET['recieve_1'];
$recieved_2 = $_GET['recieve_2'];
$recieved_3 = $_GET['recieve_3'];
//Do your processing here and insert it in the database
//Insert Query OR Update Query (whatever)
// after you have inserted you can get the response in
// the <div> having id="myDiv" Or whatever you want
// Suppose you have successfully inserted data then
$insertedDataBoolean = true;
if($insertedDataBoolean){
echo "Data: " . $recieved_1 . ", " . $recieved_2 .
" and " . $recieved_3 . " inserted successfully.";
}
else{
echo "Data-insertion error.";
}
?>

Save data by MySQL after click a link to an external web

I want to put a clicks counter on banners on my page so advertisers get an idea of how many visitors arrive via my website.
I've seen that could be done by directing the link to an intermediate page that access MySQL (to save the data in a record BD) using PHP, and then redirected to the advertiser's website, but I wonder if there otherwise somewhat more "elegant" to do so.
Could anyone tell me if it is possible?
I've found an similar example, but this one donwload a file and count the visit (I only want to go to another web)
EXAMPLE HTML
<span style="font-family: Verdana, Arial, Helvetica, sans-serif;"><a href='files/my_file.zip' id='25' onClick='dc(this.id)' target='_blank'>Download this file</a> </span>
EXAMPLE Javascript
function dc(id){$.post("process.php",{file_id:id})}
EXAMPLE Process.php
$file_id = $_POST['file_id'];
mysql_query("UPDATE file SET downloads = downloads + 1 WHERE id = " .$file_id);
I tried to adapt this example to my code, like this:
HTML
echo '<br><a onClick="sumar(this.id);" href="http://'.$result['WEB'].'" id="'.$result['ID_PAG'].'" target="_blank">'.$result['WEB'].'</a><br />';
Javascript (In head section)
function sumar(id){($.post("suma.php",{pag:id})}
Suma.php
$pag=$_POST['pag'];
$mysqli->query("UPDATE lapag SET visitas=visitas+1 WHERE id_pag=".$pag);
Thank You!
Are you sure you have the apostrophs right? I c/p html part into eclipse and it did not particularly like it.
echo "<br><a onClick='sumar(this.id)'";
echo "href='http://".$result['WEB'] . "'";
echo "id=". $result['ID_PAG'] . 'target="_blank">';
echo $result['WEB']. "</a><br />";
I have broken it up into several echoes in order to make it clearer and easier to handle.
HTML
<?php echo $result['WEB']; ?>
Sumar.php
$pag=$_GET['ID_PAG'];
$mysqli->query("UPDATE lapag SET visitas=visitas+1 WHERE id_pag=".$pag);
header("Location: http://".$_GET['WEB']); // redirect
exit();
Think best practice should look like this:
<a href="http://random.org" onclick='called(event, this, "clicked")'>Visit site</a>
function called(event, link, id){
event.preventDefault();
event.stopImmediatePropagation();
var theUrl = "counter.php";
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange=function(){
if (this.readyState != 4) //4 means call is finished - we just want to switch side after the counter-call finished
return;
window.location.href = link.href.value;
};
xmlHttp.open("GET", theUrl, true);
xmlHttp.send("id="+id);
return false;
}
Example: http://jsbin.com/porotobuna/1/edit?html,js,output
In the counter.php just get the get variable "id" (which represents the clicked link) and handle the counter (I recommend some kind of database)

AJAX file upload to php, nothing being sent?

I have an input on my website which allows the user to select a file for upload
<input type="file" name="file" id="file" />
At the end of my page, I have a button which calls a javascript function. This function needs to check if the user has specified a file for upload and if so, upload the file (php) and obtain the filename.
How can I go about accessing the file input form from javascript? i.e. how can I get the 'post' file information to call 'upload_file.php' with.
ps. I'd rather not use JQuery
edit - i've tried this and it doesn't seem to work
function uploadFile(){
var files = document.getElementById('file');
var file = files.files[0];
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST","uploadfile.php",true);
xmlhttp.setRequestHeader("Content-type", "multipart/form-data")
var formData = new FormData();
formData.append("thefile", file);
xmlhttp.send(formData);
}
php:
<?php
echo "Upload: " . $_FILES["thefile"]["name"] . "<br />";
echo "Type: " . $_FILES["thefile"]["type"] . "<br />";
echo "Size: " . ($_FILES["thefile"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["thefile"]["tmp_name"] . "<br />";
?>
is giving me an alert saying the file name is blank, the type is blank, size is 0 etc...
It is accessable through the DOM, just like any other element. The only restriction is you can't alter it for security reasons.
http://www.simonerodriguez.com/ajax-form-submit-example/
Check this link for ajax post.
You can simply post it like a normal form, need no extra efforts for same.
Have u considered HTML5 File API?
Related StackOverFlow:
Html 5 File upload
I think you need some thing like this:
http://jsfiddle.net/kHQLp/4/
Doing this through AJAX has the following problems can achieved as thus (except for IE).
1) It is impossible for IE. If somebody has found a way give me a shout. What I did is just submit the form in the normal way and return an updated page.
2) For FF (and if memory serves me right Opera and Safari) the following snippet works
var fileTag = document.getElementById('id for input element');
var file = fileTag.files[0];
// You can check the type here by checking the string file.type
var data = file.getAsBinary(); // Or getAsText()
3) For Chrome use this code
var fileTag = document.getElementById('id for input element');
var file = fileTag.files[0];
var reader = new FileReader();
reader.onload = function() { /* Use reader.result as it has loaded */ };
reader.onerror = function(e) { /* and error occurred - handle it */ };
reader.readAsText(file); // I think there is also a function readAsBinary.
When you have got the contents of the file you can post it using AJAX
Solved my problem by replacing:
xmlhttp.setRequestHeader("Content-type", "multipart/form-data")
with
xmlhttp.setRequestHeader("enctype", "multipart/form-data")

Categories

Resources