this could be something that a lot of people ask, but, im having some troubles with something different.
Im developing a "game" section where every image is a tag, which will load a flash game .swf, the thing is, this need to be dinamically, i mean, every file.swf has different width/height, i did a function in PHP which bring from a file.swf the width/height, i tried to use javascript to do this, but i got some height troubles when the file.swf was loaded, for example, one file.swf has 720x550 using php function and the JS function gave me 720x714, So...This is the thing, i got this function in PHP:
function flash_get(){
ini_set("memory_limit","30M");
$file ="games/miniracing3d.swf";
$info = getimagesize($file);
$width = $info[0];
$height = $info[1];
echo "<script type='text/javascript'>
$('#game_lb_loaded').flash({
src: 'games/miniracing3d.swf',
width:$width,
height:$height
});
</script>";
}
It loads a JS plugin called jquery.flash.js, which is the one who load the file...but, i need this to work with Jquery, why exactly? well, i got this code in Jquery:
$body.on('click','.game_button_link',function() {
var id_game = $(this).attr('id'),
game = 'games/'+id_game+'.swf';
$("#game_lb_loaded").lightbox_me({
centered: true,
closeEsc: true,
overlayCSS: {
background: 'black',
opacity: .8,
width: 750,
height: 600
},
onLoad: function() {
$("#game_lb_loaded").flash({
src: game
});
}
});
});
That code its a code what i was working before making the PHP function, well, this is it, every has the class "game_button_link" and an id in it, which every id will be the name of the .swf, example id="file" == "file.swf" id="file2" == "file2.swf"...and so on...the real thing is, i need to mix the php function to get the width/height into onclick jquery function i really dont know how to achieve this, oh i forgot, i use lightbox_me to open a lightbox with the flash file in it...but it doesnt matter right now, i want to mix the php and jquery functions T_T, please i need your help :)
I end up using this code:
Javascript
$body.on('click','.game_button_link',function() {
var id_game = $(this).attr('id'),
game = 'games/'+id_game+'.swf';
$("#game_lb_loaded").lightbox_me({
centered: true,
closeEsc: false,
closeClick: false,
closeSelector: ".close_button_lb",
appearEffect: "fadeIn",
overlayCSS: {
background: 'black',
opacity: .8,
width: 800,
height: 600
},
onLoad: function() {
$.post('game_dimension.php', 'game='+game,
function(data){
var dimensions = data.split(',');
$('#game_lb_loaded').flash({
src: game,
width: dimensions[0],
height: dimensions[1]
});
}
);
},
destroyOnClose: true
});
});
PHP
<?php
ini_set("memory_limit","30M");
$file = $_POST['game'];
$info = getimagesize($file);
$width = $info[0];
$height = $info[1];
echo $width.','.$height;
?>
Thanks to everyone who helped :) I really appreciated it!
PHP is server-side, JS is client-side. They do not mix.You could use jQuery .ajax() to get data from the server, but you can never run PHP on the client-side.
I think this is what you're looking for?
In your php file, instead of echoing that script
echo $width.','.$height;
and then this would be your ajax call.
$.post('file.php',
function(data){
var dimensions = data.split(',');
$('#game_lb_loaded').flash({
src: 'games/miniracing3d.swf',
width: dimensions[0],
height: dimensions[1]
});
}
);
does that help?
If you know the values before the page is sent (inside the PHP code), you can write them out to the javascript in the page. In my example I'll use the case where you need to pass it to a function that is not under your PHP file's control:
<?php
$height = getHeight(); // just for example
?>
<script>
var height = <?php echo $height; ?>;
doSomethingWith( height );
</script>
If it is after the page has been sent, you'll use AJAX. You'll create a PHP page that doesn't output anything other than
<?php
$height = getHeight(); // Just for example
$width = getWidth(); // Just for example
$out = array("height"=>$height, "width"=>$width);
echo json_encode($out);
?>
Then in your javascript you either use jQuery or another JSON parser or eval() [but only when you control the output of the script and even then think twice about this].
var myObj = $.parseJson(serverOutput);
alert(myObj.height);
alert(myObj.width);
So that is the general two ways you go about this.
Related
I've built a map with PHP and Highmaps (from Highcharts libraries) which loads data from a SQL Server database. So far so good! But now I want to send a value from the map to another PHP page using Ajax since I want to send the name of the point clicked by the user.
series: {
cursor: 'pointer',
point: {
events:{
click:function(){
var myVariable = this.name;
$.get('my_page.php',{"brazil_state":myVariable});
}
}
}
}
After doing this on the same page:
<?php
$brazil_state = $_GET['brazil_state'];
$stmt = "select * from [DATABASE].[dbo].[MY_TABLE] where state = '{$brazil_state}'";
$stmt_exec = sqlsrv_query($conn, $stmt);
while($rows = sqlsrv_fetch_array($stmt_exec)){
print_r($rows);
}
?>
And this would bring to me all the results that satisfy the condition of the query, but the parameter is not being parsed from JQuery Ajax to the PHP $_GET.
I've searched the answer, but I haven't found any yet.
Thanks in advance!!!
In the second codesnippet you reference the variable $_GET['myVariable'], but the name of the variable you use in the ajax-request:
$.get('my_page.php',{"brazil_state":myVariable});
is "brazil_state"
I've found a way to solve my question:
series: {
cursor: 'pointer',
point: {
events:{
click:function(){
//open div with JQuery UI fold function
$( "#folder" ).show( "fold", 1000 );
//sends the request to details.php and brings the result into the div id='folder' on the current page
$.ajax({
url: 'details.php?state=' + this.name,
success: function(data) {
$('#folder').html(data);
}
});
}
}
}
}
Thank you, people!
Hi I need set value of PHP variable to "1" if clients screen resolution is more then 1200px (I check only width) and set value of this variable to "2" if client have screen smaller then 1200px.
To check clients width of screen I use JQuery function "$( window ).outerWidth(true)". If PHP can check clients resolution then I don´t need wrote this question, but PHP not allow this and for that I search for solution of this problem.
=> How can I write script which allow change PHP variable before client load page? I mean I need AJAX, but I don´t know how used it.
Sorry for this maybe simply question. Can someone help me?
This might help ,
var width = $(window).width();
var height = $(window).height();
var screenTimer = null;
function Screen (){
$(window).resize(function() {
height = $(window).height();
width = $(window).width();
getScreen ();
});
function getScreen (){
return { 'height' : getHeight (), 'width': getWidth () };
}
screenTimer = setInterval ( getScreen (), 50 );
}
function getHeight (){
console.log ( 'height: ' + height);
$('#height').text(height);
return height;
}
function getWidth (){
console.log ( 'width: ' + width);
$('#width').text(width);
return width;
}
Screen ();
put this code in php along with script tag and set your variable.
Impossible I get it... Finally a write this:
index.php:
<script type="text/javascript">
$(document).ready(function() {
var sirka_monitoru = $( window ).outerWidth();
if ( sirka_monitoru < 1200 ){
$.post("soubor1.php", { nejaka: "1111" }, function (msg)
{
$('.some_name').html(msg);
});
}
else{
$.post("soubor2.php", { nejaka: "2222" }, function (msg)
{
$('.some_name').html(msg);
});
}
}); //END $(document).ready()
</script>
<div class="some_name"></div>
soubor1.php (1st file to include) file soubor2.php is similar to soubr1.php
<?php
echo "Value: " . $_POST["nejaka"];
?>
<div style="width: 100%; float: left; background-color: green; height: 100px;">
soubor1
</div>
=> When I load page then check width of users screen and after that I can load different PHP files and send him some important variables to solved my problem from question.
=> I accept my answer and solved this queston and close it
Firstly I appreciate my request is quite "ambitious", but any help is greatly appreciated as I'm not sure the best way to proceed.
On my site (built with PHP/MySQL) after a user has uploaded a PDF I would like to display the PDF inline on the page (I'm assuming in an iFrame). I then need them to be able to drag out a number of "boxes" on top of the PDF (I'm assuming with jQuery). I then need to record the co-ordinates of this box so then later I can re-create the PDF injecting new text into the defined "boxes".
Does this sound feasible? If not what else would you suggest? (please don't say imagemagick!)
I know how to recreate a PDF injecting new text, but my issue is with how to allow the user to record those coordinates.
You could use PDF.js to render the PDF on the page. PDF.js will display it as part of the page so you can attach events and interact with it in ways you could not if it was being displayed by the Acrobat plugin.
I couldn't find a preexisting library for getting the coordinates so I whipped up this code to implement it.
Live demo of selection code
$(function () {
"use strict";
var startX,
startY,
selectedBoxes = [],
$selectionMarquee = $('#selectionMarquee'),
positionBox = function ($box, coordinates) {
$box.css(
'top', coordinates.top
).css(
'left', coordinates.left
).css(
'height', coordinates.bottom - coordinates.top
).css(
'width', coordinates.right - coordinates.left
);
},
compareNumbers = function (a, b) {
return a - b;
},
getBoxCoordinates = function (startX, startY, endX, endY) {
var x = [startX, endX].sort(compareNumbers),
y = [startY, endY].sort(compareNumbers);
return {
top: y[0],
left: x[0],
right: x[1],
bottom: y[1]
};
},
trackMouse = function (event) {
var position = getBoxCoordinates(startX, startY,
event.pageX, event.pageY);
positionBox($selectionMarquee, position);
};
$(document).on('mousedown', function (event) {
startX = event.pageX;
startY = event.pageY;
positionBox($selectionMarquee,
getBoxCoordinates(startX, startY, startX, startY));
$selectionMarquee.show();
$(this).on('mousemove', trackMouse);
}).on('mouseup', function (event) {
var position,
$selectedBox;
$selectionMarquee.hide();
position = getBoxCoordinates(startX, startY,
event.pageX, event.pageY);
if (position.left !== position.right &&
position.top !== position.bottom) {
$selectedBox = $('<div class="selected-box"></div>');
$selectedBox.hide();
$('body').append($selectedBox);
positionBox($selectedBox, position);
$selectedBox.show();
selectedBoxes.push(position);
$(this).off('mousemove', trackMouse);
}
});
});
You will have to tweak it to get coordinates that are relative to the PDF once you display it, but this should get you on the right track.
I need to be able to replace a php file with another php file based on screen resolution. This is what I have so far:
<script type="text/javascript">
function adjustStyle(width) {
width = parseInt(width);
if (width = 1920) {
$('book.php').replaceWith('book2.php');
}
}
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
</script>
which obviously isn't working-- any ideas? Thank you in advance for any help received.
UPDATE
Is this at all close (to replace the book.php line)?
{ $("a[href*='book.php']").replaceWith('href', 'book2.php'); };
Second Update to reflect input gathered here
function adjustStyle(width) {
width = parseInt(width);
if (width == 1920) {
$('#bookinfo').replaceWith(['book2.php']);
$.ajax({
url: "book2.php",
}).success(function ( data ) {
$('#bookinfo').replaceWith(data);
});
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
}
}
I have not seen the use of replaceWith in the context you put it in. Interpreting that you want to exchange the content, you may want to do so my using the load() function of jQuery.
if(width == 1920){
$("#myDiv").load("book1.php");
} else {
$("#myDiv").load("book2.php");
}
Clicking on the button replaces the content of the div to book2.php.
The first problem is I don't think that you are using the correct selectors. If you have the following container:
<div id="bookContainer">Contents of book1.php</div>
The code to replace the contents of that container should be
$('#bookContainer').replaceWith([contents of book2.php]);
In order to get [contents of book2.php] you will need to pull it in by ajax using the following code I have also included the line above so that the data from book2.php will be placed into the container:
$.ajax({
url: "http://yoururl.com/book2.php",
}).success(function ( data ) {
$('#bookContainer').replaceWith(data);
});.
I haven't tested this so there might be an issue but this is the concept you need to accomplish this.
First off... using a conditional with a single = (equal sign) will cause the condition to always be true while setting the value of variable your checking to the value your checking against.
Your condition should look like the following...
if (width == 1920) { // do something }
Second, please refer to the jQuery documentation for how to replace the entire tag with a jquery object using replaceWith()... http://api.jquery.com/replaceWith/
I would use a shorthand POST with http://api.jquery.com/jQuery.post/ since you don't have the object loaded yet...
In short, my code would look like the following using $.post instead of $.ajax assuming I had a tag with the id of "book" that originally has the contents of book.php and I wanted to replace it with the contents of book2.php...
HTML
<div id="book">*Contents of book.php*</div>
jQuery
function onResize(width) {
if (parseInt(width) >= 1920) {
$.post('book2.php',function(html){
$('#book').html(html).width(width);
});
}
else {
$.post('book.php',function(html){
$('#book').html(html).width(width);
});
}
}
Hope this helps.
I'm using jQuery + PHP on my website and I want to do something like this:
To simplify things I've got a page with 2 buttons () and according to which I click I want to start a script in background (php script) so I do a simple thing with jquery:
$("#button1").click(function(){
$.post("script.php", {val:"but1"}, function(result){
alert(result); // I want something with the result
});
});
$("#button2").click(function(){
$.post("script.php", {val:"but2"}, function(result){
alert(result);
});
});
and in the script.php I've got a simple if statement deciding what I should do.
In the php script I'm downloading a file and I want to create a progress bar of the file download. The php script would return me values (echo percentage; flush();) in some time interval.
And here comes the problem - when I echo those percentage values and flush it refreshes it "just in php" but the jquery waits until the script is finished anyway. Is there a way to get those values as they appear (after flush) or is there a completely other approach to this? I can't think of anything else right now, maybe I shouldn't be using jquery at all.
Thanks for the help.
You can store the progress in a text file or DB while running the script and then have another file get the result via AJAX calls.
JS/HTML
<script>
$(function() {
var id;
var timeoutLength = 1000;
$("#button1").click(function() {
$("#result").html("");
// Create unique identifier
id = (new Date().getTime()) + "-" + Math.floor(Math.random()*100);
$.get("script.php", {id: id}, function(result){
$("#result").html(result);
});
setTimeout(checkProgress, timeoutLength);
});
function checkProgress() {
$.get("script.php", {progress: true, id: id}, function(data) {
prog = parseInt(data);
// Display progress bar
if(prog < 100) {
$("#progress").css({ display: 'block', width: prog });
$("#progress").html(prog + "%");
setTimeout(checkProgress, timeoutLength);
} else {
$("#progress").css('display', 'none');
}
});
}
})
</script>
<button id="button1">Click</button>
<div id="progress" style="background: green"></div>
<div id="result"></div>
script.php
<?php
function getProgress($file) {
return (file_exists($file)) ? file_get_contents($file) : 0;
}
function setProgress($file, $progress) {
file_put_contents($file, $progress);
}
// Remove invalid characters
$id = str_replace('/[^a-zA-Z0-9\-_]/', '', $_GET['id']);
$file = "progress-" . $id . ".txt";
if(isset($_GET['progress'])) {
echo getProgress($file);
} else {
// Do something and update progress
for($i = 10; $i <= 100; $i += 10) {
// Do something
setProgress($file, $i);
sleep(1);
}
unlink($file);
echo "Result: " . rand(1, 100);
}
Edit:
Added support for multiple requests and simple progress bar.
i believe that what all you need is the pecl uploadprogress package
it is not very easy to install and its not sure it works, i have find hard to make it work under certain server configurations, but i think its a good shot
EDIT: sorry i didnt see you mention download so have a look here
Below script will work for the progress-bar.
But, what I would do is, trigger an AJAX call to start the download and trigger another AJAX call to start receiving the input (using How to show file download progress in PHP Shell Scripting?).
PHP:
<?php
echo "wget '$feedURL'\n";
$execute = "wget -O ".$filePath." '$feedURL'\n";
$systemOutput = shell_exec($execute);
$systemOutput = str_replace( "\n", "\n\t", $systemOutput);
echo "\t$systemOutput\n";
?>
GetProgress:
function getProgress(){
GDownloadUrl("getprogress.php?progress_key=<?php echo($unique_id)?>",
function(percent, responseCode) {
document.getElementById("progressinner").style.width = percent+"%";
if (percent < 100){
setTimeout("getProgress()", 100);
}
});
}
Here is nice implementation with the help PHP's APC to get a nice progress-bar during UPLOAD of a file - http://www.haughin.com/2007/10/23/php-upload-progress-with-php-52-apc/
Alternative solution:
You can store the progress of downloading file into $_SESSION array inside PHP.
Besides that, you can write a dedicated PHP to only retrieve this percentage from session. This PHP will be called from your client's AJAX. This way the proccess won't take so much resources from server to calculate or to echo the download's percentage.
Try to avoid I/O from files if you are going to handle high rates of reading/writing onto them. Session variables are less expensive to achieve this functionality.
Provided that your PHP has some way to know the progress percentage, you should do multiple requests for progress updates:
function receiveProgress(data) {
// update progres indicator here
if (parseFloat(data) < 100) {
setTimeout(checkProgress, 100);
} else {
pressedButton = '';
}
}
function checkProgress() {
$.post("script.php", {val:pressedButton}, receiveProgress);
}
var pressedButton = '';
$("#button1").click(function(){
pressedButton = 'but1';
checkProgress();
});
This will ask server for progress updates every 100ms