How can I escape from PHP code inside Javascript? - 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: \".

Related

Javascript - perform operation vertically and horizontally with dynamic text input

need help i am working with some text inputs here that are dynamic depending on how many the user enter. what i wanted to do is to compute the text inputs automatically after user input value using onkeyup javascript.
here the php and html code:
<?Php
$x = 10;
$i = 0;
for($i=0; $i<$x; $i++){
echo "<input type='text' onkeyup='multiply()' id='tb1'>";
echo "x";
echo "<input type='text' onkeyup='multiply()' id='tb2'>";
echo "=";
echo "<input type='text' onkeyup='multiply()' id='tb3'>";
echo "<br>";
}
?>
total:<input type='text' onkeyup='multiply()' id='tb4'>
and here's the javascript:
<script>
function multiply(){
var textbox1 = document.getElementById('tb1').value;
var textbox2 = document.getElementById('tb2').value;
var result = parseFloat(textbox1) * parseFloat(textbox2);
if(!isNaN(result))
{
document.getElementById('tb3').value = result;
}
}
</script>
now, the first row of text inputs works fine but the remaining text inputs doesn't I know i'm missing something here and i can't figure it out, how can
i compute horizontally those values from tb1 and tb2 then display it on tb3
and compute vertically all the values of tb3 and display it in tb4. any help is much appreciated.TIA
Well all rows contain elements with same ids. So row 1 will contain elements with ids: tb1, tb2, tb3. Row 2 will also contain elements with ids tb1, tb2 and tb3.
The id of each element on a page needs to be unique. You can make the ids unique by appending the row number to the id. For example:
<?php
$x = 10;
$i = 0;
for($i=0; $i<$x; $i++){
echo "<input type='text' onkeyup='multiply(" . $i . ")' id='tb" . $i . "-1'>";
echo "x";
echo "<input type='text' onkeyup='multiply(" . $i . ")' id='tb" . $i . "-2'>";
echo "=";
echo "<input type='text' onkeyup='multiply(" . $i . ")' id='tb" . $i . "-3'>";
echo "<br>";
}
?>
Total: <input type='text' id='tb4'> <input type='button' onclick='CalculateSum()' title='Calculate Sum'>
Your JavaScript code will then look as follows:
<script>
function multiply(row) {
var textbox1 = document.getElementById('tb' + row + '-1').value;
var textbox2 = document.getElementById('tb' + row + '-2').value;
var result = parseFloat(textbox1) * parseFloat(textbox2);
if(!isNaN(result))
{
document.getElementById('tb' + row + '-3').value = result;
}
}
function CalculateSum() {
let total = 0;
for (let i=0; i < 10; i++) {
total += document.getElementById('tb' + i + '-3').value;
}
document.getElementById('tb4').value = total;
}
</script>

how to append data after clear

I have to append data one by one by clicking button
$(document).ready(function() {
var i = 0;
$("#add_row").click(function() {
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><select id='myselect" + i + "' name='job_id[]" + i + "' class='form-control'><option value=''>Select the Job</option><?php
$mysql = "select * from ca_job where job_status != 'Closed' and job_customer_name = '".$com_id.
"'"; $result1 = mysql_query($mysql) or die(mysql_error());
while ($roww = mysql_fetch_array($result1)) {
$sql = "select * from `ca_job_type` where `jtype_id`= '".$roww['job_type'].
"'";
$res = mysql_query($sql) or die(mysql_error());
$row1 = mysql_fetch_array($res);
echo '<option value='.$roww['job_id'].
' selected>'.$roww['job_id'].
'-'.$row1['job_type_name'].
'</option>';
} ? > < /select></td > < td > < input name = 'invoice_description[]"+i+"'
type = 'text'
placeholder = 'invoice_description'
class = 'form-control input-md'
id = 'invoice_description' / > < /td><td><input name='sac_hsc_code[]"+i+"' type='text' placeholder='sac_hsc_code' class='form-control input-md'id='sac_hsc_code' / > < /td><td><select id='employee' name='tax_id[]"+i+"' class='form-control'><option value=''>Please select</option > <?php
$sql = "select tax_id, tax_type, tax_comp, tax_Percent FROM ca_taxmaster where tax_comp = '0'";
$resultset = mysql_query($sql) or die(mysql_error());
while($rows = mysql_fetch_array($resultset)) { echo '<option value='.$rows['tax_id'].' selected>'.$rows['tax_type'].'</option>'; } ?> < /select></td > < td > < input name = 'amount[]"+i+"'
type = 'text'
placeholder = 'amount'
class = 'form-control input-md' / > < /td>"
);
Above source which I have posted was multiple input type up to that working but after selecting drop-down of id='myselect' for first list it was showing the values if press (+) button above value get cleared and showing last data alone but I need the values of first row and second row.
$(document).ready(function() {
$('#myselect' + i).change(function() {
var job_id = $(this).find(":selected").val();
var dataString = 'job_id=' + job_id;
$.ajax({
url: '<?=base_url(); ?>ajax/getjob.php',
dataType: "json",
data: dataString,
cache: false,
success: function(employeeData) {
$('.appendData').empty();
if (employeeData) {
$("#dvPassport").show();
$("#dvPassport1").hide();
var myselect = [employeeData];
employeeData.forEach(function(item) {
var data = '<tr>';
data += '<td>' + item.job_id + '</td>';
data += '<td>' + item.disburse_Date + '</td>';
data += '<td align="right">' + item.approved_amount + '</td>';
data += '</tr>';
$('.appendData').append(data);
});
} else {
$("#dvPassport").hide();
$("#dvPassport1").show();
} //else
}
});
});
});
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
$("#delete_row").click(function() {
if (i > 1) {
$("#addr" + (i - 1)).html('');
i--;
}
});
});
Please click here to get clear view
In the above picture if I have selected dropdown two values showing and I am pressing the + button and selecting second drop-down first values getting cleared and showing second value what I have selected in the last dropdown. but I need the values of the first drop-down and second drop down.Please help me if anyone faces this problem .Thanks in advance.
i am not quit sure what you are trying to achieve but you forgot some ticks in for the value in the dropdowns, which might solve your problem
change
echo '<option value='.$roww['job_id'].' selected>'.$roww['job_id'].
to
echo '<option value="'.$roww['job_id'].'" selected>'.$roww['job_id'].
and
echo '<option value='.$rows['tax_id'].' selected>'.$rows['tax_type'].'</option>';
to
echo '<option value="'.$rows['tax_id'].'" selected>'.$rows['tax_type'].'</option>';
beside that
you should really consider formating your code well, it is very hard to read and understand and therefore very hard to debug
try to divorce your source, try to not mix php, html and javascript. it is possible to use it that way, but it also is a huge error source and very hard to maintain
use the mysqli functions instead of mysql -> MySQL Improved Extension

Trouble looping through data in HTML using JavaScript

I am using javaScript to go through 149 input type number fields and I am having problems getting it to work. I have conditions set that if the value of those number fields are negative, float, or 0 it will return an error message using
alert(" Error Message");
I am iterating through my input type's through a for loop like the following
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var i; var x = 0; var s; var val; var test;
for (i = 1; i < 150; i++) {
s = '' + i; //converts i into string
val = document.getElementById(s).value; //Puts string value into val
test = +val; //Converts val into number
//Error Checking
}
I have tried this code on smaller input type = number fields (such as 10), and all of my error flags work, but whenever I use my needed number 149 (set to 150 because I want it to do one less than 150) I do not receive any error messages or activity from my funciton.
Check the following example .
//For Demo Puropse
for(i=1;i<300;i++){
var node = document.createElement("input");
node.id=i
node.value=i
document.getElementById("stage").appendChild(node)
}
function checkValues(){
for(i=1;i<300;i++){
elemValue = document.getElementById(i).value
if(! isInteger(elemValue) || ! elemValue){
alert("Error ! : " + elemValue + "#" + i)
return;
}
}
alert("Passed")
}
function isInteger(x) {
return x % 1 === 0;
}
<button onclick="checkValues()">Check</button>
<br/>
<div id="stage"></div>
So here is my code. I am reading from a data base that I did not want to display the credentials too. In my code you will see a comment that has the comment question. Is there a way that I can just use php to get the product number and the quantity so that I can use it in form.php. It is a post method, but as the question says I am fairly new to this coding language. Hopefully this code snippet will tell you more about what I am actually trying to accomplish.
<form action="form.php" method="post">
<table cellpadding="6">
<tr>
<th>Description</th>
<th>Price</th>
<th>Weight</th>
<th>Image</th>
<th>Quantity</th>
</tr>
<!-- PHP LANGUAGE -->
<?PHP
$sql = "SELECT * FROM parts";
$q = $conn->query($sql) or die("ERROR: " . implode(":", $conn->errorIndo()));
while( $row = $q->fetch(PDO::FETCH_ASSOC))
{
echo '<tr>' .
'<td>' . $row['description'] . '</td>' .
'<td>' . $row['price'] . '</td>' .
'<td>' . $row['weight'] . '</td>' .
'<td> <img src="' . $row[pictureURL] .'" alt="' . $row[number] . '" style="width:50px;height:50px;">' .
'<td> <input type="number" id= "'. $row[number] . '" value="0">' .
'</td>' . '</tr>';
}
echo "</table>";
?>
</table> <br>
<input type="button" id="submit" value="Submit" />
</form>
<script>
var i; var x = 0; var s; var val; var test; var array = [];
$('form').submit(function(){{
var value = $(this).val();
for (i = 1; i < 5; i++) {
s = '' + i; //stores i as string
//getsElement id val string and stores into val
val = document.getElementById(s).value;
test = +val; //Converts string into tester int for error checking
if tester < 0 { alert("Must enter in one product!"); return;}
//CHECKS FOR FLOATS IN Quantity FIELD
else if (Math.floor(test) != Math.ceil(test)) { alert("Cannot have float quantities!"); return; }
else {
//My attempt at coding a block that captures the product
//Number, and the quantity selected. Is there a way
/* QUESTION */
array.push(i); array.push(x)
}
}
if (x == 0) { alert("Must have at least one product quantity to continue!"); return; }
else { alert("good!"); }
}}
</script>
</body>
</html>

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.

firefox issue with js slider

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

Categories

Resources