how to use jquery selectors in a for loop? - javascript

i want to acheive this :
for (i = <?php echo $current_i ?> /*then I get augmented in javascript */;i<max;i++){
$('#anyid****')./* my actions goes here */
}
here i want to put the counter I of the javascript in the selector
how could i do that ???

Sorry i don't know PHP but i hope you wanted to do something like below
for (i = <?php echo $current_i ?> ;i<max;i++){
$('#div'+i)/*do the rest*/
}
the + is for concatenation, i hope it is same in PHP. Also you could cast i to string.
Just for OP's understanding
in line 2 $('#div'+i) i is a integer type and others $(#div) are of type string. For jquery needs a string selector to retrieve a matching dom node and for that i needs to also be casted/converted to a string variable so that it could concatenate/add/attach with the prefix string which is in this example #div. in c# you add 2 strings like this var result = "#div" + i.ToString(); and i did not know PHP equivalent for + in c#,hence a sorry at the start of post. Now do you understand?

for (i = <?php echo $current_i ?> /*then I get augmented in javascript */;i<max;i++){
$('#anyid' + i)./* my actions goes here */
}
you can just concatenate it to the string of your selector.

That's not very "jQuery-ish". Assuming the elements have IDs with a continuing part and are in order, you can give every element a common class and use slice [docs] and each [docs]:
$('.commonClass').slice(<?php echo $current_i ?>, max + 1).each(...
You could provide better solutions if you explain more about your problem. E.g. giving each element an increasing ID does not seem to be a deliberate solution.
P.S.: I wouldn't put the PHP variable there either, maybe assign the value to a JavaScript variable first.

it would be a lot cleaner if you split up the php and javascript like this.
js_var.php
<?php
$phpvars = array(
'max' => 12,
'fop' => 22
);
function phpvar($key = NULL){
global $phpvars;
return ($key)
? json_encode($phpvars[$key])
: json_encode($phpvars);
}
?>
usage
<?php include('phpvars.php');?>
<script type="text/javascript">
window.phpvars = <?=phpvar()?>;
var max = phpvars.max;
for (var i=0;i<max;i++){
console.log(i);
}
console.log(php);
</script>

Related

Use data-attribute in javascript to alter elements width

I am still new, so please forgive me if this question is too trivial or the issue has already been discussed. I didnt find anything specific, which led me to open a new question. That said, here is how it goes:
Im passing values from my database into data-attributes in order to use them in javascript to alter the width of certain elements (i.e. graphs). The element that should be altered according to the retrieved value is a p-Tag (together with others it sits inside a foreach):
<span class="fdpg-nut-vline"><p class="fdpg-nut-graph" id="graph" data-somedat="<?php echo "'" . $value['Nu_Val'] . "%'" ?>"></p></span>
The value of the data-attribute with the name "somedat" I want to use in js, like so:
var somevar = document.getElementById('graph').getAttribute("data-somedat");
document.getElementById("graph").style.width = somevar;
What I did?
I checked whether the format of the value is right. I therefore set a 'static' variable var somevartest = '20%'; and used it in the code above. It worked and the graph changed accordingly.
I checked if the value is passed into the data-attribute: (1) in the sourcode (its there!) and afterwards included an alert which shows me the value in the right format aswell (i.e. 'x%').
What is it that Im not getting? How can I solve my problem?
The proper way to pass data from PHP to JavaScript is using a JSON string.
PHP:
<?php
$arr = get_from_database_as_array(...);
// at end of page before your scripts:
echo "<script>";
echo "var data = " . json_encode($arr, true) . ";";
echo "</script>";
HTML:
<script>
console.log(data);
document.getElementById("elem1").style.width = data["elem1"] + "px";
document.getElementById("elem2").style.width = data["elem2"] + "px";
// and so on.
</script>

How to pass numeric values from PhP to Javascript without posting data?

I need some data from SQL to Javascript, so I called them in PhP and I'm trying to pass these values to Javascript, but the code below causes a NaN failure... if I set a PhP command for the Javascript variable, I can't use it as a numeric value...
<?php
$val=12;
?>
<script>
var val="<?php echo $val; ?>";
</script>
I got a solution but I'm sure, this is not the best way to do this:
<?php
$val=12;
?>
<input type="number" id="val" name="val" value="<?php echo $val; ?>" hidden>
<script>
var val=getElementById('val').value;
</script>
One way of doing it is removing the quotes:
<script>
var val = <?php echo $val; ?>;
</script>
But there may be edge cases in which php yields unexpected results, so in my opinion it's a good practice to keep the quotes and to update the value.
If you are sure that the value will always be an integer and/or that you need an integer in your code you can do:
var numericValue = parseInt(val, 10);
Or if you are using lodash:
var numericValue = _.parseInt(val);
Remember to pass 10 as the second parameter which will specify the radix in the first case, as there may be edge cases in which numbers are interpreted with a base different than 10 (like hexadecimal or binary).
Otherwise if the value can be a float I suggest to do:
var numericValue = parseFloat(val);
And if you want to limit the digits after the decimal point you can do:
var numericValue = Number(parseFloat(val).toFixed(4));
.toFixed() returns a string so if you still need a number it's better to convert it back to a number with the Number() function.
Passing the value through an input may work but it doesn't look like a good practice, anyway to get the element you will need to add document before getElementById:
var val = document.getElementById('val').value;
Thank you all! It's easier, then I thought! I thought, quotes are always needed, as JavaScript identify "<?php" tag as string.

How To Escape a PHP Variable in Javascript?

I am trying to create a Javascript function that echoes out a Wordpress function called the_title() which just returns the title of the a blog. Through PHP it echoes out fine but when I do it through Javscript, however, quotes seem to be unescaped (specifically single quotes). Any help or explanation why this is happening?
THE CODE:
function createSliderTabs() {
var para = document.createElement("li");
var strings = "<?php the_title(); ?>";
var post_string = strings.replace(/"/g, "").replace(/'/g, "").replace(/\(|\)/g, "");
var node = document.createTextNode(post_string);
para.appendChild(node);
var element = document.getElementById("control-navigation");
element.appendChild(para);
}
createSliderTabs();
THE RESULT:
Macy&#8217 ;s Herald Square (had to include space or it would've changed to single quote)
WHAT IT SHOULD BE:
Macy's Herald Square
Any help or guidance on why this is happening? Thx in advance...
From php to js transformation you always have to use json_encode().
to avoid xss
to describe unicode characters
You can use html_entity_decode:
I'm not really familiar with wordpress, but I suppose you would use it inside the_title():
function the_title()
{
$str = 'Macy’s Herald Square';
echo html_entity_decode ($str, ENT_COMPAT , "UTF-8");
}
If you need to use json_encode() you should be able to do
$json = html_entity_decode(json_encode($array), ENT_COMPAT , "UTF-8");
EDIT: added ENT_COMPAT , "UTF-8"

javascript append colon to variable

I have a javascript function in which am trying to send some data to another php script. I have to send an array of values to the php script. I am trying to append : to each value in the javascript function so that I can use implode to get the array values in my php script. This is the javascript function I have.
$("#update-form").submit(function(e) {
$passdata = "";
<?php
for ($i=1; $i <= $total_columns - 1 ; $i++) {
printf('$passdata+=$("#slider%d").val().:;' . PHP_EOL, $i);
}
?>
if ($(this).is(':not([data-submit="true"])'))
{
$('form').append('<input type="hidden" name="foo" value="'+$passdata+'">');
$('form').data('submit', 'true').submit();
e.preventDefault();
return false;
}
})
I used printf('$passdata+=$("#slider%d").val().:;' . PHP_EOL, $i); However, I am not able to see the variable in php script. I also tried,
printf('$passdata+=$("#slider%d").val()+=:;' . PHP_EOL, $i);
How can I append : to the variable in my javascript function?
Look at what it generates in the client, is that valid JavaScript?
$passdata+=$("#slider1").val().:;
JavaScript does not do string concatenation that way.
$passdata+=$("#slider1").val() + ":";
If I were you, I would use an array and join()
$passdata.push($("#slider1").val());
and than make it a string
var myValue = $passdata.join(":");
Even better, do not use PHP to generate the JavaScript! Just add a class on the elements and use a single selector with map();
$(".myCommonClass").map( function(){ return this.value; }).get().join(":");
Or just post multiple form element names to the server and handle the multiple values on the server like forms always work.
Rather than hacking around this abomination, why not just do something like this:
Add a class to all of your sliders. Then:
$(".sliderClassNameHere").map(function(x) {return x.value;}).get().join(":");
Alternatively... just submit the sliders...?
Why not use json? In PHP you use json_encode(), put it in hidden input's value, and then in javascript you use function json_decode() on that value. That's what json is for.

Add a comma to the end of each line using php [duplicate]

This question already has answers here:
Convert php array to Javascript
(21 answers)
Closed 9 months ago.
I am having a csv file with 1 email id in each line. I want to add comma after each email id. I want to add a comma to the end of each line using php. How can i do this? Is there a particular function for that?
UPDATE
I want this so that I can construct an array out of it in javascript.
I will be loading the csv file using php and then printing it in my js.
Like
var myCars=[<?php print $csv; ?>];
So that I acheive something like this.
var myCars=["Saab#gmail.com","Volvo#gmail.com","BMW#gmail.com"];
Or is there a better way to do this?
$lines = file('file.csv');
foreach ( $lines as & $line ) {
$line .= ',';
}
file_put_contents('file.new.csv', implode(PHP_EOL, $lines));
something like that should do,
cheers
<?php
$lines = file('org.csv');
foreach ( $lines as & $line ) {
$line = trim( $line ) . ',';
}
file_put_contents('new.csv', implode(PHP_EOL, $lines));
Why not use the csv-specific functions?
$old = fopen('file.csv','r');
$new = fopen('new.csv','w+');
while($line = fgetcsv($old))
{
fputcsv($new,$line);
}
fclose($old);
fclose($new);
The above code will write a new csv, line per line, but if you just want to generate a javascript array, why not do this:
$file = fopen ('file.csv','r');
$all = array();
while($line = fgetcsv($file))
{
$all[] = $line[0];//if there is only 1 field/line
$all = array_merge($all,$line);//if multiple
}
fclose($file);
$js_array = '["'.implode('",',$all).'"];';
//or, the way I'd advise against, but good for multi-dimensional, assoc arrays
echo 'var array = JSON.parse("'.json_encode($all).'");';
why not just
$csv = str_replace("\n", ",\n", $csv);
Instead of echoing an entire csv string, you can import the file to an array using the fgetcsv function, then echo it out using json_encode(). That way you're sure to get a valid javascript array. It will also quote and encode any strings for you.
Oh, remember to run the array through some iterator which will run utf8_encode on all strings. If you have invalid utf8 characters, json_encode will barf.
There are plenty of examples on php.net of doing the different parts of this, but I can provide some examples if needed.

Categories