How do I fix this unterminated string literal error. What does this error mean and how can it be fixed
Below is the full code:
<?php
session_start();
if(isset($_POST['fileImage'])){
$idx = count($_POST ['fileImage']) -1 ;
$output = isset($_POST ['fileImage'][$idx]) ? $_POST ['fileImage'][$idx]['name'] : "";
}
?>
function stopImageUpload(success) {
var imageNameArray = ['<?php echo json_encode($output); ?>'];
var result = '';
if (success == 1) {
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
for (var i = 0; i < imageNameArray.length; i++) {
$('.listImage').append(imageNameArray[i] + '<br/>');
}
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
It means that there's something wrong with your quotes (an extra single quote in the echo'd content, or a line feed) and it's messing up the parser. Make sure any characters that are special in JS (quotes, line breaks etc) are properly escaped.
json_encode does this for you.
A better solution might look like this:
<?php
session_start();
$results = array();
if(isset($_POST['fileImage'])){
// not entirely sure what you're trying to achieve here
// so just replicating the logic you already had
// but I'm sure there's a better way to do whatever this is trying to do
$idx = count($_POST['fileImage']) -1 ;
$results[] = isset($_POST['fileImage'][$idx]) ? $_POST ['fileImage'][$idx]['name'] : "";
}
?>
function stopImageUpload(success) {
var imageNameArray = <?php echo json_encode($results); ?>;
var result = '';
if (success == 1) {
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
for (var i = 0; i < imageNameArray.length; i++) {
$('.listImage').append(imageNameArray[i] + '<br/>');
}
} else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
// you might want to use the "result" variable before returning
return true;
}
What changed? I removed the [] around the output of json_encode and made the array in PHP instead of JS. This way, when you do post the form, $results will be an array with a single element, and when you don't, it'll be an empty array. The rest of the logic should work just like before, but do read the comments I added.
Related
How do I get the html space characters out of my dynamic text loaded from a text file?
This is what my loaded text looks like in my .swf:
Adaptasi%20morfologi%20adalah%20penyesuaian%2E%2E%2E%0D%0A%0D%0A=&onLoad=%5Btype%20Function%5D
And it's my actionscript:
var select_obj:LoadVars = new LoadVars();
select_obj.onLoad = function(success:Boolean) {
if (success) {
isi.text = select_obj;
trace (select_obj);
} else {
trace('error...');
}
};
filepath = "http://localhost/adaptasi/";
select_obj.sendAndLoad(filepath + "morfologi.php", select_obj, "GET");
Here is my PHP script:
<?php
mysql_pconnect ("localhost", "root", "");
mysql_select_db ("adaptasi");
$qResult = mysql_query ("SELECT isi FROM materi WHERE id = 1");
$nRows = mysql_num_rows($qResult);
$rString ="";
for ($i=0; $i< $nRows; $i++){
$row = mysql_fetch_array($qResult);
$rString .= $row['isi'];
}
echo $rString;
?>
To get your values sent by your script, you should return them as a URL-encoded query string containing name/value pairs like this :
message=hello&from=user1&to=user2
which can be returned by your PHP script :
<?php
echo "message=hello&from=user1&to=user2";
?>
then the LoadVars object will decode (parse) that variable string automatically for you as properties of the LoadVars object :
var result:LoadVars = new LoadVars();
result.onLoad = function(success:Boolean) {
if (success) {
trace(result.message); // gives : hello
trace(result.from); // gives : user1
trace(result.to); // gives : user2
trace(result); // gives : to=user2&from=user1&message=hello&onLoad=%5Btype%20Function%5D
} else {
trace('error !');
}
};
result.sendAndLoad(filepath, result);
Hope that can help.
Use urldecode() function:
<?PHP
$string = "Adaptasi%20morfologi%20adalah%20penyesuaian%2E%2E%2E%0D%0A%0D%0A=&onLoad=%5Btype%20Function%5D";
//$string = $_GET['variable'];
$rString = urldecode($string);
echo $rString;
I wanna erase %20, %2E%2E%2E%, and etc..
For that you can try either decodeURIComponent or just decodeURI. Read that manual for differences (but for your current result, any of these two is good).
An example with your code :
var result:LoadVars = new LoadVars();
var filepath:String;
filepath = "localhost/adaptasi/";
result.sendAndLoad(filepath + "morfologi.php", result, "GET");
result.onLoad = function(success:Boolean)
{
if ( success )
{
text_morfo.text = result;
text_morfo = decodeURIComponent( text_morfo );
trace("success route : "); trace( text_morfo );
}
else { trace("error in result..."); }
}
Also I don't know what else your AS & PHP code will add later so if you need a quick testing tool you can try this link. Just put your traced results into the bottom box and choose option (like unescape, decodeURI etc). This will quickly help you see which command is best to use in your AS code.
i have an xml file in my server that i want to extract a list of IDs with php then convert the array to a JSON using json_encode() and put it in a $_SESSION variable, to make this clear my ideal JS function is:
function getIDs() {
var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>;
if(x == '') {
$.post('getPL.php','PL_name=cool&q=IDs',function(responseText){
x = responseText;
});
}
//some other code
//return array; // this is an array i use later in js
}
in my getPL.php i have:
$videos_list = $theOne->parentNode->parentNode->getElementsByTagName('video');
for ($i = 0; $i < $videos_list->length; $i++) {
$a = $videos_list->item($i);
$id_out = $a->getElementsByTagName('id')->item(0)->nodeValue;
$array[$i] = $id_out;
}
$IDs = json_encode($array);
$_SESSION['IDs'] = $IDs;
echo $IDs;
break;
if i alert var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>; i get g8M8kxuaCWk,VWrBFt46J18
but when i alert the responseText i get ["g8M8kxuaCWk","VWrBFt46J18"]
all i want is to extract the IDs from the xml file and put them in a js array object
if there is anything need more tell me
i think you need the put quotes arround the php code in your JS like:
var x = '<?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>';
ok i fixed it
so var x = '<?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>'; would give me an array, which is what i actually want
but the alert(resposeText); was actually giving me a string so i did this JSON.parse(responseText);
thanks to who helped me get to this answer
after this in both cases if i alert(obj[0]); i get the first element so it is working
my ideal JS function becomes:
function getIDs() {
var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>;
if(x == '') {
$.post('getPL.php','PL_name=cool&q=IDs',function(responseText){
x = JSON.parse(responseText); // this is the difference
});
}
return x;
}
I'm trying to get a grasp on using $.getJSON with an array from PHP.
Here's a simple example where all I want to do is output the requested info. Should the alert(data) return the array object? I am not alerting anything.
PHP file (account.php):
$arr = array('items' => 5,'others' => 6);
echo $arr = json_encode($arr)
HTML file:
$("#unsubscribe").click(function() {
$.getJSON("account.php?", function(data) {
alert(data);
});
});
First of all, it's probably a good idea if you try to load account.php in your browser. You should expect to see:
{"items":5,"others":6}
However, you won't see this. You will instead see a Parse Error, expected ;. Because you forgot it on the echo line.
This is why you see no alert. A PHP error is clearly not valid JSON, and viewing the browser's error console would tell you this ;)
In my projects I am using dump function for viewing json returned array.
Here it is:
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += " ";
if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "'"+"\\n";
if (level < 0)
dumped_text += dump(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => '" + value + "'"+"\\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
I am trying to get list of image path from my db and with help of Jquery and Json triying to add to my site. But I dont know why after encoding my string usingjson_encode` in php it changes it path and shows me like
[{"0":"user\/photogallery\/images\/members\/2\/2_1.jpg","src":"user\/photogallery\/images\/members\/2\/2_1.jpg"},{"0":"user\/photogallery\/images\/members\/2\/2_2.jpg","src":"user\/photogallery\/images\/members\/2\/2_2.jpg"}]
I need only user/photogallery/images/members/2/2_2.jpg part to create new <img src ="user/photogallery/images/members/2/2_2.jpg " /> component.
Here my php code and script
$member_id = $GET['member_id'];
$files = find_all_photos($member_id);
$encoded = json_encode($files);
echo $encoded;
unset($encoded);
function find_all_photos($id)
{
db_connect();
$query = sprintf("SELECT src FROM photo_album_list WHERE user_id = '%s'",
mysql_real_escape_string($id));
$result = mysql_query($query);
$result = db_result_to_array($result);
return $result;
}
function db_result_to_array($result)
{
$res_array = array();
for ($count=0; $row = mysql_fetch_array($result); $count++)
{
$res_array[$count] = $row;
}
return $res_array;
}
And script
$.get('photostack.php', {member_id:2} , function(data) {
console.log(data);
var items_count = data.length;
for(var i = 0; i < items_count; ++i){
var item_source = data[i];
var cnt = 0;
$('<img />').load(function(){
var $image = $(this);
++cnt;
resizeCenterImage($image);
$ps_container.append($image);
var r = Math.floor(Math.random()*41)-20;
if(cnt < items_count){
$image.css({
'-moz-transform' :'rotate('+r+'deg)',
'-webkit-transform' :'rotate('+r+'deg)',
'transform' :'rotate('+r+'deg)'
});
}
if(cnt == items_count){
$loading.remove();
$ps_container.show();
$ps_close.show();
$ps_overlay.show();
}
}).attr('src',item_source);
}
},'json');
It sounds like you're bothered that backslashes are being added prior to the slashes in the path. Completely agree that that's very odd (there's no need whatsoever to "escape" a slash in JSON strings), but in most notations it's harmless to escape a character that doesn't require escaping if that character doesn't have a special escaped meaning. (That is, it's harmless to escape / even though it doesn't need it, but obviously not harmless to escape n even though it doesn't mean it, since \n means something).
To my eyes, the JSON page is silent on what to do with invalid escapes, but Crockford's own parser allows them (disregards the unnecessary backslash), so... (Crockford being the inventor of JSON.)
It's possible that the escaped backslashes are stored in the DB that way, so your JSON string is just pulling them verbatim. If you want to remove them you'll need to process the string returned from the DB before you return or json_encode() them.
Ok, I've been banging my head up against the wall on this and I have no clue why it isn't creating the element. Maybe something very small that I overlooked here. Basically, there is this Javascript code that is in a PHP document being outputted, like somewhere in the middle of when the page gets loaded, NOW, unfortunately it can't go into the header. Though I'm not sure that that is the problem anyways, but perhaps it is... hmmmmm.
// Setting the variables needed to be set.
echo '
<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/shoutbox.js"></script>';
echo '
<script type="text/javascript">
var refreshRate = ', $params['refresh_rate'], ';
createEventListener(window);
window.addEventListener("load", loadShouts, false);
function loadShouts()
{
var alldivs = document.getElementsByTagName(\'div\');
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
var is_counted = 0;
divName = alldivs[i].getAttribute(\'name\');
if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
else if(divName == "undefined")
continue;
else
{
if (divName.indexOf(\'dp_Reserved_Counted\') == 0)
{
is_counted = 0;
shoutCount++;
continue;
}
else
{
shoutCount++;
is_counted = 1;
}
}
// Empty out the name attr.
alldivs[i].name = \'dp_Reserved_Counted\';
var shoutId = \'shoutbox_area\' + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement(\'div\');
shoutHolder.setAttribute(\'id\', [shoutId]);
shoutHolder.setAttribute(\'class\', \'dp_control_flow\');
shoutHolder.style.cssText = \'padding-right: 6px;\';
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
if (is_counted == 1)
{
startShouts(refreshRate, shoutId);
break;
}
}
}
</script>';
Also, I'm sure the other functions that I'm linking to within these functions work just fine. The problem here is that within this function, the div never gets created at all and I can't understand why? Furthermore Firefox, FireBug is telling me that the variable divName is undefined, even though I have attempted to take care of this within the function, though not sure why.
Anyways, I need the created div element to be inserted just before the following HTML:
echo '
<div name="dp_Reserved_Shoutbox" style="padding-bottom: 9px;"></div>';
I'm using name here instead of id because I don't want duplicate id values which is why I'm changing the name value and incrementing, since this function may be called more than 1 time. For example if there are 3 shoutboxes on the same page (Don't ask why...lol), I need to skip the other names that I already changed to "dp_Reserved_Counted", which I believe I am doing correctly. In any case, if I could I would place this into the header and have it called just once, but this isn't possible as these are loaded and no way of telling which one's they are, so it's directly hard-coded into the actual output on the page of where the shoutbox is within the HTML. Basically, not sure if that is the problem or not, but there must be some sort of work-around, unless the problem is within my code above... arrg
Please help me. Really what I need is a second set of eyes on this.
Thanks :)
When you're testing divName, switch the order of your conditions from this
divName = alldivs[i].getAttribute(\'name\');
if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
else if(divName == "undefined")
continue;
to this:
var divName = alldivs[i].getAttribute(\'name\');
if (!divName) // this is sufficient, by the way
continue;
else if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
The problem is that when the script finds a div without a name, it tries to call the indexOf property of a non-existent value and therefore throws an error.
There were a number of issues in the loadShouts method. First being the comparison of a string "undefined" instead of a straight boolean check, which will match. I also removed a bunch of un-needed logic. Beyond this, the id attribute being assigned to the new shoutHolder was being passed in as an array, instead of a direct property assignment.. See if the following works better.
function loadShouts()
{
var alldivs = document.getElementsByTagName("div");
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
divName = alldivs[i].getAttribute("name");
if (!divName)
continue;
if (divName.indexOf("dp_Reserved_Shoutbox") < 0 && divName.indexOf("dp_Reserved_Counted") < 0)
continue;
shoutCount++;
if (divName.indexOf("dp_Reserved_Counted") == 0)
continue;
// Empty out the name attr.
alldivs[i].setAttribute("name", "dp_Reserved_Counted");
var shoutId = "shoutbox_area" + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement("div");
shoutHolder.setAttribute("id", shoutId);
shoutHolder.setAttribute("class", "dp_control_flow");
shoutHolder.style.cssText = "padding-right: 6px;";
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
startShouts(refreshRate, shoutId);
break;
}
}
Ok, just wanted to let you know how it went. And I thank both you greatly Tracker1 and Casey Hope. Especially Tracker for the excellent rewrite of the function. You all ROCK. Here's the final function that I'm using bytheway, just a tiny bit of editing to Tracker1's Answer, which is why you got my vote hands down!
echo '
<script type="text/javascript">
var refreshRate = ' . $params['refresh_rate'] . ';
createEventListener(window);
window.addEventListener("load", loadShouts, false);
function loadShouts()
{
var alldivs = document.getElementsByTagName("div");
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
divName = alldivs[i].getAttribute("name");
if (!divName)
continue;
if (divName.indexOf("dp_Reserved_Shoutbox") < 0 && divName.indexOf("dp_Reserved_Counted") < 0)
continue;
shoutCount++;
if (divName.indexOf("dp_Reserved_Counted") == 0)
continue;
// Empty out the name attr.
alldivs[i].setAttribute("name", "dp_Reserved_Counted");
var shoutId = "shoutbox_area" + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement("div");
shoutHolder.setAttribute("id", shoutId);
shoutHolder.setAttribute("class", "dp_control_flow");
shoutHolder.style.cssText = "padding-right: 6px;";
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
startShouts(refreshRate, shoutId);
break;
}
}
</script>';
Thanks Again, you are the BEST!