Echo PHP value inside a jquery Function - php

I am trying to assign a php echo value to an input generated from a jquery function. But so far no luck. It breaks the function and no results are displayed along with the input field. What is the proper way for this scenario to display php value inside the query function.
PHP
$tablename = "table";
$next_increment = 0;
//$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = $db_con->prepare("SHOW TABLE STATUS LIKE '$tablename'");
$qShowStatusResult->execute();
$results = $qShowStatusResult->fetchAll(\PDO::FETCH_ASSOC);
foreach($results as $value){
$next_increment = $value['Auto_increment'];
}
var nextAutoIncrement = '"'<?php echo $next_increment; ?>'"';
Jquery
newSection.children(':nth-child(1)').children(':first').attr('id', 'auto_id_' + newNum).attr('name', 'auto_id_' + newNum).val(nextAutoIncrement).hide();

Try this
<script language="javascript" type="text/javascript">
var nextAutoIncrement = '<?php echo $next_increment;?>';
</script>

Try like this:
<script language="javascript" type="text/javascript"
var nextAutoIncrement = <?php echo $next_increment; ?>;
</script>

<script>
//if it is anumber
var nextAutoIncrement = <?php echo $next_increment; ?>;
// if ity is a string
var nextAutoIncrement = '<?php echo $next_increment;?>';
</script>

In JS code there is require to define the <script> tag:
$tablename = "table";
$next_increment = 0;
$qShowStatusResult = $db_con->prepare("SHOW TABLE STATUS LIKE '$tablename'");
$qShowStatusResult->execute();
$results = $qShowStatusResult->fetchAll(\PDO::FETCH_ASSOC);
foreach($results as $value){
$next_increment = $value['Auto_increment'];
}
<script type="text/javascript" >
var nextAutoIncrement = '<?php echo $next_increment; ?>';
</script>

Related

how do I loop a php variable within a javascript script

I created a form with a text field that has Spry Validation (ie javascript). The user can select the number of rows in the form from 1 to 10. I need the code below to also expand but I'm not familiar enough with javascript to make it work.
$divkey is the variable that controls how many rows are in the form.
Original
<script type="text/javascript">
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "none", {validateOn:["change"], maxChars:20});
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
so I need the line 'var sprytextfield1...' to repeat based on $divkey with the next line being 'var sprytextfield2...' and so on. Can someone please rewrite this so it will work?
Trying to use php
<script type="text/javascript">
<?php for ($i = 0; $i < $divkey; $i++) { $num=$i+1; ?>
var sprytextfield<?php echo $num;?> = new Spry.Widget.ValidationTextField("sprytextfield<?php echo $num;?>", "none", {validateOn:["change"], maxChars:20});
<?php }?>
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Trying to use javascript
<script type="text/javascript">
var numwrestler = <?php echo $wrestlerkey; ?>;
var sprytextfield = [];
for (var i = 0; i < numwrestler; i++) {
var num = i+1;
var sprytextfield[num] = new Spry.Widget.ValidationTextField("sprytextfield"+num, "none", {validateOn:["change"], maxChars:20});
}
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
I'd recommend that you use a Javascript array for this type of task.
Your code is mostly correct, but the var in your for loop is incorrect, and the creation of the num variable instead of just using i is redundant.
<script type="text/javascript">
var sprytextfield = new Array();
var numwrestler = <?php echo $wrestlerkey; ?>;
for(var i = 0; i < numwrestler; i++){
sprytextfield[i] = new Spry.Widget.ValidationTextField("sprytextfield"+(i+1), "none", {validateOn:["change"], maxChars:20});
}
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Be sure that your PHP variable(s) are defined in the file before you include them in your script.
In your PHP code, you never define the variable divkey, by deafault the value will be 0.
Try:
<script type="text/javascript">
<?php $divkey = 10; for ($i = 0; $i < $divkey; $i++) { $num=$i+1; ?>
var sprytextfield<?php echo $num;?> = new Spry.Widget.ValidationTextField("sprytextfield<?php echo $num;?>", "none", {validateOn:["change"], maxChars:20});
<?php }?>
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Please, note that the variable that you are using as index $num in every iteration of the loop will be increasing 2, because of the i++ and the $num=$i+1

what is the best way to check if a parameter is set in PHP within a jQuery template?

what is the best way to check a parameter is set in PHP within jQuery template?
I have this code:
var custID = '<?php echo htmlentities( $_GET['custID'] ); ?>';
I need to check that it is set, if it is set then echo that value, if it is not produce an error.
i'd say:
<?php
if(isset($_GET['custID']))echo "var custID = '".$_GET['custID']."';";
else echo "alert('error');";
?>
try this
var custID = <?php echo htmlentities( isset($_GET['custID']) ? $_GET['custID'] : "" ); ?>;
I'll do it like that, first we need to check if the custID exists :
<?php
$custId = isset($_GET['custID'] && !empty($_GET['custId']) ? htmlentities($_GET['custId']) : false;
if(!$custId) {
//cutsId don't exists, show your error
?>
Error
<script type="text/javascript">var custId = false;</script>
<?php } else { ?>
<script type="text/javascript">var custId = '<?php echo $custId; ?>';</script>
<?php } ?>
There you're sure that the javascript var will not throw an error.
There's another way within the script :
<script type="text/javascript">
var custId = '<?php echo isset($_GET['custId']) ? htmlentities($_GET['custId']) : false;?>';
</script>
Note that i'm keeping the quotes or they might be an error because var custId = ; is not valid but var custId = ''; is.
If custId doesn't exists, the Javascript var will be empty (not undefined) and you could check it like that :
if(custId.length)
//custId exists

how to make countdown timer for bidding website

I have to create a countdown timer for a bidding website. The timer works properly when I put it outside of the while loop. However, id does not work inside the loop. What am I doing wrong? Here is my code:
<script>
var before=""
var current="ended"
var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
function countdown(yr,m,d,id){
theyear=yr;themonth=m;theday=d
var today=new Date()
var todayy=today.getYear()
if (todayy < 1000)
todayy+=1900
var todaym=today.getMonth()
var todayd=today.getDate()
var todayh=today.getHours()
var todaymin=today.getMinutes()
var todaysec=today.getSeconds()
var todaystring=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec
futurestring=montharray[m-1]+" "+d+", "+yr
dd=Date.parse(futurestring)-Date.parse(todaystring)
dday=Math.floor(dd/(60*60*1000*24)*1)
dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1)
dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1)
dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1)
if(dday==0&&dhour==0&&dmin==0&&dsec==0){
document.getElementById(id).value=current
return
}
else
document.getElementById(id).value="Only "+dday+ " days, "+dhour+" hours, "+dmin+" minutes, and "+dsec+" seconds left "+before
setTimeout("countdown(theyear,themonth,theday,id)",1000)
}
</script>
<?php
include('../connection.php');
$rs = mysql_query("select * from datepic") or die(mysql_error());
if(mysql_num_rows($rs)){
while($row = mysql_fetch_array($rs))
{
$date = str_replace('-',',',$row['date']);
echo '<input type="text" id="'.$row['id'].'" size=80>';
?>
<script>
countdown(<?php echo $date.','.$row['id'];?>)
</script>
<?php
}
}
?>
change setTimeout with this:
setTimeout(function(){countdown(theyear,themonth,theday,id);},1000)
you can make your function to jQuery function like that:
jQuery.fn.countdown = function(yr,m,d){
$that = $(this);
theyear=yr;themonth=m;theday=d
var today=new Date()
var todayy=today.getYear()
if (todayy < 1000)
todayy+=1900
var todaym=today.getMonth()
var todayd=today.getDate()
var todayh=today.getHours()
var todaymin=today.getMinutes()
var todaysec=today.getSeconds()
var todaystring=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec
futurestring=montharray[m-1]+" "+d+", "+yr
dd=Date.parse(futurestring)-Date.parse(todaystring)
dday=Math.floor(dd/(60*60*1000*24)*1)
dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1)
dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1)
dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1)
if(dday==0 && dhour==0 && dmin==0 && dsec==0){
$that.val(current);
return
}
else
$that.val("Only "+dday+ " days, "+dhour+" hours, "+dmin+" minutes, and "+dsec+" seconds left "+before);
setTimeout(function(){ $that.countdown(theyear,themonth,theday);},1000)
}
<?php
include('../connection.php');
$rs = mysql_query("select * from datepic") or die(mysql_error());
if(mysql_num_rows($rs)){
while($row = mysql_fetch_array($rs))
{
$date = str_replace('-',',',$row['date']);
echo '<input type="text" id="'.$row['id'].'" size=80>';
?>
<script>
$("?php echo $row['id'] ?>").countdown(<?php echo $date?>);
</script>
<?php
}
}
?>

Javascript timer not looping along with mysql_fetch_array results

<? while($row = mysql_fetch_array($result))
{
$result2 = $row['end_time'];
echo"<td><div id=defaultCountdown></div></td>";
?>
<script type=text/javascript>
$(function ()
{
var t = ('<? echo $result2; ?>').split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
$('#defaultCountdown').countdown({until: d});
$('#year').text(austDay.getFullYear());
});
</script>
<? }
?>
So basically I wanted to launch the Javascript countdown timer for each row of results generated by mysql_fetch_array. However, in the code above, the timer only works for the first row of result. How do I make the timer work for every row of result?
EDIT
<td> 2012-12-17 13:12:22</td><td> <img src = Images/1324133424.jpg height=200 width=300 /> </td><td> active</td><td><div id=defaultCountdown0></div></td>
<script type=text/javascript>
$(function ()
{
var t = ('2012-12-17 13:12:22').split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
$('#defaultCountdown0').countdown({until: d});
$('#year').text(austDay.getFullYear());
});
</script>
<td> 2012-12-01 13:12:22</td><td> <img src = Images/1322754818.jpg height=200 width=300 /> </td><td> active</td> <td><div id=defaultCountdown1></div></td>
<script type=text/javascript>
$(function ()
{
var t = ('2012-12-01 13:12:22').split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
$('#defaultCountdown1').countdown({until: d});
$('#year').text(austDay.getFullYear());
});
</script>
In your PHP while loop, you are setting the same ID for all divs, which is probably why only the first row works. However, as I said in my comment, you need to add the actually JavaScript that is generated by your PHP code.
echo"<td><div id=defaultCountdown></div></td>";
EDIT:
Here's what the code should look like. Run it as it is and then try making small changes to get it to do what you want:
<?
while($row = mysql_fetch_array($result))
{
$i = 0;
$result2 = $row['end_time'];
echo "<td><div id=defaultCountdown$i></div></td>";
?>
<script type=text/javascript>
$(function ()
{
var t = ('<? echo $result2; ?>').split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
$('#defaultCountdown<?php echo $i; ?>').countdown({until: d});
$('#year').text(austDay.getFullYear());
});
</script>
<?
$i++;
}
?>

how we can assign single value of array to any variable in javascript

<?php
$abc=array();
$abc = (abc, cde,fre);
?>
<script language="javascript" type="text/javascript">
for (var i = 0; i < 3; i++) {
var gdf = "<?php echo $lat['i'];?>";
alert("value ="+gdf);
}
</script>
Following your comment, I think this is what you are trying to do:
<?php
$abc = array('abc', 'cde', 'fre');
?>
<script type="text/javascript">
var gdf = '<?php
for ($i = 0; $i < count($abc); $i++) {
echo "{$abc[$i]}";
if ($i != (count($abc)-1)) echo ", ";
}
?>';
</script>
Will output:
http://codepad.org/KjEH5CmN
<script type="text/javascript">
var gdf = 'abc, cde, fre';
</script>
NOTE
Using implode if you want a single variable would also work well:
http://codepad.org/UwukCY4m
<?php
$abc = array('abc', 'cde', 'fre');
?>
<script type="text/javascript">
var gdf = '<?php echo implode(', ',$abc); ?>';
</script>
You're not looking to assign a single value of the array; you're looking for the whole array. Your JavaScript loop is trying to iterate over the entire $abc array from PHP.
Something like this would work:
var abc = <?php echo json_encode($abc); ?>;
for(var i = 0; i < 3; i++)
var gdf = abc[i];
alert("value = " + gdf);
}
Firstly, to build a PHP array you should be using this notation:
<?php
$abc = array('abc', 'cde', 'fre');
?>
Next, it's not possible use JavaScript to directly loop through your variable that is stored in PHP. You can do something like this instead, performing the loop in PHP:
<?php
$abc=array('abc', 'cde', 'fre');
?>
<script language="javascript" type="text/javascript">
<?php foreach ( $abc as $el ): ?>
alert('value=<?php echo $el ?>');
<?php endforeach ?>
</script>
Or, if you'd really like the loop to happen in JavaScript and not PHP, you can "export" the PHP array to JavaScript by converting the array to a JSON string and outputting it.
<?php
$abc=array('abc', 'cde', 'fre');
?>
<script language="javascript" type="text/javascript">
var abc = <?php echo json_encode($abc) ?>;
for ( var i = 0; i < abc.length; i++ ) {
alert('value=' + abc[i]);
}
</script>

Categories