json_encode for multi line string php to javascript - javascript

I am trying to pass a string from php (from mysql) into a variable in javascript which has multiple lines. I understand I need to use php's json_encode() to do this. It's from a textarea and javascript opens a small window and is supposed to write its output. But I can't seem to get past the same error:Uncaught SyntaxError: Unexpected end of input
I'm guessing there's something else I need to do in the javascript
here's the very simple js function:
function view_notes(notes) {
var myWindow = window.open("", "MsgWindow", "width=400,height=400");
console.log(notes);
myWindow.document.write(notes);
}
</script>
And here's the php:
if ($result = $conn->query($sql)) {
// echo "regulars <br>";
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$phone=$row['phone'];
$formatted_phone=format_phone($phone);
$notes=$row['notes'];
$js_notes=json_encode($notes);
var_dump($js_notes);
echo"<tr>";
echo "<td>";
echo $row['First_Name'];
echo "</td>";
//echo "&nbsp";
echo "<td>";
echo $row['Last_Name'];
echo "</td>";
// echo "&nbsp";
echo "<td>";
echo $formatted_phone;
echo "</td>";
// echo "&nbsp";
echo "<td>";
echo $row['email'];
echo "</td>";
echo "<td>";
echo $row['court_status'];
echo "</td>";
echo "<td>";
echo "<button onclick=\"view_notes($js_notes)\">View Notes</button>";
echo "</td>";
}
/* free result set */
$result->free();
}

You didn't concated the string properly. To solve replace this line
echo "<button onclick=\"view_notes($js_notes)\">View Notes</button>";
with
echo "<button onclick='view_notes(".$js_notes.")'>View Notes</button>";
To solve the line break issue create one more javascript function
function nl2br (str, is_xhtml) {
if (typeof str === 'undefined' || str === null) {
return '';
}
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
and use above function in your view_notes function like this
function view_notes(notes) {
var myWindow = window.open("", "MsgWindow", "width=400,height=400");
console.log(notes);
myWindow.document.write(nl2br(notes));
}

Can you share result of
console.log(notes);
Because I think the problem is mismatch of quotes here-
echo "View Notes";
When this evaluates it places $js_notes in double quotes which breack HTML syntex rule.
Go to view source of the page in the browser and inspect this line.
Hope this will help.

Related

Causing Uncaught type (reading 'value') error when I click submit

I made the zone with checkbox list if I type in the value and that entered value is in Database. But when I click submit, it shows Uncaught TypeError: Cannot read properties of undefined (reading 'value'). I named both name and id as chkzone. Error is causing in var chkzone = document.translot.chkzone.value; line.
while ($row = mysqli_fetch_assoc($result1)) {
$field1name = $row["lotid"];
$field2name = $row["product"];
$field3name = $row["ewsflow"];
$field4name = $row["zone"];
$key = $field1name + ":" + $field2name + ":" + $field3name;
if (!in_array($key, $arr)){
echo "<tr>";
echo "<th >Lot ID:</th>";
echo "<td >$field1name</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Product:</th>";
echo "<td>$field2name</td>";
echo "</tr>";
echo "<tr>";
echo "<th>EWSFLOW: </th>";
echo "<td>$field3name</td>";
echo "</tr>";
array_push($arr, $key);
}
echo "<tr>";
echo "<th>Zone - $field4name</th>";
echo "<td><input type=\"checkbox\" name=\"chkzone\" id=\"chkzone\" value=\"$zone\"></td>";
//echo "<td>$field4name</td>";
echo "</tr>";
Below is in JavaScript.
var chkzone = document.translot.chkzone.value;
if (chkzone == null || chkzone == ""){
alert("Please choose zone to disable for Correlationwafer.");
return false;
}
{
document.getElementById("result").innerHTML = SynReqData(reqHttp2,'correlationwafer_result.php?productlotid=' + productlotid + '&chkzone' + chkzone);
return false;
}
The reason you get that error is because document.translot.chkzone is undefined. In other words, if you have an element like that in your webpage this must not be the right path to access it.
It's a little challenging to know exactly why that is without seeing your full web page, but given what you're echoing in PHP you might be able to change this:
var chkzone = document.translot.chkzone.value;
into this
var chkzone = document.querySelector('#chkzone').value;
which should work because you've given your input an id of chkzone. If this doesn't work, then please share with us when your javascript code is running, as your issue might be that it's running somewhere before this input element is inserted to the DOM of your webpage.
edit: Also unrelated to your question, but I believe you're missing an = sign here: '&chkzone' + chkzone); -> '&chkzone=' + chkzone);

Can i pass array to an HTML? Creating a dynamic html table with php/javascript

I have created a table with 3 columns and rows with the size of an array pulled from the database. I have got the value but I want to create a button inside the cells with the name from pname and when you click that button it will take you to the value of plink. I tried using <input type="button" value=" " onclick="window.open( )", but it doesn't seem to pass the arrays. I am sure there is an easier/ better way to do it with JavaScript, but I am not familiar with JavaScript. Please help me out. Here is my code.
I want the format 3 columns and infinite rows(based on the data).
<!DOCTYPE html>
$pname = array();
$plink = array();
$results = $wpdb->get_results("SELECT name, link FROM `wptable`);
if(!empty($results)) {
foreach($results as $row){
$pname[] = $row->name;
$plink[] = $row->link;
}
}
$num = 0;
echo "<table class='table'>";
echo "<tbody>";
echo "<br><br>";
$quant_row = count($pname)/3;
$quant_col = 3;
for ($count_row = 0; $count_row < $quant_row; $count_row++)
{
echo "<tr>";
for ($count_col = 0; $count_col < $quant_col; $count_col++)
{
echo "<td>";
echo $plink[$num];
echo "</td>";
$num++;
}
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
?>
You just need to echo a button inside an anchor:
echo '<button type="button">' . $pname[$num] . '</button>';
try this.
echo "<td>";
echo "<button onclick=\"Document.getElementById('link$num').display=state$num? 'none' :'block';state$num=!state$num; \">". $pname[$num] ."</button><div id='link$num'>". $plink[$num]."<div>";
echo "";
when you click on $pname , you show the $plink. reclick and hide the content

How to prevent SQL to store escape character with single quote character

I need to store text strings that will have single quote at beginning and end.
I'm issuing JavaScript command from PHP.
I'm adding the quotes to the string like this:
echo '<script type="text/javascript">';
echo 'function GetCodes() {';
echo 'var vlist = document.getElementById("vListOfCodes");';
echo 'var vcodes = "";';
echo 'var i;';
echo 'for (i = 0; i < vlist.length; i++) {';
echo 'if (i == 0) {';
echo 'vcodes = vcodes + "\'" + vlist.options[i].value + "\'";';
echo '}';
echo 'else {';
echo 'vcodes = vcodes + ",\'" + vlist.options[i].value + "\'";';
echo '}';
echo '}';
echo 'document.getElementById("vStringOfCodes").value = vcodes;';
echo '}';
echo '</script>';
When the form is posted and the $_POST['vStringOfCodes'] data saved to SQL SERVER table the backslash character is added along with the single quote, meaning instead of a value in the field of
'mystring',´mystring2',...
i have
\'mystring\',\'mystring2\',...
How can i prevent those backslashes from being added there?
You can use php native function stripslashes.
$str = "\'mytext\'";
echo stripslashes($str);
//outputs 'mytext'
//in your case
echo stripslashes($_POST['HiddenInput'])
Php function stripslashes

Undefined index after json_decode

I have a problem when I'm trying to get the contents of a JavaScript Array and pass its value to a PHP Array Variable.
What I'm doing is that, when a user clicks a button, the value of the item clicked will be added to the javascript array and every time the javascript array updates, the PHP variable will also update and so the contents of the div displaying the contents of the PHP array. I'm not using forms for this matter but buttons
However, when I try to use the json_decode function to get the values of a JavaScript array, it's giving me a Message: undefined index: data error
I'm a beginner in JavaScript, jQuery and AJAX so please bear with me
This is my code:
<script>
// ARRAY VARIABLE WHERE ITEM VALUES WILL BE STORED
var food_item = new Array();
// FUNCTION TO BE TRIGGERED WHEN USER CLICKED THE BUTTON, GET THE ITEM'S VALUE AND ADD IT TO ARRAY
function addToTray(data){
food_item.push(document.getElementById(data).value);
dataString = food_item; // array?
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "main",
data: {data: jsonString},
cache: false,
success: function(){
alert("OK");
}
});
}
</script>
<body>
...
// LINE OF CODE RESPONSIBLE FOR FETCHING JAVASCRIPT ARRAY VALUES
$this->session->userdata['food_tray'] = json_decode($_POST['data']);
// DIV TO BE UPDATED
<div class="col-md-3 food-tray" id="food-items" style="margin-top: 7%">
<!--FOOD TRAY-->
<div class="panel-heading">
<h3 class="ft-header">Food Tray</h3>
</div>
<div class="panel-body">
<?php
$count_fi = count($this->session->userdata('food_tray'));
echo "<p>Your Items (" . $count_fi . ")</p>";
if($count_fi == 0){
echo "<p class='no-avail-list'>NO ITEMS ADDED IN FOOD TRAY</p>";
}else{
echo "<table class='table borderless'>";
for($i = 0; $i < $count_fi; $i++){
echo "<tr>";
echo "<td>" . $this->session->userdata['food_tray'][$i] . "</td>";
echo "<td>P 200.00</td>";
echo "<td><form method='post'><input type='number' name='qty' min='1' max='100' value='1'/></form></td>";
echo "</tr>";
}
echo "</table>";
echo "<a href='' class='btn btn-success' data-toggle='modal' data-target='#myModal'>
Add Friend</a>";
echo "<a href='".base_url()."index.php/CheckOut' class='btn btn-warning'>Proceed to Checkout</a>";
}
?>
</div>
</div>
...
<?php
foreach($query->result() as $row){
echo "<div class='col-lg-7'>";
echo "<div class='thumbnail'>";
$file_name = strtolower(preg_replace('/[^A-Za-z0-9\-.]/', '', $row->name));
/*if(file_exists(FCPATH . '/assets/images/main/food/' . $file_name . '.jpg')){
echo "<img src='".base_url()."/assets/images/main/food/".$file_name.".jpg' alt='' width='320px' height='100px'>";
}else{
echo "<img src='http://placehold.it/320x150' alt=''>";
}*/
echo "<img src='http://placehold.it/320x150' alt=''>";
echo "<div class='caption'>";
echo "<h5 class='pull-right'>&#x20B1 " . $row->price . "</h5>";
echo "<h5><a href='#'>" . $row->name . "</a></h5>";
echo "<h5>Calorie Count : " . ($row->calorie_count == NULL ? "Not Available" : $row->calorie_count) . "</h5>";
// BUTTON FOR `addToTray()` FUNCTION
echo "<button class='btn btn-primary' id='".$row->id."' value='".$row->name."' style='width:100%' onclick='addToTray(".$row->id.")'>Add to Tray</button>";
// var_dump($row->name);
echo "</div>";
echo "</div>";
echo "</div>";
}
?>
</body>
Anyone who knows how to solve this problem? Any help would be appreciated.
create your session as
$array = array ('food_tray' => json_decode($javascriptarray));
$this->session->set_userdata($array);
check if your javascript libraries are loaded in sources tab.

Ajax function can't get int valor onclick javascript

I have a function on ajax that retrieves the int on the input button onclick, this is the javascript ajax code:
function checkBoxes(str){
var xmlhttp=browsers();
if(str=""){
document.getElementById("txt").innerHTML="";
return;
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txt").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php?h"+str,true);
xmlhttp.send();
}
I use php to print the results on the screen, with an onclick button:
if(isset($_GET['k'])){
$con=oci_connect('jvillegas','1234','XE');
if(!$con){
die("No s'ha pogut connectar: ".mysqli_error($con));
}
$k=intval($_GET['k']);
$sql3=oci_parse($con, "SELECT TARIFAS.ID, TARIFAS.ID_TIPO_ACTIVIDAD, TARIFAS.TIPO, TIPO_ACTIVIDAD.TEMPS_KM, TARIFAS.PRECIO
FROM TARIFAS, TIPO_ACTIVIDAD
WHERE TARIFAS.ID_TIPO_ACTIVIDAD=TIPO_ACTIVIDAD.ID
AND TARIFAS.ID_TIPO_ACTIVIDAD=$k");
oci_execute($sql3);
echo "<div class='divPrecios'>";
echo "<table border='1'>";
echo "<tr class='tabPreciosTitles'>";
echo "<td>Tipus Tarifa</td>
<td>Temps/Km</td>
<td>Preu</td>
<td><input type='button' class='carrito' value=''></td>";
echo "</tr>";
while (($row=oci_fetch_array($sql3,OCI_BOTH))!=false){
echo "<tr>";
echo "<td>".$row['TIPO']."</td>";
echo "<td>".$row['TEMPS_KM']."</td>";
echo "<td>".$row['PRECIO']."</td>";
echo "<td>".$row['ID']."</td>";
echo "<td><input type='button' name='checkbox[]' onclick=checkBoxes('".$row['ID']."') value='".$row['ID']."'/></td>";
echo "</tr>";
}
echo "</table>";
echo "</div>";
}
I thougt there is the error:
input type='button' name='checkbox[]' onclick=checkBoxes('".$row['ID']."') value='".$row['ID']."';
I do tests and if I pass a single int valor, it returns 0... why??
So the table with the result if all it's correct:
if(isset($_GET['h'])){
$con=oci_connect('jvillegas','1234','XE');
if(!$con){
die("No s'ha pogut connectar: ".mysqli_error($con));
}
echo "<table border=1>";
echo "<tr class='tabPreciosTitles'>";
echo "<td>Nom Activitat</td>
<td>Nom Tipus Activitat</td>
<td>Tipus Tarifa</td>
<td>Temps/km</td>
<td>Preu</td>";
echo "</tr>";
$h=intval($_GET['h']);
$sql4=oci_parse($con, "SELECT ACTIVIDAD.NOM AS NOM_ACTIVIDAD, TIPO_ACTIVIDAD.NOM AS NOM_TACTIVIDAD, TARIFAS.TIPO, TIPO_ACTIVIDAD.TEMPS_KM, TARIFAS.PRECIO
FROM TARIFAS, ACTIVIDAD, TIPO_ACTIVIDAD
WHERE TARIFAS.ID=$h
AND TARIFAS.ID_TIPO_ACTIVIDAD = TIPO_ACTIVIDAD.ID
AND TIPO_ACTIVIDAD.ID_ACTIVIDAD = ACTIVIDAD.ID");
oci_execute($sql4);
$array=array(
0=>array(),
1=>array(),
2=>array(),
3=>array(),
4=>array()
);
while (($row=oci_fetch_array($sql4,OCI_BOTH))!=false){
array_push($array[0],$row['NOM_ACTIVIDAD']);
array_push($array[1],$row['NOM_TACTIVIDAD']);
array_push($array[2],$row['TIPO']);
array_push($array[3],$row['TEMPS_KM']);
array_push($array[4],$row['PRECIO']);
}
for ($x=0;$x<count($array[4]);$x++){
echo "<tr>";
echo " <td>".$array[0][$x]."</td>";
echo " <td>".$array[1][$x]."</td>";
echo " <td>".$array[2][$x]."</td>";
echo " <td>".$array[3][$x]."</td>";
echo " <td>".$array[4][$x]."</td>";
echo " <td><input type='submit' class='carritoElim' value=''></td>";
echo "</tr>";
}
echo "</table>";
}
And to show these results I use divs:
<div id='txtHint'></div>
<div id='txtIhnt'></div>
<div id='txt'></div>
If I put an int on the query of the last table, change the $h for a 13, it works, or if I change the ajax function on > xmlhttp.open("GET","ajax.php?h=13",true); it works too.
I think your problem is coming from this line here
if(str=""){
Rather that doing a comparison you are assigned an empty string to the str variable. So from that point on in the function the value of str will be "". You want to change it to
if(str==""){

Categories