jquery viewport info not passed to php - php

I'm trying and failing to send the viewport width and heigth to a PHP file!
I know this or rather many similar questions about passing to PHP have already been asked and I've been going through these as well. However, I haven't figured out why it doesn't work for me...
I get the following output, where the second line would match the first, if the data had been passed:
Your viewport width is 1519x766
Width is: 880 and Height is 495
I just can't get the information passed to the PHP part - tried it like this in one file and also in two files, where I then call the php file using:
<?php include 'panzoom.php';?>
I use this code in the head:
<script>
var viewportwidth;
var viewportheight;
viewportwidth = window.innerWidth,
viewportheight = window.innerHeight
document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');
$(document).ready(function() {
$.ajax({
url: 'http://localhost/index.php',
type: 'POST',
dataType: 'json',
data: {
width : viewportwidth,
height : viewportheight
}
});
});
</script>
<?php
$GLOBALS['directory'] = "photos/frontpage/";
if(isset($_POST['width']) && isset($_POST['height'])) {
$GLOBALS['width'] = $_POST['width'];
$GLOBALS['height'] = $_POST['height'];
}else{
$GLOBALS['width'] = 880;
$GLOBALS['height'] = 495;
}
$width = $GLOBALS['width'];
$height = $GLOBALS['height'];
echo '<p>Width is: ' . $width . ' and Height is ' . $height . '</p>';
?>

You have posted a JSON string to the PHP script and it is called data so you should be looking for $_POST['data']
Also as it is posted as a json string, in order to make sense of it in PHP you normally decode it to either an array or a string using json_decode()
You also dont need to create all the variables in javascript to clutter up the global namespace.
So try this
<script type="text/javascript">
document.write('<p>Your viewport width is '+
window.innerWidth+'x'+window.innerHeight+'</p>');
$(document).ready(function() {
$.ajax({
url: 'index.php',
type: 'POST',
dataType: 'json',
data: {
width : window.innerWidth,
height : window.innerHeight
}
});
});
</script>
<?php
$GLOBALS['directory'] = "photos/frontpage/";
if( isset($_POST['data']) ) {
$obj = json_decode($_POST['data']);
$GLOBALS['width'] = $obj->width;
$GLOBALS['height'] = $obj->height;
}else{
$GLOBALS['width'] = 880;
$GLOBALS['height'] = 495;
}
$width = $GLOBALS['width'];
$height = $GLOBALS['height'];
echo '<p>Width is: ' . $width . ' and Height is ' . $height . '</p>';
?>

Related

Dropzone JS: How to get URLs of each image to pass as separate AJAX request after uploading process?

I'm going off of Dropzone.js resources provided by: http://www.dropzonejs.com/
What I'm trying to do - After uploading the image(s) and filling out all inputs, to get the link for each image that was uploaded in this session, to be passed into an AJAX request URL as a POST type.
My HTML:
<div id="myForm">
<input type="text" id="form-name" placeholder="Name">
<input type="text" id="form-email" placeholder="Email">
<form action="/upload-target" class="dropzone" id="myDropZone"></form>
<button id="submit-info">submit</button>
</div>
My JS:
<script>
$("div#myDropzone").dropzone({ url: "/upload.php" },
function() {
console.log("Hello");
});
</script>
The images are uploaded to a directory mentioned in the PHP code below, but I have a problem with the above script, where the output in the console doesn't even print. Hello doesn't show in the console when anything is uploaded.
My upload.php:
<?php
$ds = DIRECTORY_SEPARATOR;
$storeFolder = 'img/uploads';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
}
?>
Just to explain the above code, once an image(s) is
selected/drag-and-dorpped, upload.php uploads the images to
http://example.com/img/uploads/ folder.
Here's where I need help:
I am trying for when clicking the button with id submit-info, passing each image I've just uploaded as a string to the AJAX request:
<script>
$('#submit-info').click(function() {
var str = "name=" + $('#form-name').val()
+ "&email=" + $('#form-email').val()
+ "&images=" + /* what to put here */;
console.log(str);
$.ajax({
type: "post",
url: "sendEmail.php",
data: str,
dataType: "json",
success: function (confirmation) {
// some code here dealing with after the email is sent like hiding the form
}
});
});
</script>
Here's one way to do it:
var files = '';
if (Dropzone.forElement("#my-dropzone").files.length > 0) {
for (var i = 0; i<Dropzone.forElement("#my-dropzone").files.length; i++) {
if (i === (Dropzone.forElement("#my-dropzone").files.length - 1) ) {
files += Dropzone.forElement("#my-dropzone").files[i].name;
}
else {
files += Dropzone.forElement("#my-dropzone").files[i].name + '~';
}
}
}
The above code should be placed inside of the $('#submit-info').click(function() { ... so that once the submit button is clicked, we set an empty string, check if there are any files that were uploaded, and concatenate them if they exist.
For this example, the files are being separated by ~ characters. So once the string is passed through, you can declare your str variable like so:
$('#submit-info').click(function() {
var str = "name=" + $('#form-name').val()
+ "&email=" + $('#form-email').val()
+ "&images=" + files;

imagejpeg() php return junk values

My jQuery Ajax code is:
<div class="page_rank">
<form name="searchForm" id="searchForm" method="post">
<span class="my_up_text">ENTER THE WEBSITE TO CHECK GOOGLE PAGE RANK:</span>
<br /><br />
<input type="text" name="my_site"/></div><div class="p_ity"><input type="submit" class="btn" value="PAGE RANK" /> </form></div><div id="my_pass"></div>
<script>
function sub_form()
{
document.forms["searchForm"].submit();
}
$(function () {
$('form#searchForm').on('submit', function(e) {
$( ".p_ity" ).hide();
$.ajax({
type: 'post',
url: 'check-google-page-rank.php',
data: $('form').serialize(),
success: function (data) {
$('#my_pass').html(data);
}
});
e.preventDefault();
});
});
</script>
My php code is:
<?php
header('Content-type: image/jpeg');
require('./get_page_rank.php');
$url=$_POST['my_site'];
//echo $url;
$pr = new PR();
//$rank= $pr->get_google_pagerank($url);
$rank=$pr->get_google_pagerank($url);
// Create Image From Existing File
$jpg_image = imagecreatefromjpeg('./images/page-rank/G.jpg');
if($jpg_image)
{
// Allocate A Color For The Text
$white = imagecolorallocate($jpg_image, 0, 0, 0);
// Set Path to Font File
$font_path = './images/page-rank/Helvetica.TTF';
// Set Text to Be Printed On Image
$text = $rank;
// Print Text On Image
imagettftext($jpg_image, 85, 0, 305, 100, $white, $font_path, $text);
// Send Image to Browser
imagejpeg($jpg_image,NULL,100);
// Clear Memory
imagedestroy($jpg_image);
}
?>
It works perfectly if I execute the PHP separately with manual input so I think the problem is with jQuery html() function. I am sure the image is not corrupted and I am using utf-8 encoding and I also tried base64_encode(imagejpeg()) but got the same output.
OUTPUT:
��*����D\�#��梸�����[[h� ��0 s��('�y\�ӎ+��_�P 7��){�i�i��ĽOH�
_��:�� VV���y�x���o~�Eh��R��U�1�C����|�~,�ѿ
��7׼c��|S�����W�:�g��� ����K�z��A��D .͓�<�n��F� d�Qƹ̸{%�*֣�2�q7c�9UJ�0s��w�ߞ>ҥX��UaQG��w�bq8��
imagejpeg() outputs the image to browser directly, so the response is not the html content you could use with .html(), you don't have to use ajax in this case, the url should be used as the src of an image tag.
You could do like below:
$(function () {
$('form#searchForm').on('submit', function(e) {
$( ".p_ity" ).hide();
$('<img />').attr('src', 'check-google-page-rank.php?my_site='+ encodeURIComponent($('[name= "my_site"]').val())).load(function() {
$(this).appendTo('#my_pass');
});
e.preventDefault();
});
});
And change $url=$_POST['my_site']; to $url=$_GET['my_site'];.
In your php handler, write your image in a file;
$imgFolderPAth = "/path/to/img/";
imagejpeg($jpg_image,$imgFolderPAth . "image.jpg",100);
echo $imgFolderPAth . "image.jpg";
and in your js;
$.ajax({
type: 'post',
url: 'check-google-page-rank.php',
data: $('form').serialize(),
success: function (data) {
$('#my_pass').html('<img src="' + data + '"/>');
}
});
Or alternatively you can use;
imagejpeg($jpg_image,NULL,100);
$rawImageBytes = ob_get_clean();
echo "<img src='data:image/jpeg;base64," . base64_encode( $rawImageBytes ) . "' />";
and in your js, you can use as it is

html2canvas save image doesn't work

I'm rendering a screenshot with html2canvas 0.4.0 and want to save it as image on my webserver.
To do so, I've written the following function:
JavaScript
function screenShot(id) {
html2canvas(id, {
proxy: "https://html2canvas.appspot.com/query",
onrendered: function(canvas) {
$('body').append(canvas); // This works perfect...
var img = canvas.toDataURL("image/png");
var output = img.replace(/^data:image\/(png|jpg);base64,/, "");
var Parameters = "image=" + output + "&filedir=" + cur_path;
$.ajax({
type: "POST",
url: "inc/saveJPG.php",
data: Parameters,
success : function(data)
{
console.log(data);
}
}).done(function() {
});
}
});
}
saveJPG.php
<?php
$image = $_POST['image'];
$filedir = $_POST['filedir'];
$name = time();
$decoded = base64_decode($image);
file_put_contents($filedir . "/" . $name . ".png", $decoded, LOCK_EX);
echo $name;
?>
After the canvas is rendered I can perfectly append it to the HTML body, but saving it on my server result in a corrupted (?) file.
I can read the dimensions in IrvanView, but the image is transparent / empty?
The file is about 2.076 KB large. So it's not really empty.
I tried this with JPEG as well and it results in a corrupted file and IrfanView says something like "bogus marker length".
The screenshot has the dimensions of 650x9633. Is it to much data for a POST-Method?
In case someone stumbles over the same problem, here is how I solved it:
The problem depended on the fact, that + in URLs is interpreted as an encoded space (like %20) by most servers. So I needed to encode the data first and then send it via POST to my designated PHP function.
Here is my code:
JavaScript
function screenShot(id) {
html2canvas(id, {
proxy: "https://html2canvas.appspot.com/query",
onrendered: function(canvas) {
var img = canvas.toDataURL("image/png");
var output = encodeURIComponent(img);
var Parameters = "image=" + output + "&filedir=" + cur_path;
$.ajax({
type: "POST",
url: "inc/savePNG.php",
data: Parameters,
success : function(data)
{
console.log("screenshot done");
}
}).done(function() {
//$('body').html(data);
});
}
});
}
savePNG.php
<?php
$image = $_POST['image'];
$filedir = $_POST['filedir'];
$name = time();
$image = str_replace('data:image/png;base64,', '', $image);
$decoded = base64_decode($image);
file_put_contents($filedir . "/" . $name . ".png", $decoded, LOCK_EX);
echo $image;
?>
Cheers!

Can't get custom JSONP pipeline to work

I'm building an audio player that makes 3 different API calls, and I need them all to be in JSONP format, so I made a PHP proxy file that determines the output of the JSON data like so:
$datatype = $_GET["type"];
$artist = urlencode($_GET["artist"]);
$album = urlencode($_GET["album"]);
$content = "";
if($datatype == 'albumart'){
$content = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=037358e302c80571663e6a7a66b1dc05&artist=' . $artist . '&album=' . $album . '&format=json');
} elseif($datatype == 'artistart'){
$content = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=037358e302c80571663e6a7a66b1dc05&artist=' . $artist . '&autocorrect=1&format=json');
} else {
$content = file_get_contents('http://cjzn.streamon.fm/metadata/recentevents/CJZN-48k.json');
}
header('Content-type: application/json; charset=utf-8');
echo $_GET['callback'] . '(' . json_encode($content) . ')';
Upon testing the output it seems to work fine, it gets the respective API data, wraps it in the JSONP () and accepts a JSONP callback.
Bur when I try and use it in my Javascript file it doesn't seem to work, but I can't figure out why! Here's an example of one of the functions being used to call the JSON data:
function getAlbumArt(artist,album){
var dataArtist = artist,
dataAlbum = album,
albumArtURL;
$.ajax({
url: 'jsonproxy.php',
dataType: 'jsonp',
data: {
type: 'albumart',
artist: dataArtist,
album: dataAlbum
},
success: function(data) {
if(data.album.image[4]["#text"]){
var albumArtURL = data.album.image[4]["#text"];
$('section.player div.album-artwork').css({'background-image':'url("' + albumArtURL + '")'});
} else {
getArtistArt(dataArtist);
}
},
error: function() {
getArtistArt(dataArtist);
alert('Sorry, unable to retrieve album artwork!');
}
});
}
Can anyone help with why this doesn't work for me?
Edit
I did alert(data); on success, and that returned all of the data from the feed, after that if I did something more specific like alert(data.album.image[4]["#text"]); it returned undefined. Very confused here. Anyone have any thoughts?

jQuery Ajax - Alternate XML sources for each request

I have two XML sources to retrieve data from. I want to use them alternately per page load. So when someone visits the page the first source will be used, next time the visit the page the other source will be used. Here is the ajax request I am using to get one data source:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "source1.xml", //how do I alternately load two different xml data sources?
dataType: "xml",
success: function(xml) {
var counter = 0
var output = '<li>';
$(xml).find('person').each(function(){
counter++;
var image = $(this).find('image').text();
var name = $(this).find('name').text();
var title = $(this).find('title').text();
var company = $(this).find('company').text();
output = output + '<div><img src=img/' + image + '.jpg />' + '<br /><label><span>' + name + '</span><br />' + title + '<br />' + company + '</label><br /></div>';
if(counter % 3 === 0){
output = output + '</li><li>';
}
});
output = output + '</li>';
$('#update-target ul').html(output);
}
});
});
For extra info, here is how I am alternately loading 2 flash files using PHP:
if(isset($_SESSION['rotation'])){
$picker = $_SESSION['rotation'];
}else{
$picker = rand(0,1);
}
if($picker == 0){
echo '<script type="text/javascript">
var video1 = new SWFObject("somefile1.swf", "p1", "151", "590", "9", "#ffffff");
video1.addParam("wmode","transparent");
video1.write("meh");
</script>';
$_SESSION['rotation'] = ++$picker;
} else {
echo '<script type="text/javascript">
var video1 = new SWFObject("somefile2.swf", "p1", "151", "590", "9", "#ffffff");
video1.addParam("wmode","transparent");
video1.write("meh");
</script>';
$_SESSION['rotation'] = --$picker;
}
I realize I could just stick the jquery document ready code right in there where I have the js calling the flash but it does not seem like a very efficient way of handling this. What is a "best case" way to do this?
You can just use a variable to keep it short, like this:
echo '<script type="text/javascript">var xmlSource = "source1.xml";</script>';
Use that in an if caluse as well, then just reference that in your code:
url: xmlSource,
There are other ways of course, using a cookie (the cookie plugin), putting the text right in the document.ready handler, etc...whichever seems most elegant to you I suppose.
I recommend the variable from the PHP side or a cookie...both of these options allow the document.ready code to stay outside the page in an external script, and not downloaded by the user each time.

Categories