How to solve this string literal error - php

This code below is giving me a unterminated string literal error, how can this be fixed?
below is javascript code (QandAtable.php).
$(".imageCancel").on("click", function(event) {
var image_file_name = "<?php echo str_replace("\n", "", $image_file_name); ?>";
$('.upload_target').get(0).contentwindow
$("iframe[name='upload_target']").attr("src", "javascript:'<html></html>'");
jQuery.ajax("cancelimage.php" + image_file_name)
.done(function(data) {
$(".imagemsg" + _cancelimagecounter).html(data);
});
return stopImageUpload();
});
below is imagecancel.php script where the ajax links to:
...
$image_file_name = $_GET["fileImage"]["name"];
echo "File Upload was Canceled";
$imagecancelsql = "DELETE FROM Image
WHERE ImageFile = 'ImageFiles/". mysql_real_escape_string($image_file_name)."'";
mysql_query($imagecancelsql);
In error console it is showing it as: var image_file_name = "<br />

Try this out, don't worry about the internal double quotes, it won't affect your javascript string
var image_file_name = "<?php echo str_replace("\n", "", $image_file_name); ?>";

I doubt if I got your question correct, but there are few issues in your code.
when you are using $_GET, I guess you are doing it wrong $_GET["fileImage"]["name"] since its the GET parameter it will be simply $_GET["fileImage"]
But even before doing this, you should be sending it in the proper $_GET parameter i.e.
jQuery.ajax("cancelimage.php?fileImage=" + image_file_name)

Related

Jquery/json pull string with html from mysql db

I'm pulling data from a mysql db using php and echoing a json_encoded array.
Using ajax I pull in the results and set the values of various dom elements. I have a string which has some html tags eg <p></p>.
When I set the element $("#element").html(data['text']) it adds double quotes to the text and all of the html elements appear as text.
I can't seem to remove the quotes using replace. Oddly when I alert the value there are no quotes. They only appear in the html when I view the code.
What is the best way to include html with text? And how do I get jquery to render this has html and not text?
Many thanks!
PHP / MySQL
//Article by id
if(isset($_GET['do']) && $_GET['do']=='get_art') {
$content = array();
$id = clean_input($_GET['id']);
$q = "SELECT * FROM articles WHERE id = '$id'";
$r = $conn->query($q);
$row = $r->fetch_assoc();
$content['title'] = str_replace("€", '€', $row['title']);
$content['img'] = $row['img'];
$content['text'] = str_replace('€', '€', $row['text']);
$content['text'] = htmlentities($row['text']);
echo json_encode($content);
}
//end article by id
jQuery
//load article onclick
$('body').on('click', '.get_art', function (e) {
e.preventDefault();
var href = $(this).attr('href').replace('#', ' ');
$.ajax({
url: 'actions.inc.php?do=get_art&id=' + href,
dataType: 'json',
type: 'post',
success: function(data) {
var art_text = data['text'];
art_text = art_text.replace('&euro;', '€');
$("#art_img").attr("src", "images/" + data['img']);
$("#art_title").html(data['title']);
$("#art_text").html($.parseHTML(art_text));
} //end success
});//end ajax
});
//end load
The htmlentities (php) was making a mess of things, got it working now after I console logged the output from the php file

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!

Javascript String with Single Quote printed from PHP code

I have following script printed from PHP . If some one has a single quote in description it shows javascript error missing ; as it thinks string terminated .
print "<script type=\"text/javascript\">\n
var Obj = new Array();\n
Obj.title = '{$_REQUEST['title']}';
Obj.description = '{$_REQUEST['description']}';
</script>";
Form does a post to this page and title and description comes from textbox.Also I am unable to put double quotes around {$_REQUEST['title']} as it shows syntax error . How can I handle this ?
a more clean (and secure) way to do it (imo):
<?php
//code here
$title = addslashes(strip_tags($_REQUEST['title']));
$description = addslashes(strip_tags($_REQUEST['description']));
?>
<script type="text/javascript">
var Obj = new Array();
Obj.title = '<?php echo $title?>';
Obj.description = '<?php echo $description?>';
</script>
You also need to be careful with things like line breaks. JavaScript strings can't span over multiple lines. json_encode is the way to go. (Adding this as new answer because of code example.)
<?php
$_REQUEST = array(
'title' => 'That\'s cool',
'description' => 'That\'s "hot"
& not cool</script>'
);
?>
<script type="text/javascript">
var Obj = new Array();
Obj.title = <?php echo json_encode($_REQUEST['title'], JSON_HEX_TAG); ?>;
Obj.description = <?php echo json_encode($_REQUEST['description'], JSON_HEX_TAG); ?>;
alert(Obj.title + "\n" + Obj.description);
</script>
Edit (2016-Nov-15): Adds JSON_HEX_TAG parameter to json_encode calls. I hope this solves all issues when writing data into JavaScript within <script> elements. There are some rather annoying corner cases.
Use the string concatenation operator:
http://php.net/manual/en/language.operators.string.php
print "<script type=\"text/javascript\">\n
var Obj = new Array();\n
Obj.title = '".$_REQUEST['title']."';
Obj.description = '".$_REQUEST['description']."';
</script>";

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.

very simple javascript failing

Working Example:
This is almost identical to code I use in another places on my page but fails here for some reason.
<?php
//$p = "test";
?>
<script>
alert('posts are firing? ');
parent.document.getElementById('posts').innerHTML = "test";
</script>
Failing example: (alert still works)
<?php
$p = "test of the var";
?>
<script>
alert('posts are firing? ');
parent.document.getElementById('posts').innerHTML = '<?php $p; ?>';
</script>
Try
'<?php echo $p; ?>';
or
'<?= $p ?>';
Debugging 101: Start checking all variable values.
alert(parent);
alert(parent.document);
alert(parent.document.getElementById('posts'));
as well as the value rendered by: '<?php $p; ?>'
Make sure your 'posts' object (I guess it is DIV or SPAN) loads before you fill it using javascript.
You're trying to generate javascript with php, here I use a simple echo:
<?php
$p = "test of the var";
echo"
<div id='posts'></div>
<script type='text/javascript'>
var posts = document.getElementById('posts');
posts.innerHTML = '$p';
</script>
";
?>
Note the $p and that the div is printed before the javascript!
You are not outputting the variable data is why it isn't working. You need to echo or print the variable $p.
In your example the $p is being evaluated, not printed.
To print it you should use print, echo, or the syntax <\?=$p;?>. without the \

Categories