how do I loop a php variable within a javascript script - php

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

Related

Update a span when a select dropdown is made using ajax

I am attempting to code the following script using jquery / ajax / php.
What happens is the php pulls all the records from the database and puts them into a select dropdown. When I select an item from the dropdown ajax pulls the price from the database and adds it into the span called priceeach1 . Well thats what its supposed to do, but my jquery is useless :-S .
The stockID comes from the select box value.
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock1').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += data[x]['priceeach'];
}
$('#priceeach1').text( options);
});
});
});
</script>
The HTML :
Price Each : £<span id="priceeach1"></span>
The select2.php :
<?php include 'connectmysqli.php'; ?>
<?php
$id = $_GET['stockID'];
$sql = 'SELECT * FROM stock WHERE stockID = ' . (int)$id;
$result = $db->query($sql);
$json = array();
while ($row = $result->fetch_assoc()) {
$json[] = array(
'priceeach' => $row['priceeach'],
);
}
echo json_encode($json);
?>
EDIT >> Ok I have now updated the code with the latest edits, this now WORKS.....apart from an odd problem......If I select the first or last item in the list no price is displayed, anything in between appears just fine..........
Try this,
var options = [];
for (var x = 0; x < data.length; x++) {
options = data[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
It should be like this you have to store price in the array options[] instead of option and then join them by any separator
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options[x] = data[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
});
});
});
</script>
You have to parse your JSON data to actual JSON Object before iterating it.
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var jsonParsed = JSON.parse(data);
var options = '';
for (var x = 0; x < jsonParsed.length; x++) {
options[] = jsonParsed[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
});
});
});
</script>
Try to use this snipt:
for (var x = 0; x < data.length; x++) {
options += data[x]['priceeach'];
}
$('#priceeach1').text( options);

My divs are upside down

So I'm looping through some values, and putting them in graph form inside a div. For some reason, though, they are going from the tops of the divs to the bottom. Any help would be greatly appreciated!
<div id="div1" style="height:50px;width:70px;background:yellow; "
</div>
<?php
$n=0;
for ( ;$n< $total_pages; ++$n) {
$previous_views= mysql_query("SELECT `$n` FROM `books`.`$thisone` WHERE `$thisone`.`$thisone` =0");
$resultedin = mysql_fetch_row($previous_views);
$fullresult=implode("','",$resultedin);
?>
<script>
var highview = '<?php echo $highest_views ; ?>';
var mything='<?php echo $fullresult ; ?>';
var pagestotal='<?php echo $total_pages ; ?>';
var thewidth=70/pagestotal;
var m = mything/highview;
var h = m*50;
for ( i=0; i<1; i++){
var div = document.createElement("div");
div.style.width = thewidth+"px";
div.style.height = h+"px";
div.style.background = "green";
div.style.float = "left";
var element=document.getElementById("div1");
element.appendChild(div);
}
</script>
<?php
}
?>
EDIT: I took out "float" and added
div.style.display = "inline-block";
, just in case anyone else has similar troubles. Thanks to everyone anyways for their input, I'll look into updating my SQL.

php variable together with javascript function

I have this piece of JS code:
<script type="text/javascript">
var counter = 0;
function myFunction() {
counter++;
document.getElementById('countervalue').innerHTML = counter;
}
</script>
Which plusses a number with 1 everytime a button is pressed.
The variable "counter" decides what number to start with when the page is loaded.
This number is currently 0. But it is supposed to be a number from the database. So I made a database connection using PHP and I now have the database number in a PHP variable. However, how do I implement it on the JS script? I have tried this:
<script type="text/javascript">
var counter = $clicks;
function myFunction() {
counter++;
document.getElementById('countervalue').innerHTML = counter;
}
The variable $clicks is the number from my database that is supposed to be the starting number when clicking the button.
I tried this as well, with no luck:
var counter = <?php $clicks ?>;
You're close. You're just forgetting to echo your variable's content:
var counter = <?php $clicks ?>;
should be:
var counter = <?php echo $clicks ?>;
or, if you have short tags enabled:
var counter = <?= $clicks ?>;
var counter = <?=$clicks?>;
Remember the echo.
var counter = <?php echo $clicks; ?>;
function myFunction() {
counter++;
document.getElementById('countervalue').innerHTML = counter;
}
var counter = <?php echo $clicks; ?>;
Counter value should be assigned as
var counter = <?php echo $clicks ?>;

How to insert value using ajax into database?

Here I am getting the counter value using javascript.
I want to insert those counter value into my database.
How can I do it? Please suggest me.
<script language="JavaScript">
var counter = 1;
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
window.onload = moreFields;
</script>
please read W3school ajax tutorial and click on try it yourself button I am sure that you will easily get that :)

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