firefox issue with js slider - javascript

I have this slider and it works fine in IE and chrome but has a problem in firefox, it loads all the picture one time but it does not go back again and load them, in the console i get this error
"SyntaxError: missing ] after element lis" in the line of setTimeout(func,900)
this is the code
function pic_loader() {
//alert('s');
var func = new function () {}
$folder = $('#foldername').attr('value');
$files = document.getElementById('filename').value;
$num = document.getElementById('num').value;
$filenames = $files.split("##");
var $img = [];
var $link = [];
if ($num > 1) {
for ($i = 1; $i <= $num; $i++) {
$img[$i] = $folder + "/" + $filenames[$i];
if ($i == 1) {
$link[$i] = "<img id='slide[" + $i + "]' width=380 src=" + $img[$i] + ">";
$("#load_here").append($link[$i]);
$first = document.getElementById('slide[1]');
$first.style.display = "none";
$($first).fadeIn(800);
} else {
$link[$i] = "<img id='slide[" + $i + "]' width=380 src=" + $img[$i] + " style='display:none'>";
$("#load_here").append($link[$i]);
}
}
$i = 1;
var $loop = setInterval(function () {
//alert('x');
$j = $i + 1;
$current = document.getElementById('slide[' + ($i++) + ']');
$next = document.getElementById('slide[' + ($j) + ']');
$($current).fadeOut(800, function () {
$($next).fadeIn(800);
});
if ($j > $num) {
$($next).fadeOut(800);
setTimeout(func, 900);
function func() {
clearInterval($loop);
$("#load_here").html("");
pic_loader();
}
}
}, 4500);
} else {
$i = 1;
$img[$i] = $folder + "/" + $filenames[$i];
$link[$i] = "<img id='slide[" + $i + "]' width=380 src=" + $img[$i] + ">";
$("#load_here").append($link[$i]);
}
}

There is no syntax error in the code you pasted. It must be elsewhere. Paste it into jsfiddle, it does not throw a syntax error.

First of all, id attribute cannot contains [ or ] character.
You can use name atrribute in place od id or create id like slide_1,slide_2,....
Using name attribute you can use function like :
$current = document.getElementsByName('slide[' + ($i++) + ']');
This post can help you more about your problem Accessing an array of HTML input text boxes using jQuery or plain Javascript

Related

If I click on Tab, it doesn't response. Why?

Problem is I cannot click the Tabs on the website and If i click on Tabs; it show
Uncaught Type Error: Cannot set properties of null (setting 'value').
Is there any way to fix this? Also, I am a beginner and I don't know how to fix this. Codes are written in PHP and Javascript.
<?php
// session_start();
require("checklogin.php");
$toolsname = "Matrix Setup";
$toolsnamepath = "index.php";
$userlogin = $loginname;
$usrgroup = $_SESSION["usrgrp"];
$str_tab = isset($_POST["str_tab"])? $_POST["str_tab"] : "";
$winwidth = isset($_POST["winwidth"])? $_POST["winwidth"] : "";
$ch = isset($_POST["ch"])? $_POST["ch"] : "";
$badgeno = isset($_SESSION["badgeno"])? $_SESSION["badgeno"] : "";
if($str_tab == ""){
$str_tab = isset($_GET["str_tab"])? $_GET["str_tab"] : "";
}
if($winwidth == ""){
$winwidth = isset($_GET["winwidth"])? $_GET["winwidth"] : "";
}
if($ch == ""){
$ch = isset($_GET["ch"])? $_GET["ch"] : "";
}
echo "<html>";
echo "<head><title>$toolsname</title>";
echo "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=5\">";
echo "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">";
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"\web/css/lotmgt_edge.css\"/>";
echo "<script src=\"lotmgt.js\"></script>\n";
echo "<script src=\"setup/setup.js\"></script>\n";
echo "<script src=\"productmatrix/productmatrix.js\"></script>\n";
echo "<script src=\"simulator/simulator.js\"></script>\n";
echo "<script src=\"addmatrix/addmatrix.js\"></script>\n";
echo "<script src=\"addAVImatrix/addmatrix.js\"></script>\n";
echo "<script src=\"\web/js/eregister/pointer.js\" type=\"text/javascript\"></script>";
echo "</head>";
echo "<body onload=OnLoad('" . $ch . "','" . $badgeno . "')>";
//include($_SERVER['DOCUMENT_ROOT']."\library\common\apewsheader.php");
//include($_SERVER['DOCUMENT_ROOT']."\library\common\db_config.inc");
//include($_SERVER['DOCUMENT_ROOT']."\library\common\standard_defines.inc");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/apewsheader.php");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/db_config.inc");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/standard_defines.inc");
include("editme.php");
echo "<form name=\"lotmgt\" method=\"post\" target=\"_self\" onsubmit=\"return false;\">";
echo "<div style=\"position:relative; top:20px;\">";
echo "<table cellpadding=\"3\" cellspacing=\"0\" border=\"0\" width=\"99%\">";
echo "<tr>";
echo "<td>";
for($c=0;$c<count($ary_tab);$c++) {
$class_tab = (($ch=="ProductMatrix" && $ary_tab[$c]=="Product Matrix" && (!isset($str_tab) || $tr_tab=="")) || ($ch=="SocketSimulator" && $ary_tab[$c]=="Socket Simulator" && (!isset($str_tab) || $str_tab=="")) || ($ch=="AVIMatrixAdd" && $ary_tab[$c]=="AVI Matrix Add" && (!isset($str_tab) || $str_tab=="")) || ($ch=="SetupPostTest" && $ary_tab[$c]=="Setup PostTest" && (!isset($str_tab) || $str_tab=="")) || ($ch=="Setup" && $ary_tab[$c]=="Setup" && (!isset($str_tab) || $str_tab=="")) || (($c==0 && !isset($str_tab)) && $ch=="") || $ary_tab[$c] == $str_tab)? "link_tab_slct" : "link_tab";
echo "" . $ary_tab[$c] . "";
}
echo"</td>";
echo"</tr>";
echo"</table>";
echo "</div>";
//echo $str_tab;
if($str_tab != ""){
switch($str_tab){
case "Setup":
include("setup/setup.php");
break;
case "Setup PostTest":
include("setup/setup.php");
break;
case "Setup1":
include("setup1/setup.php");
break;
case "Product Matrix":
include("productmatrix/productmatrix.php");
break;
case "Socket Simulator":
// include("simulator/simulator.php");
include("simulator/Socket_simulator.php");
break;
// case "Matrix Add":
// include("addmatrix/addmatrix.php");
// break;
case "AVI Matrix Add":
include("addAVImatrix/addmatrix.php");
break;
}
}
else {
if ($ch=="ProductMatrix") {
include("productmatrix/productmatrix.php");
}
else if($ch=="SocketSimulator"){
// include("simulator/simulator.php");
include("simulator/Socket_simulator.php");
}
else if($ch=="AVIMatrixAdd"){
include("addAVImatrix/addmatrix.php");
}
else if($ch=="Setup"){
include("setup/setup.php");
}
else if($ch=="SetupPost6E"){
include("setup/setup.php");
}
else{
include("setup/setup.php");
}
}
//common
echo "<input type=\"hidden\" name=\"str_tab\" value=\"" . $str_tab . "\">";
echo "<input type=\"hidden\" name=\"winwidth\" value=\"" . $winwidth . "\">";
echo "<input type=\"hidden\" name=\"username\" value=\"" . $loginname . "\">";
echo "</form>";
flush();
mysqli_close($conn);
echo "</body>";
echo "</html>";
?>
Above codes are index.php codes.
var winplanproducttoentity = '';
var winupdateauto = '';
var winupdatebytester = '';
var winupdatebyproduct = '';
var winupdatestatus = '';
var wintestlot = '';
var winassignlot = '';
var winshowlot = ''
var winchecksicom = '';
var w;
var winwidth = window.screen.width;
var div = new Array('outputdiv','setupdiv');
//var div = new Array('outputdiv','setupdiv','availdiv');
var reqHttp = InitRequest();
var reqHttp1 = InitRequest();
var reqHttp2 = InitRequest();
var reqHttp3 = InitRequest();
function InitRequest() {
var request=null;
try {
request=new XMLHttpRequest();
}
catch (e) {
try {
request=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
request=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return request;
}
function AsynReqData(request,url,fn) {
request.open("GET", url + '&sid=' + Date() + Math.random(), true);
request.onreadystatechange = eval(fn);
request.send(null);
}
function SynReqData(request,url) {
request.open("GET", url + '&sid=' + Date() + Math.random(), false);
request.send(null);
return request.responseText;
}
function DisplayTab(tabname,tabid) {
document.getElementById(tabid).value = tabname; // this is the $str_tab
document.lotmgt.submit();
}
function OnLoad(ch,badgeno){
var tab = document.lotmgt.str_tab.value; // this is the $str_tab from DisplayTab function
w = (winwidth < 1280)? 1280 : winwidth;
if((tab=='' & ch=='') || tab=='Setup' || (ch=='Setup' & tab=='')) {
var p_1 = "checked";
var T_0 = "checked";
var zmiss = "checked";
for(var i=0; i<div.length; i++) {
document.getElementById(div[i]).className = 'hide';
}
// var wd = (128*5) - 10;
var wd = (128*7.5) - 50;
var lf = 0;
document.getElementById('filterdiv').style.width = wd + 'px';
document.getElementById('filterdiv').style.left = lf + 'px';
wd = (128*5.5) - 80;
lf = (128*5) - 10; // lf = (128*7) - 20;
document.getElementById('waferdiv').style.width = wd + 'px';
document.getElementById('waferdiv').style.left = lf + 'px';
// AsynReqData(reqHttp,'setup/content_wafer.php?site=','UpdateWafer');
AsynReqData(reqHttp1,'setup/content_filter.php?site=' + '' + '&badgeno=' + badgeno + '&p_1=' + p_1 + '&T_0=' + T_0 + '&zmiss=' + zmiss,'UpdateFilter');
}
else if (tab=='Product Matrix' || (ch=='ProductMatrix' & tab=='')){
AsynReqData(reqHttp,'productmatrix/content_filter.php?area=','UpdatePMFilter');
}
// else if (tab=='Matrix Simulator' || (ch=='MatrixSimulator' & tab=='')){
// // AsynReqData(reqHttp,'simulator/content_filter.php?area=','UpdateSIMFilter');
// }
else if (tab=='Setup PostTest' || (ch=='SetupPostTest' & tab=='')){
var p_1 = "checked";
var T_0 = "checked";
var wd = (128*9) - 50;
var lf = 0;
document.getElementById('filterdiv').style.width = wd + 'px';
document.getElementById('filterdiv').style.left = lf + 'px';
AsynReqData(reqHttp1,'setup/content_filter1.php?site=' + '' + '&badgeno=' + badgeno + '&p_1=' + p_1 + '&T_0=' + T_0,'UpdateFilter');
}
}
//shared functions
function ManagePopup(except){
var mywin = new Array('winplanproducttoentity','winupdateauto','winupdatebytester','winupdatebyproduct','winupdatestatus','wintestlot','winassignlot','winshowlot','winchecksicom');
for(var i=0; i<mywin.length; i++) {
var win = window[mywin[i]];
if (mywin[i] == except){
if(!win.closed && win.location) win.focus();
}
else{
if(!win.closed && win.location) win.close();
}
}
}
function PlanProductToEntity(product,type){
var w = 300;
var h = 600;
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
var winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no';
ManagePopup('winplanproducttoentity');
winplanproducttoentity = this.open('../lotmgt/wip/pop_assignproduct.php?product=' + product + '&type=' + type, 'winplanproducttoentity', winprops);
}
Above codes are Javascript codes. Error says in Javascript and How to fix that?
The error occurs in the JS code and is due to the HTML generated in PHP which is missing an id attribute.
You seem to get the error here: document.getElementById(tabid).value = tabname; because document.getElementById(tabid) is null.
When it looks for the element with id str_tab it doesn't find it. The only element in the HTML which could be the desired one has the attribute name="str_tab" and it's your hidden field. You have to add the missing id="str_tab" attribute to this hidden field.

Suggest a way to store the value form csv into dropdown with javascript variable perform operations on it

<script> //script loading the csv and reading the files to out into an array of variables which are used in dropdown
var $csvData = [],
$colNames = [];
function _ReadCSV($a) {
var $f = $a.files[0];
if($f) {
var reader = new FileReader();
reader.onerror = function($e) {
div.innerHTML = 'The file can\'t be read! Error ' + $e.target.error.code;
}
reader.onload = function($e) {
var $data = $e.target.result.split("\n");
$colNames = $data[0].split(","); //split to separate the column inside the csv
$data.splice(0, 1);
for(var $b = 0; $b < $data.length; $b++) {
var $tmpJSON = {},
$colData = $data[$b].split(",");
for(var $c = 0; $c < $colData.length; $c++) $tmpJSON[$colNames[$c]] = $colData[$c];
$csvData.push($tmpJSON);
document.getElementById("try").innerHTML = "Value: "+ $colData; //just to check the value
}
_CreateDropdown();
}
reader.readAsText($f);
}
}
function _CreateDropdown() {
var $tmpHTML = '<select onchange="_UpdateFields(this.value)">';
for(var $a = 0; $a < $csvData.length; $a++) $tmpHTML += '<option value="' + $a + '">' + $csvData[$a][$colNames[0]] + '</option>';
$tmpHTML += '</select>';
document.getElementById("dropdown").innerHTML = $tmpHTML;
_UpdateFields(0);
}
function _UpdateFields($a) {
var $values = '';
for(var $b = 0; $b < $colNames.length; $b++) {
console.log($colNames[$b], $csvData[$a][$colNames[$b]]);
if($csvData[$a][$colNames[$b]] != "") $values += $colNames[$b] + ': <input id="' + $colNames[$b] + '" name="' + $colNames[$b] + '" type="text" value="' + $csvData[$a][$colNames[$b]] + '" /><br />';
}
document.getElementById("fields").innerHTML = $values;
}
window.onload = function() {
document.getElementById('fileBox').onchange = function(){ _ReadCSV(this); }
}
</script>
Currently I have two columns in csv and need to pick the value of one of the column item. Which is selected upon the dropdown selected by the user and then need to modify the value. The $values variable stores both the columns values.

How can I escape from PHP code inside Javascript?

var i = 1;
$("#add_row").click(function(){
var arr = "<tr><td><input type='hidden' name='counter' value='" + i + "'><input type='hidden' id='pd-id-" + i + "' name='pd-id-" + i + "'><input autocomplete='off' type='text' id='pd-search-" + i + "' class='hahaha'><ul style='width: 44.8vw' class='livesearch' id='pd-result-" + i + "' onclick='clickResult()'></ul></td><td><input type='text' required name='workdescription-" + i + "'></td><td><select></select></td><?php
$date = new DateTime();
$y=1;
if (date('d') < '18' AND date('d') > '2') {
for ($x = 1 ; $x <= 16 ; $x++) {
echo "<td><input type='text' name='hr-" . i . "-" . $x . "'></td>";
}
} else if (date('d') < '3') {
for ($x = 16 ; $x <= date('t', strtotime(date('Y-m')." -1 month")) ; $x++) {
echo "<td><input type='text' name='hr-" . i . "-" . $y . "'></td>";
$y++;
}
} else {
for ($x = 16 ; $x <= date('t') ; $x++) {
echo "<td><input type='text' name='hr-" . i . "-" . $y . "'></td>";
$y++;
}
}
$i++;
?></tr>"
;
i++;
$( "#tablebody" ).append(arr);
});
I need to escape the letter i inside the echo of the PHP. I want them to have the value of the javascript variable i at the top. How may I do this? Also is there a better way to do this?
Like I said in a comment above, there 's no need for PHP in this case. You can solve it with Javascript only. To answer your question correctly, here 's a possible solution with Javascript and PHP.
<table id="my-table">
<tr>
</tr>
</table>
<template id="my-template">
<td><input type="text" name=""></td>
</template>
<script>
var day = '<?= (new DateTime())->format('d') ?>',
daysOfMonth = '<?= (new DateTime())->format('t') ?>',
daysOfMonthOneMonthBefore = '<?= (new DateTime('-1 month'))->format('t') ?>',
template = document.getElementById('my-template'),
i = 1,
y = 1;
var positiveInt = new Number(day),
positiveIntOneMOnthBefore = new Number(daysOfMonthOneMonthBefore),
inputElement = template.content.querySelector('input');
if (positiveInt < 18 && positiveInt > 2) {
for (var x = 1; x <= 16; x++) {
inputElement.name = 'hr-' + i + '-' x;
var clone = document.importNode(template.content, true);
document.querySelector('#my-table tr').appendChild(clone);
}
} else if (positiveInt < 3) {
for (var x = 16; x <= positiveIntOneMOnthBefore; x++) {
inputElement.name = 'hr-' + i + '-' + y;
y++;
var clone = document.importNode(template.content, true);
document.querySelector('#my-table tr').appendChild(clone);
}
} else {
for (var x = 16; x <= positiveInt; x++) {
inputElement.name = 'hr-' + i + '-' + y;
y++;
var clone = document.importNode(template.content, true);
document.querySelector('#my-table tr').appendChild(clone);
}
}
</script>
As you said you need only the actual date from the server. The rest of the code is done with native javascript. You don t even need jQuery for this. This code example is not tested. This code uses HTML5 elements like the template tag. Make sure you are using the right HTML5 doctype. Beside that it should show you a possible way how to solve your issue.
Try your echos like this:
echo "<td><input type='text' name='hr-' + i + '-" . $x . "'></td>";
Remember that all the php code gets completely parsed server-side. Javascript is client side. Don't confuse javascript and php syntax. Concating with . is php, + is the javascript equivalent. Also use quotes consistently. E.g. " in php and ' in javascript. If you need " in Javascript, escape it like so: \".

Getting an image source from JSON data

I'm attempting to call a PHP file and have it return a result (a single record's 'pageLocation') from a database table ('page'). I then want to get that result into a variable, so I can use it while creating an image in html.
Currently, the image is being created but the source is not feeding into it, leaving a default empty image at the correct size.
Javascript:
// Loads a list of comics created by the user from the database.
function loadComic()
{
var xmlhttp = new XMLHttpRequest();
var getID = '<?php echo $_SESSION["userID"]; ?>';
var url = "loadCom.php?userID="+getID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
loadComicJSON(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
// JSON parsing for 'loadComic'.
function loadComicJSON(response)
{
var arr = JSON.parse(response);
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
//Non-relevant code affecting layout if no comics are found.
}
else
{
out+="<br>";
for(i = 0; i < arr.length; i++)
{
// Gets image source from database.
imgSrc = "";
tempID = arr[i].comicID;
$.post("getCover.php", {'comicID':tempID}, function(result)
{
imgSrc += ("" + result);
}
);
// Creates image item and associated radio button.
out += "<hr><br><img name = '" + ('com' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='" + imgSrc + "'><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br>";
}
}
}
</script>
PHP (getCover.php):
<?php
if (isset($_POST["comicID"]))
{
include_once('includes/conn.inc.php');
$checkID = $_POST["comicID"];
$query = ("SELECT FIRST (pageLocation) FROM page WHERE comicID = '$checkID' ORDER BY pageNum");
$result = mysqli_query($conn, $query);
$conn->close();
echo ($result);
}
else
{
$checkID = null;
echo "Error. No comic found.";
}
?>
Thanks for any help provided.
You need to get he data from the result, like:
$row = $result->fetch_assoc()
Also, yes, Jim G is right, you need to escape that POST variable.

XML or text declaration not at start of entity error - PHP and Javascript

Hi I'm trying to get the xml data from php to javascript using DOM document and it keeps giving me : XML or text declaration not at start of entity error.(on firebug)
I tried saving it to a real xml file and it outputs a well formatted xml.
I guess the reason for this is white space on top of the xml file. I tried using ob_start(); and ob_end_flush(); but couldn't get that working
BTW I'm new to Ajax!
JS script
var xh = createRequest();
var xhrObject = false;
if (window.XMLHttpRequest)
{
xHRObject = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xHRObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData()
{
if ((xh.readyState == 4) &&(xh.status == 200))
{
alert("hi");
var serverResponse = xh.responseXML;
var header = serverResponse.getElementsByTagName("good");
var spantag = document.getElementById("sp");
var x;
spantag.innerHTML = "";
x = "<table cellpadding='1' cellspacing='6' border='0'>";
x += "<tr><td>ID</td><td>price</td><td>quantity</td><td>Total</td><td>Remove</td></tr>";
for (i=0; i<header.length; i++)
{
var id = header[i].getElementsByTagName("ID")[0].childNodes[0].nodeValue;
var price = header[i].getElementsByTagName("price")[0].childNodes[0].nodeValue;
var qty = header[i].getElementsByTagName("quantity")[0].childNodes[0].nodeValue;
var total = header[i].getElementsByTagName("total")[0].childNodes[0].nodeValue;
if(qty=="0")
{
continue;
}
x += "<tr>"
+ "<td>" + id + "</td>"
+ "<td>" + price + "</td>"
+ "<td>" + qty + "</td>"
+ "<td>" + total + "</td>"
+ "<td>" + "<a href='#' onclick='AddRemoveItem(\"Remove\","+id+");'>Remove Item</a>" + "</td>"
+ "</tr>";
}
x += "</table>";
if (header.length != 0)
spantag.innerHTML = x;
}
}
PHP code
function toXml($shop_goods)
{
$doc = new DomDocument();
$goods = $doc->createElement('goods');
$goods = $doc->appendChild($goods);
foreach ($shop_goods as $Item => $ItemName)
{
$good = $doc->createElement('good');
$good = $goods->appendChild($good);
$title = $doc->createElement('ID');
$title = $good->appendChild($title);
$value = $doc->createTextNode($Item);
$value = $title->appendChild($value);
$price = $doc->createElement('price');
$price = $good->appendChild($price);
$value3 = $doc->createTextNode($ItemName["price"]);
$value3 = $price->appendChild($value3);
$quantity = $doc->createElement('quantity');
$quantity = $good->appendChild($quantity);
$value2 = $doc->createTextNode($ItemName["qty"]);
$value2 = $quantity->appendChild($value2);
$total = $doc->createElement('total');
$total = $good->appendChild($total);
$value3 = $doc->createTextNode($ItemName["total"]);
$value3 = $total->appendChild($value3);
}
$strXml = $doc->saveXML();
//echo("<br>----- DATA RECOREDED!!! ----");
return $strXml;
}
As others have noted, this could be an encoding issue.
Check your code for the Xml byte order mark.
Check the document is returning the correct mime type.
Not sure of your constraints but have you considered serializing your data to Json format. It's much easier to work with in the browser.
Finally consider using a library like JQuery to handle your ajax requests, much easier for cross browser compatibility.

Categories

Resources