Javascript Append function won't duplicate img src on each card - javascript

I have the following code that is suppose to loop through the arrays and print a card out for each one. It works when I hardcode my img src to a path on my computer. When I try and use my image array, my cards stop duplicating. I know my array is populated because I pull from it in another place in my code. I am evidently not putting the right quotes around stuff. Can someone see anything wrong?
var names= <?php echo json_encode($Names); ?>;
var colors= <?php echo json_encode($Color); ?>;
var Images= <?php echo base64_encode($Image); ?>;
//Can use variable as selector, not that I'm using a specific selector
//Try using array of arrays and pick one to each loop over
$(document)
.ready(function() {
$.each(colors,
function(i, value) {
$('.main_card_shell').append(
"<div class='card_content card_style' id='card0'>" +
"<div class='subcard_style box_title'>" +
"<img class='card_image' src='data:image/png;base64, " + Images[i] + "' alt='Item #1' />" +
'<div class="profile">' +
'<div class="card_number">' + value + '</div>' +
'<div class="card_name">' + names[i] + '</div>' +
'<div class="tag_row">' +
'<div class="sample_item sample_item4"></div>' +
'<div class="sample_item sample_item3"></div>' +
'</div>' +
'</div>' +
'</div> ' +
"<div class='subcard_style box_status'>" +

The quotes look fine in my eyes. But because Images is not an array
var Images= <?php echo base64_encode($Image); ?>;
this can't work
"<img class='card_image' src='data:image/png;base64, " + Images[i] + "' alt='Item #1' />"
[update]
In your php code you are using base64_encode($image[$i]). But with
var Images= <?php echo base64_encode($Image); ?>;
you are encoding the array, not the images in the array. Try this instead:
var Images = [];
<?php
for ($i = 0; $i < count($image); $i += 1) {
echo 'Images['.$i.'] = "'.base64_encode($image[$i]).'";';
}
?>
That way the value of each item in your javascript array Images is the base64_encoded
representation of the value in your php array $image.
Make sure, the spelling of $image is right. In your comment you are using $image[0] but in your code snippet it's $Image.

Related

Getting php array dynamically in javascript

With the following code I try to add a new div-element with jQuery.
$(document).ready(function () {
var languages = <?php echo json_encode($languages); ?>;
var div = '';
$.each(languages, function (key, value) {
div = '<div class="main bg_notice" style="padding:3px; line-height:20px;">';
div += ' <img src="/lang/' + value['directory'] + '/admin/images/' + value['image'] + '" alt="' + value['name'] + '" title="' + value['name'] + '" style="border:0;">';
div += ' <b><?php echo TEXT_MASK_ALIAS; ?></b>';
div += ' <input type="text" name="mask_alias[' + value['id'] + ']" value="" style="width:80%" maxlength="255">';
div += '</div>';
$('[name="categories_name[' + value['id'] + ']').closest('div').after(div);
});
});
The value for the input field is created dynamically in PHP
echo (isset($mask_alias[$languages[$i]['id']]) ? stripslashes($mask_alias[$languages[$i]['id']]) : $categories_desc_fields['mask_alias']);
How do I get this into javascript writing style.
$languages[$i]['id']
is equivalent to
+ value['id'] +
in javascript.
The result should look like this non working code
div += ' <input type="text" name="mask_alias[' + value['id'] + ']" value="<?php echo (isset($mask_alias[$languages[$i]['id']]) ? stripslashes($mask_alias[$languages[$i]['id']]) : $categories_desc_fields['mask_alias']); ?>" style="width:80%" maxlength="255">';
var languages = JSON.parse(<?php echo json_encode($languages); ?>)'
You should do part of this in php and part of this in javascript.
I suggest that in PHP, you create a new array based on languages that will be handed to javascript, where all the php-level calculations have been already done.
For example
// php code
// you already have $languages defined
$jsLanguages = array_map(function ($key, $lang) {
$lang['mask'] = isset($mask_alias[$lang['id']]) ? stripslashes($mask_alias[$lang['id']]) : $categories_desc_fields['mask_alias'];
$lang['imageURL'] = "/lang/{$lang['directory']}/admin/images/{$lang['image']}";
return $lang;
}, $languages);
then
$(document).ready(function () {
var languages = <?php echo json_encode($jsLanguages); ?>;
var div = '';
$.each(languages, function (key, lang) {
div = '<div class="main bg_notice" style="padding:3px; line-height:20px;">';
div += ' <img src="' + lang.imageURL + '" title="' + lang.name + '" style="border:0;">';
div += ' <b><?php echo TEXT_MASK_ALIAS; ?></b>';
div += ' <input type="text" name="mask_alias[' + lang.id + ']" value="' + lang.mask + '" style="width:80%" maxlength="255">';
div += '</div>';
$('[name="categories_name[' + lang.id + ']"').closest('div').after(div);
});
});
I suspect languages is a string in json format rather than an actual object.
Try using JSON.parse to convert the string to an object.
var languages = JSON.parse(<?php echo json_encode($languages); ?>);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

Ajax Webpage Not Displaying Most Update to Date Content After Redirect

I have page that displays images from different directories and can change the file names of files in a folder, based on their order in a jQuery sortable list.
So far everything is working except that after I Save the new file names and the Save page redirects to the Edit page I have to do a "Empty Cache and Hard Reload" in order for the new file order to be displayed.
Edit Page
<!DOCTYPE html>
<?php
session_start();
if (!$_SESSION['username']) {
echo "<script>window.location = './index.php'</script>";
}
?>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Cache-control" content="no-cache">
<meta http-equiv="Expires" content="-1">
<link rel="stylesheet" href="../js/jquery/jquery-ui-1.11.4/jquery-ui.css">
<script src="../js/jquery/jquery-2.1.4.min.js"></script>
<script src="../js/jquery/jquery-ui-1.11.4/jquery-ui.js"></script>
<script>
$(window).load(function() {
$(document).ready(function() {
$("#btnRefresh").click(function() {
window.location.reload(true);
});
$.ajax({
url: 'getPics.php',
success: function(resultOfAjaxCall) {
xmlDoc = $.parseXML(resultOfAjaxCall);
$xml = $(xmlDoc);
html = "";
$xml.find('Folder').each(function(index) {
//console.log($(this).attr('Name'));
city = $(this).attr('Name');
html += "<h3 class='accordion-header'>" + city + "</h3>";
html += "<div class='accordion-section'>";
html += "<button id='" + city + "_Save'>Save " + city + "</button>";
html += " ";
//Upload Form
html += '<form enctype="multipart/form-data" action="uploader.php" method="POST">';
html += '<input type="hidden" name="MAX_FILE_SIZE" value="100000" />';
html += '<input type="hidden" name="City_Folder" value="' + city + '" />';
html += 'Choose a file to upload: <input name="userfile" type="file" /><br />';
html += '<input type="submit" value="Upload File" />';
html += '</form>';
//Save Form
html += '<form enctype="multipart/form-data" action="save.php" method="POST" id="' + city + '_Save_Form">';
html += '<input type="hidden" name="City_Folder" value="' + city + '" />';
html += '</form>';
html += "<ul class='" + city + "-sortable-list'>";
$(this).find('File').each(function(index) {
//console.log($(this).text()
fileName = $(this).find('File_Name').text();
filePath = $(this).find('File_Path').text();
fileRealPath = $(this).find('File_Real_Path').text();
//console.log(fileName);
//console.log(filePath);
html += '<form enctype="multipart/form-data" action="delete.php" method="POST" id="' + fileName + '_Delete_Form">';
html += '<input type="hidden" name="Delete_Path" value="' + filePath + '" />';
html += '</form>'
html += "<li id='" + fileName + "' class='ui-state-default' value='" + fileRealPath + "'>" + fileName + " ";
html += "<button id='" + fileName + "_Delete'>Delete</button>";
html += "<br>"
html += "<img src='" + filePath + "' style='width:150px;'/>";
html += "<br></li>";
})
html += "</ul>";
html += "</div>";
//window.location.reload(true);
});
$("#accordion").append(html);
var $accordion = $("#accordion").accordion({
collapsible: true,
heightStyle: "content",
active: false
});
$("[class$=-sortable-list]").sortable({
update: function(event, ui) {
console.log(ui);
var order = [];
$("[class$=-sortable-list] li").each(function(e) {
order.push($(this).attr("id") + "=" + ($(this).index() + 1));
});
var positions = order.join();
// alert(positions);
},
stop: function(event, ui) {
console.log("an item was moved");
$accordion.find("#tmp").remove();
},
start: function(event, ui) {
$accordion.append("<ul id='tmp'></ul>");
$accordion.find("#tmp").append(ui.item);
}
}).disableSelection();
//Save Click
$("[id$=_Save_Form]").submit(function(event) {
folder = event.target.id.replace("_Save_Form", "");
$("." + folder + "-sortable-list li").each(function(e) {
//alert(folder);
//alert($(this).index());
//alert($(this).attr("value"));
$("<input />").attr("type", "hidden")
.attr("name", "path[" + $(this).index() + "]")
.attr("value", $(this).attr("value"))
.appendTo("#" + event.target.id);
});
});
$("[id$=_Save]").click(function(event) {
$("#" + event.target.id + "_Form").submit();
});
}
});
});
});
</script>
<title>Edit Slider</title>
</head>
<body>
<?php ?>
<p>You are logged in as <?= $_SESSION['username'] ?> (Logout)</p>
<p><button id="btnRefresh">Refresh</button></p>
<div id="accordion">
</div>
</body>
</html>
Save Page
<?php
$root = filter_input(INPUT_SERVER, "DOCUMENT_ROOT", FILTER_SANITIZE_STRING, FILTER_SANITIZE_MAGIC_QUOTES);
require $root . '/CC_Library/CC_Folder.php';
require $root . '/CC_Library/CC_String.php';
$folder = filter_input(INPUT_POST, "City_Folder", FILTER_SANITIZE_STRING, FILTER_SANITIZE_MAGIC_QUOTES);
$dir = "";
$i = 0;
$s = new CC_String;
$tmp = $s->generate_rand(5);
foreach ($_POST['path'] as $value) {
$CC = new CC_File($value);
$dir = $CC->get_File_Dir();
echo "Changing " . $CC->get_Full_File_Name() . " to " . $tmp . str_pad($i, 10, '0', STR_PAD_LEFT) . "." . $CC->get_File_Extension() . "<br>";
$CC->Rename($tmp . str_pad($i, 10, '0', STR_PAD_LEFT) . "." . $CC->get_File_Extension());
$i++;
}
$j = 0;
//echo $dir;
$F = new CC_Folder($dir);
$Files = $F->get_Folder_Files();
foreach ($Files as $value) {
echo "Changing " . $value->get_Full_File_Name() . " to " . $folder . "-" . str_pad($j, 8, '0', STR_PAD_LEFT) . "." . $value->get_File_Extension() . "<br>";
$value->Rename($folder . "-" . str_pad($j, 8, '0', STR_PAD_LEFT) . "." . $value->get_File_Extension());
$j++;
}
echo "<script>window.location.replace('Edit_Slider.php')</script>";
I dont want to read all of that notorious code. Your problem is client sided, not server sided so your code is irreverent.
Your webbrowser is caching and not updating your images. A fix for this would be to extend the current image source with a timestamp like so:
<img src="image.jpg?lastmod=12345678"
//javascript
function(img_src){
var timestamp = (new Date()).getTime();
img_src += "lastmod?" + timestamp;
}
how to clear or replace a cached image
The reason this works is because the source URL is different each time because of the timestamp will always be different & web browsers remember content relative to the URL.

display parsing json to radio button

I want to loop data of json and display to the radio button on html,
var link = "http://localhost/codeigniter/load";
var selector = "#result-media-uploader";
$.getJSON(link,function(data){
$.each(data,function(i,item){
var openTag = "<div class='col-lg-2'>";
var closeTag = "</div>";
openTag += "<input id='media-radio' type='radio' name='media-radio' value='"+item.id+"'>";
openTag += "<label class='label'><img width='100%' height='100%' src='"+item.post_content+item.post_title+"'></label>";
openTag += closeTag;
$(selector).append(openTag);
});
});
request is sended but in the output is none..
this is the server code
$data = $this->db->where('post_type','attachment')->where('post_mine_type','image')
->get('cs_posts')->result_array();
return json_encode($data);
I'm new on javascript, can you explain my mistake.. thanks for your help..
try this,
openTag += "<label class='label'><img width='100%' height='100%' src='"+item.post_content+""+item.post_title+"'></label>";
$("+selector+").append(openTag);
thanks guys.. (y)
this the final code..
js file
var folder = "/codeigniter";
var url = window.location.protocol+"//"+window.location.host+folder+"/admin/uploads/load";
$('#refresh-media-uploader').click(function(){
$.getJSON(url,function(data){
$.each(data,function(i,item){
var openTag = "<div class='row'><div class='col-lg-2'>";
var closeTag = "</div></div>";
openTag += "<input id='media-radio' type='radio' name='media-radio' value='"+item.id+"'>";
openTag += "<label class='label'><img width='100%' height='100%' src='"+item.post_content+"100x100-"+item.post_title+"'></label>";
openTag += closeTag;
$("#result-media-uploader").append(openTag);
});
});
});
and sirver side
$data = $this->db->where('post_type','attachment')->where('post_mine_type','image')
->get('cs_posts')->result_array();
echo json_encode($data);

PHP jQuery "unterminated string literal" error in onclick handler

I'm using PHP to pass variables into the onclick of an element, however when I do this I get an "Unterminated string literal" error of the string is too long. My PHP is as follows:
$query = $conn->prepare("SELECT Name, Image, Description, Link, Price, ID FROM gallery ORDER BY ID desc");
$query->execute();
$query->bind_result($name, $img, $desc, $link, $price, $id);
while($query->fetch())
{
if(strlen($desc) > 100)
{
$sdesc = substr($desc, 0, 100) . '...';
}
$onclick = 'popup(\'' . $name . '\', \'' . $desc . '\', \'' . $price . '\', \'' . $img . '\', \'' . $link . '\', ' . $id . ')';
echo '<div class="gallery" onclick="' . $onclick . '">
<img src="' . $img . '" alt="' . $name . '" />
<div><p>' . $sdesc . '</p>
' . $price . '
</div></div>';
}
My jQuery is as follows
function popup(title, desc, price, img, link, id)
{
$(".popupbodyg").children().remove();
var HTML = '<input type="image" src="close.gif" id="close" /><div><div id="comments">' +
'<iframe src="comments.php?id=' + id + '"></iframe><br /><input type="image" id="share" src="Very-Basic-share-icon.png" /></div>' +
'<div id="desc"><p>' + desc + '</p><br />' +
'<a class="gallery" href="' + link + '" target="_blank">' + price + '</a></div>' +
'<div id="img"><img src="' + img + '" alt="' + title + '"/></div></div>';
$(".popupbodyg").append(HTML);
$("#popup").toggle();
$(".popupbodyg #img").css("width", $(".popupbodyg").width() - 230 + "px");
$(".popupbodyg #img").css("height", $(".popupbodyg").height() - ($("#desc").height - 5) + "px");
$("#close").click(function(){
$("#popup").hide();
});
$("#share").click(function(){
$("#sharepopup").show();
$("#sharepopup").find("#link").attr("value", "http://www.encantojewellerydesign.com/gallery/?g=" + id);
$("#sharepopup").find(".fb-share-button").attr("data-href", "http://www.encantojewellerydesign.com/gallery/?g=" + id);
$("#sclose").click(function(){
$("#sharepopup").hide();
});
});
}
The only way I can think of right now is by limiting the amount of characters in the description, which I would like to avoid.
Did you try any of the string replace methods that are found elsewhere on SO?
$desc=str_replace("\n","\\n",$desc); //I'm guessing that the newline would probably be in the description if anywhere in the data you're passing.
ALSO:
Another slightly different approach would be to just embed the data into your element and retrieve the data with a single click handler that passes it to your popup function.
In other word, you could change the div.gallery look like this:
<div class="gallery" data-name=".$name." data-img=".$img." data-desc=".$desc." data-link=".$link." data-price=".$price." data-id=".$id.">
Then add an click handler like this:
$('gallery').on('click', function() {
var name = $(this).data('name');
var img = $(this).data('img');
var desc = $(this).data('desc');
var link = $(this).data('link');
var price = $(this).data('price');
var id = $(this).data('id');
popup(title, desc, price, img, link, id);
});
I am assuming that it has to do with the extra html characters that $description and other variables are passing to yout js. Try may be something like this(for a better answer, post a dump of the variables you are passing):
<?php
$query = $conn->prepare("SELECT Name, Image, Description, Link, Price, ID FROM gallery ORDER BY ID desc");
$query->execute();
$query->bind_result($name, $img, $desc, $link, $price, $id);
while($query->fetch())
{
if(strlen($desc) > 100)
{
$sdesc = substr($desc, 0, 100) . '...';
}
$onclick = 'popup(\'' .strip_everything( $name ). '\', \'' . strip_everything($desc ). '\', \'' .strip_everything $price) . '\', \'' . $img . '\', \'' . $link . '\', ' . $id . ')';
echo '<div class="gallery" onclick="' . $onclick . '">
<img src="' . $img . '" alt="' . $name . '" />
<div><p>' . $sdesc . '</p>
' . $price . '
</div></div>';
}
function strip_everything($str){
$str = strip_tags($str);
return str_replace("\n" , ' ' , $str);
}

Calling a Javascript function from PHP with variables created in php

I have a javascript function in a file comment_insert.js:
function comment_insert(data,ul_id) {
var t = '';
t += '<li class="comment-holder" id="_' + data.comment_id + '">';
t += '<div class="user-img">';
t += '<img src="' + data.profile_img + '" class="user-img-pic" />';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field" >' + data.Username + '</h3>';
t += '<div class="comment-text">' + data.comment + '</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">[x]</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('#' + ul_id).prepend(t);
}
I want to call this function from a php file display.php as:
$smthng = new stdClass();
$smthng->comment_id = 24;
$smthng->Userid = 1;
$smthng->comment = "Hard coded comments";
$smthng->Username = "Sagar_username";
//$smthng->profile_img = "images/Setting-icon.png";
$data = json_encode($smthng);
$ul_id = "ul218";
comment_insert(jQuery.parseJSON($data),$ul_id);
The function being called is the same as in comment_insert.js which accepts 2 inputs (data and ul_id). These are being created in display.php and then I want to execute the function.
Assuming that the PHP code is in the same file as Javascript and is being used for front end out put to the browser, you can do this:
<?php
$smthng = new stdClass();
$smthng->comment_id = 24;
$smthng->Userid = 1;
$smthng->comment = "Hard coded comments";
$smthng->Username = "Sagar_username";
//$smthng->profile_img = "images/Setting-icon.png";
$data = json_encode($smthng);
$ul_id = "ul218";
?>
<script type="text/javascript">
comment_insert(jQuery.parseJSON(<?php echo $data ?>), <?php echo $ul_id ?>);
</script>
However, if this is not in a file that is producing output to the browser, you cannot execute Javascript server-side
In order to execute Javascript in PHP you'll need to install the V8js Extension.
After installing you should parse your comment_insert.js to a PHP variable via file_get_contents and execute it somehow like this:
<?php
$v8 = new V8Js();
/* Get you js file's content */
$JS = file_get_contents("PATH/TO/JS-FILE/comment_insert.js");
try {
$v8->executeString($JS, 'basic.js');
} catch (V8JsException $e) {
var_dump($e);
}
?>
Note: In order to make it work, I think you'll replace the jQuery call with native JS.
So modify you comment_insert.js to something like this:
function comment_insert(data,ul_id) {
var t = '';
t += '<li class="comment-holder" id="_' + data.comment_id + '">';
t += '<div class="user-img">';
t += '<img src="' + data.profile_img + '" class="user-img-pic" />';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field" >' + data.Username + '</h3>';
t += '<div class="comment-text">' + data.comment + '</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">[x]</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
//$('#' + ul_id).prepend(t);
elem = document.getElementById(ul_id);
elem.insertBefore(t);
}

Categories

Resources