Getting php array dynamically in javascript - 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.

Related

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

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.

SyntaxError: missing ; before statement in a html select tag

I have the following java script :
var i = 2;
$(".addmore").on('click', function () {
count = $('table tr').length;
var data = "<tr><td><input type='checkbox' class='case'/></td><td><span id='snum" + i + "'>" + count + ".</span></td>";
data += "\n\\n\
<td><select><?php foreach($commodity_name as $value){?><option><?php echo $value['commodity_name']; ?></option><?php }?></select></td>\n\
<td><input type='text' id='commodity_type" + i + "' name='commodity_type[]'/></td><td><input type='text' id='unit_per_pack" + i + "' name='unit_per_pack[]'/></td><td><input type='text' id='no_of_units" + i + "' name='no_of_units[]'/></td><td><input type='text' id='total_quantity" + i + "' name='total_quantity[]'/></td></tr>";
$('table').append(data);
i++;
});
Which is supposed to populate and auto generate a dropdown, but I keep getting the folloing error :
SyntaxError: missing ; before statement
...on>CREPE BANDAGE 2" DOZENSCREPE BANDAGES 4" DOZ
Which I believe is due to the use of either the following characters ' or " in the database data. Is there a way I can bypass the characters ?
Make sure that , assigning string in variable , you should not use a blank new line while coding in JS , On the otherhand if you want to add new line of html ,use br .
Something used as following
var data = "<tr><td><input type='checkbox' class='case'/></td><td><span id='snum" + i + "'>" + count + ".</span></td>";
data += "<td><select><?php foreach($commodity_name as $value){?><option><?php echo $value['commodity_name']; ?></option><?php }?></select></td>";
data += "<td><input type='text' id='commodity_type" + i + "' name='commodity_type[]'/></td>";
data += "<td><input type='text' id='unit_per_pack" + i + "' name='unit_per_pack[]'/></td>";
data += "<td><input type='text' id='no_of_units" + i + "' name='no_of_units[]'/></td>";
data += "<td><input type='text' id='total_quantity" + i + "' name='total_quantity[]'/></td></tr>";

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.

Outputted results from query outputting, but not allowing some of the results to be selected

I have the following code that is supposed to shuffle results from my database if a user is in group 3, 4 or 5. The query is outputting the results fine, but when I click the button to shuffle the results, the only results that display then are from group 3. I believe the issue in my JS, but I'm not sure where or why it is only shuffling the group 3 results when my query is selecting all users from group 3,4 and 5 and the output shows that.
Lets say:
Bob is group 3
Joe is group 4.
Bill is group 5
The way my page looks is like this.
Users that need shuffled...
-Bob
-Joe
-Bill
Button - Shuffle
When I click on the Shuffle Button. Only Bob shows up.
What is wrong in my code that would do this?
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` IN (3, 4 ,5)");
echo 'Users to be given draft order: <br>';
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
echo $row['firstname'] . ' ' . $row['lastname'] . '<br>';
}
?>
<form method="POST" name="form">
<input type="submit" value="Create Draft Order" name="shuffle">
</form>
Shuffled results: <br>
<div class="main-bag">
<div class="shuffle_results" id="results"></div>
</div>
<form method="post">
<input type="submit" value="Finalize Draft Order" name="insert">
var displayResults = function(data){
var i = 0;
var lineheight = 24;
var time = 3000;
var interval = setInterval(function(){
if( i <= data.length){
console.log( data[i] );
$('#results').append('<div class="result">' +
//'<div class="shuffle_results">' + data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<div class="shuffle_results">' + data[i].drafted_order + ' '+ data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<input type="hidden" name="count[]" value="' + data[i].drafted_order + '">' +
'<input type="hidden" name="firstname[]" value="' + data[i].firstname + '">' +
'<input type="hidden" name="lastname[]" value="' + data[i].lastname + '">' +
'<input type="hidden" name="id[]" value="' + data[i].id + '">' +
'<input type="hidden" name="username[]" value="' + data[i].username + '">' +
'<input type="hidden" name="email[]" value="' + data[i].email + '">' +
'</div>');
var $this = $('.shuffle_results:last');
$this.show().animate({
'left': 0 + 'px',
'bottom': + '0px'
//$(document).height() - (lineheight * data.length)
}, {
duration: time
});
i++;
} else {
clearInterval(interval);
}
}, 3000);
};

Pulling Form Variables through Javascript in a For Loop

I have a webpage that based on user input populates with form fields, as done by the following:
function Go2() {
var loans = document.getElementById('count').value;
var content = document.getElementById('stage3').innerHTML;
content = '<TABLE Width="100%">'
+'<TR>'
+'<TD Style="font-weight:bold;" Width="30%">Customer Name</TD>'
+'<TD Style="font-weight:bold;" Width="30%">Customer Number</TD>'
+'<TD Style="font-weight:bold;" Width="30%">Origination Date</TD>'
+'</TR>'
+'</TABLE>';
document.getElementById('stage3').innerHTML = content;
for(var i=0; i<loans; i++) {
content = document.getElementById('stage3').innerHTML;
document.getElementById('stage3').innerHTML = content
+ '<TABLE Width="100%">'
+ '<TR>'
+ '<TD Width="30%"><INPUT Name="CName'
+ i
+ '" Size="40" Type="text"></TD>'
+ '<TD Width="30%"><INPUT Name="CNumber'
+ i
+ '" Size="40" Type="text"></TD>'
+ '<TD Width="30%"><INPUT Name="Date'
+ i
+ '" Size="40" Type="text"></TD>'
+ '</TR>'
+ '</TABLE>';
}
content = document.getElementById('stage3').innerHTML;
document.getElementById('stage3').innerHTML = content
+ '<TABLE><TR><TD><INPUT Type="Button" Value="Submit" onClick="Go3()"></TD></TR></TABLE>';
}
Now what I need to do is iterate through the form and pull out the values for each of the form fields. This is about as far as I've gotten:
for (var n=0; n<loans; n++) {
content += '<TR>'
+ '<TD Colspan="2">'
+ document.getElementById('CName + n').value
+ '</TD>'
+ '<TD Colspan="2">'
+ document.getElementById('CNumber + n').value
+ '</TD>'
+ '<TD>'
+ document.getElementById('Date + n').value
+ '</TD>'
+ '</TR>';
}
Which does...Nothing. The last notable progress I had was getting it to spit out "null" which isn't really progress at all. I've looked at eval, but there's quite a few warnings against it.
Any Ideas?
I think you want
document.getElementById('CName' + n).value
(where n is outside of the quotes)
Well it should be 'CName' + n - i.e., you got the quotation marks in the wrong place
If all your controls are in a form, then you can access them as:
var allControls = document.<formId>.elements;
or
var allControls = document.forms[formId].elements;
Then iterate over the list of controls to get the values. The form controls must have names to be successful, no need for IDs. You can also get the values as:
var value = allControls['CName' + n].value;
or just
var form = docment.forms[formID];
var value = form['CName' + n].value;

Categories

Resources