JavaScript - Newbe, How To Convert Php Variable (array) To Use In Js
Hello everyone,
I couldn't find anything informative on this subject online. could someone point me to the right direction on how to convert php variable so it could be used in a javascript section. for example I have a php array named $places, it's a nested array and I'd like to traverse through all the elements of this array much like it's done in php =>foreach($places as $place) but this done in JS. in a nutshell how do i convert this variable into a JS appropriate variable. -Thank you Similar TutorialsI am working on a page where the user will select a location from a dynamically generated dropdown list. I was able to create the php multidimensional array (tested and working) from a MySql database using the users information at login, but I'm having problems converting it to a javascript multidimensional array. I need to be able to access variables that I can pass to a number of text fields within an html form. For instance, if a user belongs to a company with multiple addresses, I need to be able to let them select the address they need to prepopulate specific text fields. php array creation: Code: if ($row_locations) { while ($row_locations = mysql_fetch_assoc($locations)) { $mail[$row_locations['comp_id']]=array('mailto'=>$row_locations['mailto'], 'madd'=>$row_locations['madd'], 'madd2'=>$row_locations['madd2'], 'mcity'=>$row_locations['mcity'], 'mstate'=>$row_locations['mstate'], 'mzip'=>$row_locations['mzip'], 'billto'=>$row_locations['billto'], 'badd'=>$row_locations['badd'], 'badd2'=>$row_locations['badd2'], 'bcity'=>$row_locations['bcity'], 'bstate'=>$row_locations['bstate'], 'bzip'=>$row_locations['bzip']); } } javascript function - this should create the array and send variables to text fields. Code: function updateAddress() { var mail = $.parseJSON(<?php print json_encode(json_encode($mail)); ?>); { if (comp_id in mail) { document.getElementById('mailto').value=mail.comp_id.mailto.value; document.getElementById('madd').value=mail.comp_id.madd.value; document.getElementById('madd2').value=mail.comp_id.madd2.value; document.getElementById('mcity').value=mail.comp_id.mcity.value; document.getElementById('mstate').value=mail.comp_id.mstate.value; document.getElementById('mzip').value=mail.comp_id.mzip.value; } else { document.getElementById('mailto').value=''; document.getElementById('madd').value=''; document.getElementById('madd2').value=''; document.getElementById('mcity').value=''; document.getElementById('mstate').value=''; document.getElementById('mzip').value=''; } } } Where is this breaking? Thanks in advance. ... at least that's what I think I'm trying to do... what I have is this function which reads the JSON attributes of crab_house, a JSON object: Code: $.getJSON( '../map/clients.json', function(data) { $.each( data. crab_house , function(i, m) { bizAdd= new google.maps.LatLng(m.lat, m.lng); var message =m.html; createMarker(bizAdd,message); }); but what I would like to do is something like: Code: var bizId='crab_house'; $.getJSON( '../map/clients.json', function(data) { $.each( data. bizId , function(i, m) { bizAdd= new google.maps.LatLng(m.lat, m.lng); var message =m.html; createMarker(bizAdd,message); }); is it possible? thanks in advance... Say I had a bunch of elements with id names "id1", "id2". "id3" etc. Then say I had a function that adds a click handler such that when you click these elements it gets the id name with this.attributes[1].nodeValue;. Then say I had a bunch of arrays with the same names as the ids var id1 = ["data", false, 45]; var id2 = ["otherdata", true, 15]; var id3 = ["otherotherdata", null, 65];. How would I set a variable "currentid" to the array with the corresponding name as the id name? I guess the underlying question is, how would I convert a string to a variable name?
TASK: Convert a 1D javascript array into a 2D array and then save on server as .txt file. Currently, I have a string of data in a javascript variable: Code: var myData = [uniqueCode, datum1, datum2, datum3 ... uniqueCode, datum13, datum14, datum15...uniqueCode, datum27, datum28, datum29] When the user clicks on a button, I send the string of data to the "End" page: Code: //html <form name="data" method="post" action="End.php"> /javaScript function sendData() { var packed = ""; // Initialize packed or we get the word 'undefined' for (i = 0; (i < myData.length); i++) { if (i > 0) { packed += ","; } packed += escape(myData[i]); } document.data.data.value = packed; document.data.submit(); } At the "End" page, I collect the data with php: Code: $packed = $_POST['data']; $myData = explode(",", $packed); for ($i = 0; ($i < count($myData)); $i++) { $myData[$i] = rawurldecode($myData[$i]); $myData[$i] = str_replace("\\", "\\\\", $myData[$i]); $myData[$i] = str_replace("\"", "\\\"", $myData[$i]); } And then I store the data in a .txt file on the server (identified by the uniqueCode): Code: //php $uniquecode = $myData[0]; $myFile = "data_".$uniquecode.".txt"; $fh = fopen("data\\$myFile", "w") or die("Couldn't open the file"); fwrite($fh, implode(",",$myData)); fclose($fh); ?> Thus, I am able to save the data collected in the javascript string variable "myData". HOWEVER: The format I actually want is not a string, but an array, which starts a new line each time the unique code is shown. Thus, instead of saving: Code: uniqueCode, datum1, datum2, datum3 ... uniqueCode, datum13, datum14, datum15...uniqueCode, datum27, datum28, datum39 I want to save: Code: uniqueCode, datum1, datum2, datum3 ... uniqueCode, datum13, datum14, datum15... uniqueCode, datum27, datum28, datum39 Any help would be MUCH appreciated. Cheers, Adrian Hello. I need help PLEASE ! I need to convert a string Quote: lalaw|lalaw1|lalaw2|lalaw3 in to Array The values I have in variable "tables" I want to create variable list which takes values from "tables" Than I want to split this, and put each value in to new array: I've started with: Code: var list = "tables"; var listArray = list.split("|"); for(i=0; i < listArray.length;i++) { //? how to put now values in to array? } Best Regards Leos It is very simple.. i want to use the insertBefore but cannot figure it out. this is my JavaScript: Code: //create before element var myNewElement = document.createElement("li"); var newList = document.getElementsByTagName("li")[2]; myNewElement.insertBefore(newList, myNewElement); myNewElement.innerHTML = "Another List"; //document.getElementsByTagName("li").appendChild(); The console says node was not found. The bottom line is commented out because i'm not sure if i need it I have an old mojozoom script working on my xcart.... my problem is that it has a click event that opens the product in full screen view...I have to disable this function! It is working of a loop for the dynamic products thats why I cant figure out where the dynamic link is... thank you for any help or hints in the right direction... i did try to single out where iin the code was the problem but to no avail. Code: var MojoZoom = (function() { var $ = function(id) {return document.getElementById(id);}; var dc = function(tag) {return document.createElement(tag);}; var defaultWidth = 288; var defaultHeight = 288; function addEvent(element, ev, handler) { var doHandler = function(e) { return handler(e||window.event); } if (element.addEventListener) { element.addEventListener(ev, doHandler, false); } else if (element.attachEvent) { element.attachEvent("on" + ev, doHandler); } } function getElementPos(element) { var x = element.offsetLeft; var y = element.offsetTop; var parent = element.offsetParent; while (parent) { x += parent.offsetLeft; y += parent.offsetTop; parent = parent.offsetParent; } return { x : x, y : y } } function getEventMousePos(element, e) { var scrollX = document.body.scrollLeft || document.documentElement.scrollLeft; var scrollY = document.body.scrollTop || document.documentElement.scrollTop; if (e.currentTarget) { var pos = getElementPos(element); return { x : e.clientX - pos.x + scrollX, y : e.clientY - pos.y + scrollY } } return { x : e.offsetX, y : e.offsetY } } function makeZoomable(img, zoomSrc, zoomImgCtr, zoomWidth, zoomHeight, alwaysShow) { // make sure the image is loaded, if not then add an onload event and return if (!img.complete && !img.__mojoZoomQueued) { addEvent(img, "load", function() { img.__mojoZoomQueued = true; setTimeout(function() { makeZoomable(img, zoomSrc, zoomImgCtr, zoomWidth, zoomHeight, alwaysShow); }, 1); }); return; } // sorry var isIE = !!document.all && !!window.attachEvent && !window.opera; var w = img.offsetWidth; var h = img.offsetHeight; var oldParent = img.parentNode; if (oldParent.nodeName != "A") { var linkParent = dc("a"); linkParent.setAttribute("href", zoomSrc); oldParent.replaceChild(linkParent, img); linkParent.appendChild(img); } else { var linkParent = oldParent; } linkParent.style.position = "relative"; linkParent.style.display = "block"; linkParent.style.width = w+"px"; linkParent.style.height = h+"px"; var imgLeft = img.offsetLeft; var imgTop = img.offsetTop; var zoom = dc("div"); zoom.className = "mojozoom_marker"; var zoomImg = dc("img"); zoomImg.className = "mojozoom_img"; zoomImg.style.position = "absolute"; zoomImg.style.left = "-9999px"; document.body.appendChild(zoomImg); var parent = img.parentNode; var ctr = dc("div"); with (ctr.style) { position = "absolute"; left = imgLeft+"px"; top = imgTop+"px"; width = w+"px"; height = h+"px"; overflow = "hidden"; display = "none"; } ctr.appendChild(zoom); parent.appendChild(ctr); var zoomInput = parent; var useDefaultCtr = false; if (!zoomImgCtr) { zoomImgCtr = dc("div"); zoomImgCtr.className = "mojozoom_imgctr"; var imgPos = getElementPos(img); zoomImgCtr.style.left = w + imgPos.x + "px"; zoomImgCtr.style.top = imgPos.y + "px"; zoomImgCtr.style.width = (zoomWidth ? zoomWidth : defaultWidth) +"px"; zoomImgCtr.style.height = (zoomHeight ? zoomHeight : defaultHeight) +"px"; document.body.appendChild(zoomImgCtr); useDefaultCtr = true; } zoomImgCtr.style.overflow = "hidden"; if (!alwaysShow) { zoomImgCtr.style.visibility = "hidden"; } addEvent(zoomImg, "load", function() { var zoomWidth = zoomImg.offsetWidth; var zoomHeight = zoomImg.offsetHeight; var ctrWidth = zoomImgCtr.offsetWidth; var ctrHeight = zoomImgCtr.offsetHeight; var ratioW = zoomWidth / w; var ratioH = zoomHeight / h; var markerWidth = Math.round(ctrWidth / ratioW); var markerHeight = Math.round(ctrHeight / ratioH); document.body.removeChild(zoomImg); zoomImgCtr.appendChild(zoomImg); var zoomFill = dc("div"); zoomFill.className = "mojozoom_fill"; zoom.appendChild(zoomFill); var zoomBorder = dc("div"); zoomBorder.className = "mojozoom_border"; zoom.appendChild(zoomBorder); zoom.style.width = markerWidth+"px"; zoom.style.height = markerHeight+"px"; if (alwaysShow) { zoom.style.left = "0px"; zoom.style.top = "0px"; zoomImg.style.left = "0px"; zoomImg.style.top = "0px"; } var isInImage = false; if (!alwaysShow) { addEvent(zoomInput, "mouseout", function(e) { var target = e.target || e.srcElement; if (!target) return; if (target.nodeName != "DIV") return; var relTarget = e.relatedTarget || e.toElement; if (!relTarget) return; while (relTarget != target && relTarget.nodeName != "BODY" && relTarget.parentNode) { relTarget = relTarget.parentNode; } if (relTarget != target) { isInImage = false; ctr.style.display = "none"; zoomImgCtr.style.visibility = "hidden"; } } ); // a bit of a hack, mouseout is sometimes not caught if moving mouse really fast addEvent(document.body, "mouseover", function(e) { if (isInImage && !(e.toElement == zoomBorder || e.target == zoomBorder)) { ctr.style.display = "none"; zoomImgCtr.style.visibility = "hidden"; isInImage = false; } } ); } addEvent(zoomInput, "mousemove", function(e) { isInImage = true; var imgPos = getElementPos(img); if (useDefaultCtr) { zoomImgCtr.style.left = w + imgPos.x + "px"; zoomImgCtr.style.top = imgPos.y + "px"; } ctr.style.display = "block"; zoomImgCtr.style.visibility = "visible"; var pos = getEventMousePos(zoomInput, e); if (e.srcElement && isIE) { if (e.srcElement == zoom) return; if (e.srcElement != zoomInput) { var zoomImgPos = getElementPos(e.srcElement); pos.x -= (imgPos.x - zoomImgPos.x); pos.y -= (imgPos.y - zoomImgPos.y); } } var x = markerWidth/2; var y = markerHeight/2; if (!isIE) { pos.x -= imgLeft; pos.y -= imgTop; } if (pos.x < x) pos.x = x; if (pos.x > w-x) pos.x = w-x; if (pos.y < y) pos.y = y; if (pos.y > h-y) pos.y = h-y; var left = ((pos.x - x)|0); var top = ((pos.y - y)|0); zoom.style.left = left + "px"; zoom.style.top = top + "px"; zoomImg.style.left = -((pos.x*ratioW - ctrWidth/2)|0)+"px"; zoomImg.style.top = -((pos.y*ratioH - ctrHeight/2)|0)+"px"; } ); }); // I've no idea. Simply setting the src will make IE screw it self into a 100% CPU fest. In a timeout, it's ok. setTimeout(function() { zoomImg.src = zoomSrc; }, 1); } function init() { var images = document.getElementsByTagName("img"); for (var i=0;i<images.length;i++) { var img = images[i]; var zoomSrc = img.getAttribute("data-zoomsrc"); if (zoomSrc) { makeZoomable(img, zoomSrc, document.getElementById(img.getAttribute("id") + "_zoom"), null, null, img.getAttribute("data-zoomalwaysshow")=="true"); } } } return { addEvent : addEvent, init : init, makeZoomable : makeZoomable }; })(); MojoZoom.addEvent(window, "load", MojoZoom.init); If I assign an array to another variable, any changes to the array change both variables. Is it a pointer instead of a copy? Try this: Code: <script type="text/javascript"> Arr=['a','b','c']; Arr2=Arr; Arr[1]='_'; alert('Array 1: '+Arr); alert('Array 2: '+Arr2); // Both arrays become 'a','_','c' </script> Why's this happen? Is it to be expected? Variables don't do this but it's happening for arrays in IE and FireFox, maybe all others. I am currently trying to check using javascript whether a php array contains a variable, and if it does then display a message. Any help would be much appreciated. I have written the following code... Code: <?php //php which sets users array to the results of the sql $selectquery = "SELECT Username FROM User"; $selectresult = mysql_query($selectquery); while ($row = mysql_fetch_array($selectresult)){ $users[] = $row['Username']; } ?> <script language="javascript" type="text/javascript"> function verifyUsername(array_var){ var user = document.getElementById("username").value; for(var i=0; i<array_var.length; i++){ if(array_var[i] == user){ document.getElementById("usernameerror").textContent = "already in array"; } } } </script> //html code for the form Username: <input type="text" name="username" id="username" onblur="return verifyUsername(<?php $users?>)"/> <span id="usernameerror" class="red"></span> I was wondering if it is possible to put all the non null variables of an array into a string variable with spaces between each array value? For example, if array() is a text array and has 10 values, array(0) through array(9), with three of those values null, let's say array(3), array(5), and array(7) are null, is there a way to put the remaining seven values into a string variable with spaces between each array value?
I need to get this script to work, I only included what im having the problem with. I am Using jQuery Library. Here is how this should work: .btnRoof div is clicked the parent id is retrieved as var pid a function called roof is called which simply changes a css background to "color" the function perform is called to get the "color1[0]" from the array. My Problem: perform() returns the word color1, color10, color1[0], or c. instead of images/cp-roof-blue.png as listed in the array. Code: $(document).ready(function() { var color1=new Array(); color1[0]="images/cp-roof-blue.png"; color1[1]="images/cp-panel-blue.png"; color1[2]="images/cp-trim-blue.png"; function perform(name, x) { alert(name[x]); //alert([name][x]); //alert(name+'['+x+']'); //alert(color1[0]); // correct return name[x]; } function Roof(color) { $("#colorPicker .roof").css("background", "url("+color+")"); } $('.btnRoof').click(function() { var pid = $(this).parent().parent().attr("id"); Roof(perform(pid, 0)); }); }); I tried to clarify as much as possible, please let me know if I need explain further. Thanks. the title kind of sums it up... if I have an array of equations (I'm guessing they should be strings but they don't have to be) and a user-defined variable can that variable be used for the "x" in the equations? I already did the easy part ... Code: <!DOCTYPE html> <html> <head> </head> <body> <input onkeyup="solve(this.value)" /><br> <input id="box0" /><br> <input id="box1" /><br> <input id="box2" /><br> <script type="text/javascript"> var equations=["(x*9/5)+32","x+273.15","x-50*(8/13)"] function solve(val){ for (var i = 0; i < equations.length; i++) { document.getElementById("box"+i).value= //ummm... } } </script> </body> </html> I have inherited some code, and cannot get it to work. Note the bold section in the OBJECT tag below. I believe this is where the issue is. Code: <script language="JavaScript"> var camArray = new Array(); camArray['Dolliver'] = "http://video.dot.ca.gov/asx/D5-Bello-at-101.asx"; camArray['Mattie'] = "http://video.dot.ca.gov/asx/D5-Mattie-Rd-at-101.asx"; camera="Dolliver"; var camHTMLd = "<object id='MediaPlayer' width=320 height=240 classid='CLSID:22D6f312-B0F6-11D0-94AB-0080C74C7E95' standby='Loading Windows Media Player components...' type='application/x-oleobject' codebase='http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,7,1112'><param name='filename' value='"+camArray[camera]+"'><param name='Showcontrols' value='False'><param name='autoStart' value='True'><embed type='application/x-mplayer2' src='"+camArray[camera]+"' width=320 height=240></embed></object>" function changeCam(camera){ document.getElementById("caltransCamera").innerHTML = camHTMLd; //alert(camHTMLd+camArray[camera]); } </script> Then in the page, I have the following code: <a href="javascript:changeCam('Mattie');">101 at Mattie Road</a> It SHOULD open and start displaying the MATTIE cam, but it reloads the default Dolliver. What am I missing? Thank you in advance. I have strings's that are causing problems when being sent to a PHP script via JavaScript. (not all of it is getting sent) i.e. This is someone's line of text & it's rather long. I wish to convert the whole string to some other format say like the spaces to %20 and and the & to & I think, and so on... Then once the PHP script $_GET's the string it converts it back to the original. PLEASE NOTE: I wish to use JavaScript, not JQuery. Hi, I have a programing problem that have been around for ages. I have search on google using several expressions and words and after hours of digging i'm still unable to do it. I would like to get a value from a HTML page hosted remotely with an inconstant value. Then define this value and name as a javascript variable and apply or show in my page. Thanks for all the help P.S. Is there any way to make a domain lookup in javascript? I mean a user enters a domain and the script converts to an ip and shows to the user. If not thanks, probably it can only be done in the server side... See title How do i do it? Hello I have a php page in which I declared a js variable... right at the top of the page... <script type="text/javascript"> var tester = 0; </script> Later in the page I test this variable... <script type="text/javascript"> if (tester==1){ do some stuff!! } </script> But I keep getting an error variable _tester undefined Am I missing something obvious... I am new to js... but this seems really straightforward Hi! I have a javascript in the head of the document which has a variable named "ref2" ... ref2 is already working as I can see its value working in another function. I need to send this variable as the value of a hidden field in the form which is in the body of the document. This is my JavaScript Code: Code: function WriteContactFormStatement1 () { var ContactFormValue = ref2; document.write('<input type="hidden" name="UReferrersName" value="' + ContactFormValue + '" />'); } var WriteContactFormStatement = WriteContactFormStatement1 (); And at the end of my form, before the submit button, I have the following code: Code: <!-- START -- Javascript to print the statement for UReferrersName --> <script language="JavaScript" type="text/JavaScript"> //WriteContactFormStatement(); document.write (WriteContactFormStatement); </script> <!-- End -- Javascript to print the statement for UReferrersName --> When I execute the form, it doesn't work the way it should, plus, gives me a word "undefined" next to the "Submit" button ..... Please help !... - Xeirus. I don't know how I should do ? Quote: <html> <head> <script type="text/javascript"> function add(a,b){ y=a+b return y } var aaa = add(one,two) //one needs to get somehow get the value of yil, in this case 10 var one = function reas(){i=10;if(i<10){yil = 15}; else{yil = 10; yil = one;}; var two = 20; document.write(y) </script> </head> </html> also why doesn't this work? Quote: <html> <head> <script type="text/javascript"> function adder(a,b){ var k=a+b; return k } var hes=adder(5,kol); kol=40; alert(hes); </script> </head> </html> you cannot have variables in callback functions? hello there.. I'm poor with javascript.. can you help me to convert this php to javascript? Code: <?php setcookie("KNwidget", "fbfans", time()+3600); ?> <?php if (isset($_COOKIE["KNwidget"])) echo "when has COOKIE, nothing show here.."; else echo "<script type='text/javascript'>some java script here</script>"; ?> |