So I have this php foreach-loop that gets data from my database.
I use a $i++ to number up the same div.
$i=0;
foreach ($pages as $page){
echo '<div class="class_'.$i++.'">
echo '</div>';
}
Now I have a piece of jQuery in my footer that does something to the <div>
<script>
jQuery(document).ready(function($){
$('.class_1');
$('.class_2');
$('.class_3');
});
</script>
Because I will never know how many instances there are I want the jQuery to add up with the foreach-loop but the script is outside the loop so it won't add up.
I don't really know my jQuery that much so any help would be appreciated.
M.
You can get every element with that class and then use $.each for it.
$('[class^="class_"]').each(function() {});
$i=0;
foreach ($pages as $page){
echo '<div class="class_'.$i++.'">';
echo '</div>';
}
echo '<div number-of-divs=' . $i . ' style="display:none;"/>';
Your js code:
<script>
jQuery(document).ready(function($){
var number = $('div[number-of-divs]').attr('number-of-divs');
for (i = 1; i <= number; i++) {
$('.class_' + i);
}
});
</script>
A good approach for this is you should pass another class in your code or pass this only if above is the only case. $('[class^="class_"]').each(function() {}); This will not work in some cases so use below code
$i=0;
foreach ($pages as $page){
echo '<div class="catch_me class_'.$i++.'">
echo '</div>';
}
and get it from this script
$('.catch_me').each(function(){
//You code here
});
Related
I want to take things from another site and add href's a link. But my JQuery code just took the first href and change every hrefs' with that.
The code takes a table and tag. I just want to add a link in front of href.
I mean first href is like "example/example1" and I want to change it like "https:example.com/example/example1".
PHP cUrl code:
<?php
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,"https://www.planetdp.org/subtitlelist?translator=Kill+Master");
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl,CURLOPT_FOLLOWLOCATION,1);
$sonuc = curl_exec($curl);
preg_match_all('#<td class="subtitle1">(.*?)</td>#si',$sonuc,$info);
$info = $info[0];
echo '<ul class="movie-name">';
for($i=0; $i < count($info);$i++){
echo '<li class="content">';
echo $info[$i];
echo '</li>';
}
echo '</ul>';
?>
And JQuery code:
$(".alert-link").attr("href");
var href = $(".alert-link").attr("href");
$(".alert-link").attr("href", "https://planetdp.org"+href);
You need to iterate through all the classes you want to change href on
$('.alert-link').each(function() {
var value = $(this).attr('href');
$(this).attr("href", "https://planetdp.org"+href);
});
Tested working good. Hope this help you.
$('a').each(function() {
var value = $(this).attr('href');
$(this).attr("href", "https://planetdp.org"+href);
});
ok so I have this in my HTML code:
<script type="text/javascript" src="load2.php"> </script>
I saw somewhere you could call a php file like that and the javascript contained in it will be rendered on the page once echoed.
So in my PHP file i have this:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['DayNum']; }
$length = count($storeArray);
I connected to my database and stuff and pulled those records and stored them in an array. Now my problem is alerting them using js. This is what I have:
echo " function test() {
for(var i = 0; i<$length; i++){
alert($storeArray[i]);
}
}
";
The test() function is being onloaded in my HTML page, but for nothing the values in the array won't alert. Any help please?
echo " function test() {
for(var i = 0; i<$length; i++){
alert($storeArray[i]);
}
}
";
This code is literally writing what you have written above. It's not completely clear, but I believe your intent is to loop over the contents of your database data, and alert that to the browser with alert() function.
You can achieve this in a couple of ways.
Write multiple alert statements
echo "function test() {"; //Outputting Javascript code.
for($i = 0; $i<$length; $i++){ //Back in PHP mode - notice how we aren't inside of a string.
$value = $storeArray[$i];
echo "alert($value)"; //Outputting Javascript code again.
}
echo "}"; //Outputting Javascript code to close your javascript "test()" function.
Write a Javascript array, then loop over it in Javascript
echo "function test() {";
echo " var storeArray = ['" . implode("','", $storeArray) . "'];";
echo " for (var i = 0; i < storeArray.length; i++) {";
echo " alert(storeArray[i]);";
echo " };";
echo "}";
Finally, you could use AJAX and JSON to load the data, rather than outputting a JS file from PHP. That is an entirely different topic, though, and you should search StackOverflow for more examples as there are numerous questions and answers involving it.
Unless your array contains only number, you probably have JS error. You should put your $storeArray[i] in quotes in the alert function so it considered as a string in js.
alert('$storeArray[i]');
Once printed out, the JS will look something like this
alert('foo');
alert('bar');
Whereas with your code, it would've printed it like this
alert(foo);
alert(bar);
in your php file include load2.php
header("Content-Type: text/javascript");
in the in the top. so your browser get what it wants.
$i=0;
$storeArray = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[$i] = $row['DayNum'];
$i++;
}
echo "var arr = Array();";
echo "function test() {";
foreach ($storeArray as $key=>$item) {
echo "arr[".$key."] = ".$item.";";
}
echo "}";
echo "alert(arr);";
actually you can comment out the two echos containing the <script></script> part when including the file as <script src="load2.php" type="text/javascript" ...
I am trying to get some information from our database and then use it in javascript/JQuery and I think I might be doing something wrong with the scope of the coding.
Here is the current segment of code on my phtml page (magento)
<script type="text/javascript">
<?php
echo 'var $image-paths = new Array();';
for ($i = 0; $i < count ($_child_products); $i++)
{
echo '$image-paths[';
echo $i;
echo '] = ';
echo $this->helper('catalog/image')->init($_child_products[$i], 'image');
echo ';';
}
?>
document.getElementById('main-image').href = $image-paths[1];
</script>
The bottom getElementById is just for testing to see if it really grabbed that image path. So far the php stuff is working and echo'ing the correct links. However, is simply echo'ing them not enough; does it actually register it into the javascript code?
Here is what my source code looks like on my server:
<script type="text/javascript">
var $image-paths = new Array();
$image-paths[0] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5f b8d27136e95/feeds/MrsMeyers/MRM-64565-a.jpg;
$image-paths[1] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-64566-a.jpg;
$image-paths[2] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-64568-a.jpg;
$image-paths[3] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-D43114-a.jpg;
document.getElementById('main-image').href = $image-paths[1];
</script>
But the image link does not change to image-path[1]. Any ideas?
Thanks in advance!
$image-paths[0] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5f b8d27136e95/feeds/MrsMeyers/MRM-64565-a.jpg;
^-- no quote here, or at the end of the string
You're producing invalid javascript. Pop up your javascript console (shift-ctrl-J in chrome/firefox) and you'll see the error.
Producing javascript dynamically is problematic. Anytime you insert something from a PHP variable/function, you should run that through json_encode(), which guarantees you get valid javascript:
echo json_encode($this->helper('catalog/image')->init($_child_products[$i], 'image'));
Or better yet, change the code to:
$links = array();
for ($i = 0; $i < count ($_child_products); $i++)
$links[] = $this->helper('catalog/image')->init($_child_products[$i], 'image');
}
echo '$image-paths = ', json_encode($links);
<script type="text/javascript">
<?php
echo 'var $image_paths = new Array();';
for ($i = 0; $i < count ($_child_products); $i++)
{
echo '$image_paths[';
echo $i;
echo '] = "'; // Here the starting of quotes.
echo $this->helper('catalog/image')->init($_child_products[$i], 'image');
echo '";'; // Here the ending of quotes.
}
?>
document.getElementById('main-image').href = $image_paths[1];
</script>
This should work now. Hope it helps.
This is a part fo php code, which use the contentArray, which is a JSON, and generate the UI to the user, it generate html tags, also, it generate js code too.... It works, but I think the code is pretty difficult to read and maintain, any ideas??? thank you.
for($i = 0; $i < count($contentArray); $i++){
if($i %2 == 0){
echo ("<li class='even_row'>");
}else{
echo ("<li class='odd_row'>");
}
$content = $contentArray[$i];
echo("<textarea class='userdata' id='user_data_textarea_".$content->{'m_sId'}."'>");
echo($content->{'m_sDataContent'});
echo("</textarea>");
echo("</li>");
echo("<script type='text/javascript'>");
echo("$('#user_data_textarea_".$content->{'m_sId'}."').bind('keydown', function(e){");
echo(" TypingHandler.handleTypingInUserDataTextArea(".$content->{'m_sId'}.", e);");
echo(" });");
echo("</script>");
}
first for your odd and even styling there is not need for a class just use css
here is info on that
then in php only echo what you need in one line
$count = count($contentArray);
for($i = 0; $i < $count; $i++){
$content = $contentArray[$i];
echo('<li><textarea class="userdata" id="user_data_textarea_"'.$content->{'m_sId'}.'">'.$content->{'m_sDataContent'}.'</textarea></li>');
}
and lets put the jquery in the html page away from php
we get can get every item by using starts with selector
$('[id^=user_data_textarea_]').bind('keydown', function(e){
var id = this.id.str_replace("user_data_textarea","");
TypingHandler.handleTypingInUserDataTextArea(id, e);
});
One tip on your "for" loop, you should calculate the count of $contentArray before the loop. Every time the loop executes, it has to call that function.
$count = count($contentArray);
for ($i=0; $i<count; $i++) {
// ...
}
You could try real HTML:
<?php
for($i = 0; $i < count($contentArray); $i++){
$rowClass = $i %2 == 0 ?'even_row' : 'odd_row';
?>
<li class='<?= $rowClass ?>'>
<textarea class='userdata' id='user_data_textarea_<?=$content->{'m_sId'}?>'>
<?= $content->{'m_sDataContent'} ?>
</textarea>
</li>
<script type='text/javascript'>
//etc...
</script>
<?php } ?>
It should look something like this, for better readability in the IDE.
<?php
foreach($contentArray as $content){
?>
<li>
<textarea class="userdata" id="user_data_textarea<?php echo htmlentities($content['m_sId']); ?>">
<?php echo htmlspecialchars($content['m_sDataContent']); ?>
</textarea>
<script type="text/javascript">
$('#user_data_textarea_<?php echo htmlspecialchars($content['m_sId']); ?>').bind('keydown',function(e){
TypingHandler.handleTypingInUserDataTextArea('<?php echo htmlspecialchars($content['m_sId']); ?>',e);
});
</script>
</li>
<?php
}
You could remove the ( ) from the echo statements, they're not necessarily needed and might help make it look a little neater...
That actually looks pretty understandable to me; I could figure out what you're doing without difficulty. The only difference I would suggest would be the use of ternary operators for the row class:
echo "<li class='".( ($i%2 == 0) ? "even" : "odd" )."_row'>";
...but that's just me, some would find that MORE confusing, rather than less. I personally like putting it all in one line.
Personnaly, I like to use printf to write html code in php. It could look like:
for($i = 0; $i < count($contentArray); $i++){
printf("<li class='%s'>", $i % 2 ? "odd_row" : "even_row");
$content = $contentArray[$i];
printf("<textarea class='userdata' id='user_data_textarea_%s'>%s</textarea>",
$content->{'m_sId'},
$content->{'m_sDataContent'});
echo("</li>");
echo("<script type='text/javascript'>");
printf("$('#user_data_textarea_%1$s').bind('keydown', function(e){
TypingHandler.handleTypingInUserDataTextArea(%1$s, e);
});",
$content->{'m_sId'});
echo("</script>");
}
<?php
foreach($contentArray as $content){
$class = ($i %2 == 0) ? "even_row": "odd_row"; ?>
<li class="<?php echo $class ?>">
<textarea class='userdata' id='user_data_textarea_<? echo $content['m_sId'] ?>'>
<? php echo $content['m_sDataContent'] ?>
</textarea>
</li>
<script type='text/javascript'>
$('#user_data_textarea_<?php echo content['m_sId'] ?>').bind('keydown', function(e){
TypingHandler.handleTypingInUserDataTextArea(<?php $content['m_sId'] ?>, e);
});
</script>
<?php } // end foreach ?>
jQuery code should be already in the HTML, using some main selector and not binding elements one by one, it not makes sense for me. That should clarify your code.
for($i = 0; $i < count($contentArray); $i++){
$content = $contentArray[$i];
echo "<li class='" . (($i %2 == 0) ? "even_row" : "odd_row") . ">";
echo "<textarea class='userdata' id='user_data_textarea_".$content->{'m_sId'}."'>";
echo $content->{'m_sDataContent'};
echo "</textarea>";
echo "</li>";
}
ADDED
A generic case:
$(function() {
$('.userdata').click(function() {
some_function($(this).attr('id');
});
})
That is, bind using a class selector and late use some unique identifier for doing the job.
Put everything in arrays, then echo them at the END of your loop.
// Put each item in the array, then echo at the end
$items = array();
$js = array();
// I'm assuming that your content array has numeric keys
// if not, use the for statement from your original code
foreach ($contentArray as $i => $content)
{
// using sprintf
$items[] = sprintf('<li class="%s_row"><textarea class="userdata" id="user_data_textarea_%s">%s</textarea></li>'
, ($i % 2) ? 'even' : 'odd'
, $content->m_sId
, $content->m_sDataContent
);
// or just plain old concatenation
$js[] = "$('#user_data_textarea_{$content->m_sId}').bind('keydown', function(e){TypingHandler.handleTypingInUserDataTextArea({$content->m_sId}, e);});";
}
echo "<ul>" . join("\n", $items) . "</ul>\n"
. '<script type="text/javascript">' . join("\n", $js) . "</script>\n";
Separate your content and code using for example smarty. It requires some infrastructure investment in the short term, but improves maintenance in the long run.
Reflecting the comments, let's then treat PHP as a real templating language.
$contentCount = count($contentArray);
for($i = 0; $i < $contentCount; $i++)
{
$rowType = ( $i % 2 ) ? 'even' : 'odd';
$content = $contentArray[$i];
echo <<<EOT
<li class='{$rowType}_row'>
<textarea class='userdata' id='user_data_textarea_{$content->m_sId}'>
{$content->m_sDataContent}
</textarea>
</li>
<script type="text/javascript">
$('#user_data_textarea_{$content->m_sId}').bind('keydown', function(e)
{
TypingHandler.handleTypingInUserDataTextArea({$content->m_sId}, e);
}
</script>
EOT;
}
I am trying to allow the users of my website, to upload images and then select one to be a back image, the uploading works fine, but I have a problem in my controller or view I think, i would appreciate it some could help me out,
VIEW:
<div id="background-select">
<?php
$count = 0;
if(isset($special)) {
foreach ($special as $row) {
print '<div class="select">';
print "<a class='background_btn' href='index.php/home/set_background/".$row['background_id']."'>$count</a>";
print '</div>';
$background = $row['background_name'];
echo $background;
}
}
if(isset($generic)) {
foreach ($generic as $row) {
print '<div class="select">';
print "<a class='background_btn' href='index.php/home/set_background/".$row['background_id']."'>$count</a>";
print '</div>';
$background = $row['background_name'];
echo $background;
}
}
if(isset($user_background)) {
foreach ($user_background as $row) {
print '<div class="select">';
print "<a class='background_btn' href='index.php/home/set_background/".$row['background_id']."'>$count</a>";
print '</div>';
$background = $row['background_name'];
echo $background;
}
}
?>
</div>
<script type="text/javascript">
$("a.background_btn").click(function(ev){
ev.preventDefault();
alert("hello");
var url = $(this).attr("href");
alert(url);
$.ajax ({
url : url,
type: "POST",
success : function (html) {
alert("<?php echo $background; ?>")
$('#wrapper').css('background', 'url(/media/uploads/backgrounds/<?php echo $background; ?>)');
}
})
});
</script>
<div id="wrapper">
CONTROLLER:
public function set_background() {
$this->load->model('image_model');
if($query = $this->image_model->get_background_by_id($this->uri->segments[3])) {
//die(var_dump($query));
foreach ($query as $row) {
$data['background'] = $row['background_name'];
}
}
$this->load->view('template/background-select', $data);
}
The problem is that I can only set the background to the first returned value for example if the first loop return $background to = red.png then I cannot get anything but red.png to load in.
Can any one suggest a solution?
You appear to load a background using AJAX. However, you set the value of $background in the initial request, and the 'success' method of your AJAX call never uses the returned HTML. Only the background that was originally set when the page was first loaded. You should make sure your AJAX call returns the background, so you can use that in your javascript. Don't try to set the background in your 'success' method using PHP.
Also, not sure about this though, but your controller seems to set a single property $data['background'], overwriting it every iteration of the foreach instead of creating an array or hashmap.
I think you should keep separate PHP and JS. After completed upload process you can redirect (or show dynamically by using AJAX) uploaded images page. After user clicked an uploaded image just change background attribute maybe like this:
<div id="back">
<img src="foo.jpg" alt="..." />
<img src="bar.jpg" alt="..." />
...
</div>
$(function(){
$("#back img").bind("click", function(e){
var src = $(this).attr("src");
$("#back").css({"background-image": "url(/images/" + src + ")"});
});
});