PHP - Json_encode() Is *not* A Security Feature (or: How To Pass Php Values To Javascript)
Since there have been some debates about how to safely pass PHP values to JavaScript, I hope I can clarify a few things.
One suggestion that kept recurring was to simply run the value through json_encode() and then inject the result into a script element. The JSON-encoding is supposed to (magically?) prevent cross-site scripting vulnerabilities. And indeed it seemingly works, because naïve attacks like trying to inject a double quote will fail.
Unfortunately, this approach doesn't work at all and is fundamentally wrong for several reasons:
json_encode() was never intended to be a security function. It simply builds a JSON object from a value. And the JSON specification doesn't make any security promises either. So even if the function happens to prevent some attack, this is implementation-specific and may change at any time.
JSON doesn't know anything about HTML entities. The encoder leaves entities like " untouched, not realizing that this represents a double quote which is dangerous in a JavaScript context.
The json_encode() function is not encoding-aware, which makes it extremely fragile and unsuitable for any security purposes. Some of you may know this problem from SQL-escaping: There used to be a function called mysql_escape_string() which was based on a fixed character encoding instead of the actual encoding of the database connection. This quickly turned out to be a very bad idea, because a mismatch could render the function useless (e. g. the infamous GBK vulnerability). So back in 2002(!), the function was abandoned in favor of mysql_real_escape_string(). Well, json_encode() is like the old mysql_escape_string() and suffers from the exact same issues.
Any of those issues can be fatal and enable attackers to perform cross-site scripting, as demonstrated below.
1)
The entire “security” of json_encode() is based on side-effects. For example, the current implementation happens to escape forward slashes. But the JSON standard doesn't mandate this in any way, so this feature could be removed at any time (it can also be disabled at runtime). If it does get disabled, then your application is suddenly wide open to even the most trivial cross-site scripting attacks:
<?php header('Content-Type: text/html; charset=UTF-8'); $input = '</script><script>alert(String.fromCharCode(88, 83, 83));</script><script>'; ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>XSS</title> </head> <body> <script> var x = <?= json_encode($input, JSON_UNESCAPED_SLASHES) ?>; </script> </body> </html>2) In XHTML, a script element works like any other element, so HTML entities like " are replaced with their actual characters (in this case a double quote). But JSON does not recognize HTML entities, so an attacker can use them to bypass json_encode() and inject arbitrary characters: <?php header('Content-Type: application/xhtml+xml; charset=UTF-8'); $input = "";alert('XSS');""; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>XSS</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> </head> <body> <script type="text/javascript"> var x = <?= json_encode($input) ?>; </script> </body> </html>3) json_encode() blindly assumes that the input and the output should always be UTF-8. If you happen to use a different encoding, or if an attacker manages to trigger a specific encoding, you're again left with no protection at all: <?php header('Content-Type: text/html; charset=UTF-7'); $input = '+ACIAOw-alert(+ACI-XSS+ACI)+ADsAIg-'; ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-7"> <title>XSS</title> </head> <body> <script> var x = <?= json_encode($input) ?>; </script> </body> </html>(This particular example only works in Internet Explorer.) I hope this makes it very clear that json_encode() is not a security feature in any way. Relying on it is conceptually wrong and simply a very bad idea. It's generally not recommended to inject code directly into a script element, because any mistake or bug will immediately lead to a cross-site scripting vulnerability. It's also very difficult to do it correctly, because there are special parsing rules and differences between the various flavors of HTML. If you try it, you're asking for trouble. So how should one pass PHP values to JavaScript? By far the most secure and robust approach is to simply use Ajax: Since Ajax cleanly separates the data from the application logic, the value can't just “leak” into a script context. This is essentially like a prepared statement. If you're into micro-optimization and cannot live with the fact that Ajax may need an extra request, there's an alternative approach by the OWASP: You can JSON-encode the data, HTML-escape the result, put the escaped content into a hidden div element and then parse it with JSON.parse(): <?php header('Content-Type: text/html; charset=UTF-8'); $input = 'bar'; ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>XSS</title> <style> .hidden { display: none; } </style> </head> <body> <div id="my-data" class="hidden"> <?php $json_object = json_encode(array( 'foo' => $input, )); // HTML-escape the JSON object echo htmlspecialchars($json_object, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8'); ?> </div> <script> var data = JSON.parse(document.getElementById('my-data').innerHTML); alert('The following value has been safely passed to JavaScript: ' + data.foo); </script> </body> </html> Similar TutorialsHello there,
I have 2 questions:
1) Look he http://www.hellastra...ooking/taxi.php
I have a form and i want to pass values from URL to fields.
So, for example to pass a value to Prefered driver ID field you write this:
http://www.hellastra...?drivercode-123 and the value 123 is passed to that field. I did this with this code:
<?php $sDriverCode = $_REQUEST['drivercode']; ?> <input style="width:100px;" name="drivercode" id="drivercode" value="<?=$sDriverCode?>" data-mini="true" />At the same form i have some radio-type fields. Its the one you see at Type of Vehicle (Standard, Premium etc). When i try to do the same, i cannot get this to work. What i am trying to do is this: hey guys,i'm back with a new prob.. i have an image here that when clicked using onclick, will open a window and sort of pass the php values to the window. okay,it's confusing but perhaps this will help you understand. let me break it down. this is what the image code looks like. i have placed this inside the php echo. Code: [Select] <img src="images/edit.png" alt="Edit rooms" width="16" height="16" onclick="window.open(\'edit.php?course='.$row['c_name'].'&year='.$row['year'].'&block='.$row['block'].'\',\'width=300, height=200, menubar=yes\')"/> now my problem is i can't seem to get all three of the values, c_name,year and block to be posted on the window.. here's the code on edit.php: Code: [Select] <?php include("dbcon.php"); $course = $_GET['c_name']; $year = $_GET['year']; $block = $_GET['block']; ?> <html> <body> Course:<input type="text" name="course" value="<?php echo $course;?>"><br> Year:<input type="text" name="year" value="<?php echo $year;?>"><br> Block:<input type="text" name="block" value="<?php echo $block;?>"><br></html> i have already used $_GET as you can see but only year and block appear on the form. i get a notice saying that c_name is an undefined index. i am really confused and i don't know what the problem is. i hope you guys can help me.. Hi, I'm trying to pass values from an array into a form. As a newbie, I've came up with the code underneath, but I want to pinpoint all the first values toward 1 selection list in the form. Any suggestions how to accomplish this? Thanks in advance. Ruud <html> <head> <title>Test formulier</title> </head> <body> <h2>Test formulier</h2> <form action="test.php" method="post"> <p> <?php $prijzen = array( array("01", "125","150", "A" => true,"B" => true), array("02", "125","150", "A" => true,"B" => true), array("03", "125","150", "A" => true,"B" => false), array("04", "125","150", "A" => true,"B" => true) ); ?> </P> <select name="prijzen[]" id="prijzen" multiple="multiple" size="7" class="none"> <?php while(list($key, $val) = each($prijzen)){ while(list($key2, $val2) = each($val)){ echo '<option value="'.$key2.'">'.$val2.'</option>'.PHP_EOL; } } ?> </select> </body> </html> I am under developing PHP add to cart without DB, so that i am using SESSION, actually get data from fetch_data.php data to my_cart.php using the POST method, successfully retun the values, After receiving the post data how can i convert to display like a table. workout: fetch_data.php return values. https://snag.gy/IASCMZ.jpg & values received https://snag.gy/ojWxHe.jpg Here is my my_cart.php : // FYI -> Here i am using only two fields : voice_sku & voice_name <table width="100%" cellpadding="6" cellspacing="0"> <thead> <tr> <th>Voice Sku</th> <th>Voice Name</th> <th>Remove</th> </tr> </thead> <tbody> <?php session_start(); $voice_sku = ''; $voice_name = ''; if(isset($_POST['voice_sku'])&& isset($_POST['voice_name'])) { // print_r($_POST); // die(); $voice_sku = $_POST['voice_sku']; $voice_name = $_POST['voice_name']; $_SESSION['voice_sku'] = $voice_sku; $_SESSION['voice_name'] = $voice_name; } var_dump($_SESSION); ?> <tr> <td colspan="5"> <span style="float:right;text-align: right;"> <!-- --> </span> </td> </tr> <tr> <td colspan="5"> <a href="index.php" class="button">Add More Items</a> <button type="submit">Update</button> </td> </tr> </tbody> </table>
First, I will select checkbox then click generate report then it displays the items with download link Then i click download link to download the selected checkbox values in pdf I want to download the selected checkbox items by clicking download link Now i am getting all check box items in the pdf download How to download only the selected check box items Code: [Select] <?php session_start(); $_SESSION['pidd'] = 2; $sessvar = $_SESSION['pidd']; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Untitled Document</title> <link rel="stylesheet" type="text/css" href="css/style.css" /> <style type="text/css" media="print"> DIV#noprint{visibility:hidden;} INPUT#printbutt{visibility:hidden;} #downloadlink{visibility:hidden;} </style> <script type="text/javascript"> function gen() { var st1=document.getElementById("ckbox1").checked; var st2=document.getElementById("ckbox2").checked; var st3=document.getElementById("ckbox3").checked; var st4=document.getElementById("ckbox4").checked; if(st1 == true) { document.getElementById('g1').style.display = 'block'; } if(st2 == true) { document.getElementById('g2').style.display = 'block'; } if(st3 == true) { document.getElementById('g3').style.display = 'block'; } if(st4 == true) { document.getElementById('g4').style.display = 'block'; } document.getElementById('p_info').style.display = 'none'; document.getElementById('histree').style.display = 'none'; document.getElementById('insurence').style.display = 'none'; document.getElementById('billin').style.display = 'none'; } function showuser() { document.getElementById('g1').style.display = 'none'; document.getElementById('g2').style.display = 'none'; document.getElementById('g3').style.display = 'none'; document.getElementById('g4').style.display = 'none'; var str1=document.getElementById("ckbox1").checked; var str2=document.getElementById("ckbox2").checked; var str3=document.getElementById("ckbox3").checked; var str4=document.getElementById("ckbox4").checked; if(str1 == true) { document.getElementById('p_info').style.display = 'block'; } else document.getElementById('p_info').style.display = 'none'; if(str2 == true) { document.getElementById('histree').style.display = 'block'; } else document.getElementById('histree').style.display = 'none'; if(str3 == true) { document.getElementById('insurence').style.display = 'block'; } else document.getElementById('insurence').style.display = 'none'; if(str4 == true) { document.getElementById('billin').style.display = 'block'; } else document.getElementById('billin').style.display = 'none'; } function checkByParent(aId, aChecked) { var collection = document.getElementById(aId).getElementsByTagName('INPUT'); for (var x=0; x<collection.length; x++) { if (collection[x].type.toUpperCase()=='CHECKBOX') collection[x].checked = aChecked; } } </script> </head> <body> <div id="main_content"> <div id="left"> <div id="noprint"> <h4>Patient Report</h4> <a id="check_all" href="#" style="text-decoration:none" onClick="checkByParent('checkboxes', true); return false;">check all</a> <a id="uncheckall" href="#" style="text-decoration:none" onClick="checkByParent('checkboxes', false); return false;">uncheck all</a> <br> <br> <form method="post" name="myform" action=""> <div id="checkboxes"> <div id="cb_id1"> <input id="ckbox1" name="cbox1" type="checkbox" <? if(isset($_REQUEST['cbox1'])) echo 'checked="checked"' ; ?> value="p_info" /> Patient Info </div> <div id="cb_id2"> <input id="ckbox2" name="cbox2" type="checkbox" <?php if(isset($_REQUEST['cbox2'])) echo 'checked="checked"' ; ?> value="histree" /> History </div> <div id="cb_id3"> <input id="ckbox3" name="cbox3" type="checkbox" <?php if(isset($_REQUEST['cbox3'])) echo 'checked="checked"' ; ?> value="insurance" /> Insurence </div> <div id="cb_id4"> <input id="ckbox4" name="cbox4" type="checkbox" <?php if(isset($_REQUEST['cbox4'])) echo 'checked="checked"' ; ?> value="billin" /> Billing </div> </div> <!--checkboxes div --> <br> <input id="vuprint" name="view" type="button" value="View" onClick="showuser();"> <hr/> <label for="docs"> Documents:<br> <br> </label> <input name="sub" type="button" value="Generate report" onclick="gen();"> <hr/> </form> <input id="printbutt" name="prt" type="button" value="Print" onClick="javascript:window.print();"> </div> <!--No print --> </div> <!--Left div --> <div id="side"> <div id="p_info"> <?php require("db_conn.php"); $pinfo = mysqli_query($mysqli,"SELECT * FROM patient_datas WHERE P_Id='".$sessvar."' "); while($fet = mysqli_fetch_array($pinfo)) { echo "<h4>Patient Info</h4>"; echo "<b>Name: </b>" . $fet["P_Fname"] . " " . $fet["P_Lname"]. "<br>"; echo "<b>Dob:</b> " . date("d-m-Y",strtotime($fet["P_Dob"]))."<br>"; echo "<b>Age:</b> " . $fet["P_Age"]."<br>"; echo "<b>Gender:</b> " . $fet["P_Gender"]."<br>"; echo "<b>Marital Status:</b> " . $fet["P_Mstatus"]."<br>"; echo "<b>Blood: </b>" . $fet["P_Blood"]."<br>"; echo "<b>Height: </b>" . $fet["P_Height"] . $fet["P_Hval"]."<br>"; echo "<b>Weight: </b>" . $fet["P_Weight"] . $fet["P_Wval"]; } ?> </div> <div id="histree"> <?php $his = mysqli_query($mysqli,"SELECT * FROM patient_datas WHERE P_Id='".$sessvar."' "); while($hisrow = mysqli_fetch_array($his,MYSQLI_ASSOC)) { echo "<h4>Patient Histroy</h4>"; echo "<b>P_Idate: </b>" . date("d-m-Y",strtotime($hisrow["P_Idate"]))."<br>"; echo "<b>P_Edate: </b>" . date("d-m-Y",strtotime($hisrow["P_Edate"]))."<br>"; echo "<b>D_Ddate: </b>" . date("d-m-Y",strtotime($hisrow["D_Ddate"])); } ?> </div> <!-- Insurence --> <div id="insurence"> <?php $insu = mysqli_query($mysqli,"SELECT * FROM patient_datas WHERE P_Id='".$sessvar."' "); while($insrow = mysqli_fetch_array($insu,MYSQLI_ASSOC)) { ?> <?php echo "<h4>Insurence</h4>"; echo "<b>P_Isname: </b>" . $insrow["P_Isname"]."<br>"; // echo $insow[""]; } ?> </div> <div id="billin"> <?php $bilrow = mysqli_query($mysqli,"SELECT * FROM patient_datas WHERE P_Id='1' "); while($bill = mysqli_fetch_array($bilrow,MYSQLI_ASSOC)) { ?> <?php echo "<h4>Billing</h4>"; echo "<b>P_Fbill: </b>" . $bill["P_Fbill"]."<br>"; echo "<b>Fees: </b>" . $bill["fees"]; } ?> </div> </div> <!--/side div --> <div id="generatereport"> <div id="g1" style="display:none; clear:both;"> <label for="Gen_reports">Generaterd reports</label> <br /> <br /> <?php $pinfo = mysqli_query($mysqli,"SELECT * FROM patient_datas WHERE P_Id='1' "); while($fet = mysqli_fetch_array($pinfo,MYSQLI_ASSOC)) { $new_dob = date("d-m-Y",strtotime($fet["P_Dob"])); ?> <?php echo "<h4>Patient Info</h4>"; echo "<b>Patient Id:</b> ". $fet["P_Id"]."<br>"; echo "<b>Name:</b> " . $fet["P_Fname"] . " " . $fet["P_Lname"]."<br>"; echo "<b>Dob:</b> " . $new_dob ."<br>"; echo "<b>Age:</b> " .$fet["P_Age"]."<br>"; echo "<b>Gender:</b> " . $fet["P_Gender"]."<br>"; echo "<b>Marital Status:</b> " . $fet["P_Mstatus"]. "<br>"; echo "<b>Blood:</b> " . $fet["P_Blood"] . "<br>"; echo "<b>Height:</b> " . $fet["P_Height"] . $fet["P_Hval"]. "<br>"; echo "<b>Weight:</b> " . $fet["P_Weight"] . $fet["P_Wval"]. "<br>"; } echo "*************************************************************************************************************************"; ?> </div> <div id="g2" style="display:none"> <?php $his = mysqli_query($mysqli,"SELECT * FROM patient_datas WHERE P_Id='1' "); while($secrow = mysqli_fetch_array($his,MYSQLI_ASSOC)) { echo "<h4>Patient Histroy</h4>"; echo "<b>P_Idate:</b> " . date("d-m-Y",strtotime($secrow["P_Idate"])) ."<br>"; echo "<b>P_Edate:</b> " . date("d-m-Y",strtotime($secrow["P_Edate"])) ."<br>"; echo "<b>D_Ddate:</b> " . date("d-m-Y",strtotime($secrow["D_Ddate"])) ."<br>"; } echo "*************************************************************************************************************************"; ?> </div> <div id="g3" style="display:none"> <?php $insu = mysqli_query($mysqli,"SELECT * FROM patient_datas WHERE P_Id='1' "); while($insrow = mysqli_fetch_array($insu,MYSQLI_ASSOC)) { echo "<h4>Insurence</h4>"; echo "<b>P_Isname:</b>" . $insrow["P_Isname"]."<br>"; } echo "*************************************************************************************************************************"; ?> </div> <div id="g4" style="display:none"> <?php $bilrow = mysqli_query($mysqli,"SELECT * FROM patient_datas WHERE P_Id='1' "); while($bill = mysqli_fetch_array($bilrow,MYSQLI_ASSOC)) { echo "<h4>Billing</h4>"; echo "<b>P_Fbill:</b> " . $bill["P_Fbill"]."<br>"; echo "<b>Fees:</b> " . $bill["fees"]; } ?> </div> <?php $infochk = 'p_info'; $hischk = 'histree'; $insuchk = 'insurance'; $billchk = 'billin'; ?> <a id="downloadlink" href="download_pdf2.php?info=<?php if(isset($infochk)) echo $infochk; ?>&hist=<?php if(isset($hischk)) echo $hischk; ?>&insu=<?php if(isset($insuchk)) echo $insuchk; ?>&billin=<?php if(isset($billchk)) echo $billchk; ?>">Download</a> </div> <!--generate report --> </div> <!--/main_coontent --> </body> </html> I have a list of checkboxes, like e.g each checkbox has a value as ResumeID, now question is/are; 1) how to get the values of the checkboxes using jQuery ? 2) when I got the values of the checkboxes using jQuery, how to pass those values to a PHP Controller action ? I have a page that contains a List box containing a list of categories taken from a mysql database, 4 iframe elements and 4 submit button (code to follow)
When an item is selected from the List box the onchange event submits the page to jobs.php and loads it into the joblist iframe. Once the iframe is loaded and visible it makes the "Add Job To Category" submit button visible. This all works great
When I click the "Add Job To Category" Submit button it loads Jobnew.php into the jobed iframe this is working but I can not seem to figure out how to pass the selected item from the List box using this submit button
I hope I am clear in my question if not please advise any help is very much appreciated....
Jobtask.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Job Configuration</title> <head> </head> <body> <div style="position:absolute;left:5px;top:0px;width:1345px;height:50px;z-index:0;"> <img src="images/img0001.png" id="Shape1" alt="" style="border-width:0;width:1345px;height:50px;"></div> <span style='position:fixed;left:525px;top:8px;font-family:Arial;font-size:32px;width:275px;'>Job Configuration</span> <form action='index.html' target='' method='post'> <div style="position:absolute;left:205px;top:55px;width:1345px;height:50px;z-index:0;"> <Input type="submit" action="index.html" Target="_top" method='post'Value="Main Menu"> </div> </form> <form style=position:fixed;left:200px;top:82px;> <iframe name='joblist' id='joblist' style=position:fixed;left:200px;top:px;visibility:hidden;z-index:10 src='' height="475" width="1150" scrolling='yes' frameBorder='0' ></iframe> <iframe name='job' id='job' style=absolute:fixed;left:200px;top:0px;visibility:hidden;z-index:0 src='' height="475" width="1150" scrolling='yes' frameBorder='0' ></iframe> <iframe name='jobed' id='jobed' style=position:fixed;left:460px;top:150px;visibility:hidden;z-index:10 src='' height="217" width="350" scrolling='no' frameBorder='0' ></iframe> <iframe name='newcat' id='newcat' style=position:fixed;left:460px;top:150px;visibility:hidden;z-index:10 src='' height="125" width="350" scrolling='no' frameBorder='0' ></iframe> </form> <?php error_reporting(E_ALL); include('dbcon/dbconnect.php'); $con=mysqli_connect($host,$user,$password,$db); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } if (isset($_POST['id'])) { $insql= "INSERT INTO catagory (Catagory) VALUES ('$_REQUEST[newcat]')"; $con->query($insql); } $Catresult = mysqli_query($con, "SELECT CatID, Catagory FROM catagory"); echo "<div id='wb_CatSel' style='position:absolute;z-index:0;text-align:center;'bgcolor='#00b0e6';>"; echo "<span style='position:fixed;left:10px;top:82px;font-family:Arial;font-size:15px;background-color:#00b0e6;width:175px;'>Select Category</span></div>"; echo "<form action='jobs.php' target='joblist' style='position:fixed;left:10px;top:101px;'></td>"; echo "<select name='cat' size='11' style='width: 175px;' onchange='this.form.submit()'>"; while($row = mysqli_fetch_array($Catresult)) { echo "<option value=\"".$row['CatID']."\">".$row['Catagory']."</option>\n "; } echo "</select>"; echo "</form>"; echo "<form action='Jobnew.php' target='jobed' method='post'>"; echo "<div style='position:absolute;left:10px;top:285px;width:1345px;height:50px;z-index:0;'>"; echo "<Input type='hidden' id='id1'><Input type='submit' id='sbtn' style='width:175px;visibility:hidden;' Value='Add Job To Category'></div></form>"; echo "<form action='Jobtask.php' target='' method='post'>"; echo "<div style='position:absolute;left:10px;top:310px;width:1345px;height:50px;z-index:0;'>"; echo "<Input type='submit' style='width:175px;' action='Jobtask.php' Target='_top' method='post' Value='Reset Form'></div></form>"; echo "<form action='newcat.php' target='newcat' method='post'>"; echo "<div style='position:absolute;left:10px;top:335px;width:1345px;height:50px;z-index:0;''>"; echo "<Input type='submit' style='width:175px;'' action='newcat.php' Target='newcat' method='post' Value='Add New Category'></div></form>"; ?> </body> </html> I read ages ago (and checked to see if it's true, it was and given how it works, it must still be) the end user can alter the value of any form field, using Firebug or similar, before submitting it. Two things I've figured out today: 1) a form input doesn't need a value - doesn't even need the attribute - if you're only checking whether the POST var isset and the actual value isn't important 2) Although it appears not to matter in the example I'm working on now, if the script doesn't check what the value is, and potentially sanitise it, the user could submit the form with any value, true, false, malicious, idk... So my question is: is this one of the ways malicious bad things can happen and do I *have to* specify a value, not because the script won't work without it, it does, but because in the real world it opens a security door if I don't check for malicious script by saying "if value not as expected, script has to die". Having formulated the question properly and thought about it I can't imagine simply making a form, without obvious connections to anything important, could be a problem in the way I'm asking about but I asked it now so Edited by appobs, 03 July 2014 - 12:08 PM. This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=357747.0 how can i do this ? i have a number of links , when i click one a pop up is displayed, i need to run a php script depending upon which link is clicked.
Or can i run a javascript function once a query string is passed in the url
Please advice.
Edited by chauhanRohit, 12 July 2014 - 04:10 AM. I am trying to build a website, whe
1) User logs in (UserA)
2) Inserting a name in the search box and pressing "Search", a list of all users matching that name is shown
3) The user selects a user (UserB) from that list (among several results)
4) By selecting the user (UserB) , a message box appears to insert text
5) The user(UserA) types the message
6) The user(UserA) presses the SUBMIT button and sends the message to the other user(UserB)
The problem i face is how to pass the variables from my PHP script to the JavaScript script. Its easy for me to get the values of input fiedls, select fields or any other DOM element value. But if the value i need to pass to Javascript file to perform an AJAX call isnt inside a DOM element, how do i do it?
For example, for me to determine the user that will send the message (userA), i will need several data. This data, i have them inside the PHP script as variables, but dont know how to pass them to Javascript file.
Getting the data from the URL, or from a hidden input field or any other DOM element, is a solution, but i want to know the way that is safer and better.
To summarize:
[PHP Script with necessary data]-->[pass necessary data from PHP to JavaScript file]-->[perform an AJAX call] --> [return data to PHP Script]
How do i do it?
Thanks in advance.
Hey everyone. So i'm trying to json_encode one of my arrays like such:
heres an example of how the array is being created (From the array results, everything seems to be fitting OK into the actual array creation) but it's just the actual array creating a multi demension after each result.
$num = 1; $num2 = 1; $i = 0; if ($num > 0) { $array[$i][1] = 40; } if ($num2 > 0) { $array[$i][2] = 50; } ++$i;I'm trying to achive this: var array_one_results = new Array(); array_one[1][0] = 40; array_one[1][0] = 50; array_one[2][1] = 40; array_one[2][1] = 50;right now, this is my results: var array_name = new Array(); array_name["0"] = new Array();array_taken["0"]["0"] = "10"; array_taken["0"]["1"] = "20"; array_name["1"] = new Array();array_taken["1"]["0"] = "10"; array_taken["1"]["1"] = "20"; array_name["2"] = new Array();array_taken["2"]["0"] = "10"; array_taken["2"]["1"] = "20"; array_name["3"] = new Array();array_taken["3"]["0"] = "10"; array_taken["3"]["1"] = "20"; array_name["4"] = new Array();array_taken["4"]["0"] = "10"; array_taken["4"]["1"] = "20";It's creating a new array for each. If anyone could help me through this, i'd really appreciate it. I'm encoding it with this: function js_str($s) { return '"'.addcslashes($s, "\0..\37\"\\").'"'; } function js_array($array, $keys_array) { foreach ($array as $key => $value) { $new_keys_array = $keys_array; $new_keys_array[] = $key; if(is_array($value)) { echo 'array_name'; foreach($new_keys_array as $key) { echo '["'.$key.'"]'; } echo ' = new Array();'; js_array($value, $new_keys_array); } else { echo 'array_taken'; foreach($new_keys_array as $key) { echo '["'.$key.'"]'; } echo ' = '.js_str3($value).";\n"; } } } I work with a large codebase and I have this situation come up fairly often:
the legacy class has large objects such as:
$design->motor->dimensions->a; $design->motor->dimensions->bd; $design->specifications->weight; $design->data->height; //etcWhen I create a new class, that class sometimes operates on the specific data, so say: class MyClass { public function compute($weight, $height, $a) { //stuff } } //and I call this for example as such: (new MyClass())->compute($design->specifications->weight, $design->data->height, $design->motor->dimensions->a);CONS: Potential issue: if design specs change and I need to change things parameters in "compute" function, I need to "re-key" the variables I pass to the function, and adjust things accordinly in MyClass as wel. PROS: only the exact data is being passed, and this data can come from anywhere it is viable, so in effect the function is fairly well separated, I think. Alternative option for me is to pass the entire design object, i.e class MyClass { public function compute(&$design) //can also be done via DI through a setter or constructor. { print $design->specifications->weight; print ($design->data->height + $design->motor->dimensions->a); //stuff } } (new MyClass())->compute($design);PROS: In this case when things change internally in which variables are needed and how things are computed, I only need to change the code in compute function of the class itself. CONS: MyClass now needs to be aware of how $design object is constructed. When it comes to this parameter passing, and Dependency Injection like this in general, does Computer Science advocate a preference on this issue? Do I pass the entire object, or do I pass only the bits and pieces I need? Code: [Select] <form action='test.php' method='post'> <input id="Username" type="hidden" name="date2" /> <input type="submit" name="action" value="Submit"></form> Hi I want to pass a Username javascript variable to test.php as hidden, anyone can help? When code this Code: [Select] <input id="Username" type="input" name="date2" />Data can pass to test.php When code this Code: [Select] <input id="Username" type="hidden" name="date2" />Data fail to pass over Reasons to use json_last_error() is obvious when decoding, but was not so to me when encoding. Looking at the documents, malformed UTF-8 characters will result in an error. The examples given show encoding a string, however, an array with an index value which is malformed UTF-8 characters will result in the same error. Are there other cases which json_encode() will result in error? Why would one actually want to use json_encode() on a string? Hi guys, I need to know how to json_encode a mysql output, so far the PHP ref manual for json_encode is not proving very helpful. Any help is much appreciated. Hello, I am new to pHp and javascript languages and I am trying to do some math calculations in pHp, then display the results with google charts. However, I got stuck with inserting data from pHp using json_encode. It works for the most simple array, with using 2 values. When using array of arrays, it does not work. I believe it could be a syntax errors with all those brackets but I could not figure it out. Thanks for any ideas! <?php // some arrays with dim 2x2 $testarr0 = array( 0.1, 2.5); $testarr = array( 1.0, 3.5); $testarr = array( $testarr0, $testarr ) ; // this is how it looks in pHp $json = json_encode($testarr); echo($json); echo '<br/>'; echo json_encode($json); ?> <html> <head> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"> </script> <script type="text/javascript"> google.charts.load('current', {'packages':['line']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('number', 'x values'); data.addColumn('number', 'y1 '); //var dataArray = <?php echo json_encode($testarr);?>; //document.body.innerHTML = " Data Array with json: " + dataArray ; // defining array here works well /* data.addRows( [ [0.1 ,2.5], [1.0 ,3.5] ] ); */ // this here does not work: data.addRow( <?php echo json_encode($testarr);?> ); // some options for the chart var options = { chart: { title: 'Points over time', }, width: 600, height: 400, axes: { x: { 0: {side: 'top'} } } }; var chart = new google.charts.Line(document.getElementById('line_top_x')); chart.draw(data, google.charts.Line.convertOptions(options)); } </script> </head> <body> <div id="line_top_x" style="width: 900px; height: 500px"></div> </body> </html>
when trying to decode a array of rows taken from my database I found that the json_encode function doesn't allow you to present you array as (with brackets [ ])
[{"name":"Destramic"}]but returns the array as (without brackets [ ]) {"name":"Destramic"}I looked into the documentation and it doesn't seem as if php offer such a way of having bracket which Is a bit of a problem with passing to jquery (which I've found using their autocomplete plugin) this has resulted in me having to add brackets myself $data = "[" . json_encode($rows2) . "]";does anyone know if you can encode it with the brackets or readable for jquery...thank you |