I am running a foreach loop and I want to be able to change the content and class of the affected div elements.
foreach ($fields as $key => $value) { ?>
<script type="text/javascript">
document.getElementById('<?php echo $key ?>').innerHTML = '<?php echo $value ?>';
</script>
<?php } ?>
foreach ($fields as $key => $value) { ?>
<script type="text/javascript">
document.getElementById('<?php echo $key ?>').innerHTML = '<?php echo $value ?>';
</script>
you better use it like this .
<script>
<?php foreach ($fields as $key=>$value){ ?>
document.getElementById("<?php echo $key; ?>").innerHTML = "<?php echo $value; ?>";
<?php } ?>
</script>
and make sure you have all correspoinding elements with the same id as $key in this script for example.
<?php foreach($fields as $key=>$value){ ?>
<div id="<?php echo $key; ?>" ></div>
<?php } ?>
Regards
You may use only one part...
server-side with PHP and more tempting
client-side with Javascript
For the last approach, it could be okay to store / request the array as an JavaScript array, or json object and iterate it / update the existing elements during a loop after the site has been loaded.
A mixture of both may lead to a non-maintainable source and more render and execution time as expected.
I have not got what you actually want, But lets with this code. It may help you...
<script type="text/javascript">
$( document ).ready(function() {
<?php
foreach ($fields as $key => $value) {
?>
document.getElementById('<?php echo $key ?>').innerHTML = '<?php echo $value ?>';
<?php
}
?>
});
</script>
Related
This question already has answers here:
Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate]
(14 answers)
Closed 5 years ago.
I like to display php array in javascript, but in specific element with id.
below is my code which shows what I want to do.
<?php function ogolne_informacje(){
global $mypod;?>
<strong><?php echo 'Pokój: '?></strong><?php echo $mypod->display('room')."<br />";?>
<strong><?php echo 'Email: '?></strong><?php echo $mypod->display('user_email')."<br />";?>
<strong><?php echo 'Telefon: '?></strong><?php echo $mypod->display('phone')."<br />"; }?>
<?php $i =0;
while ( $mypod->fetch() ) :{
ob_start();
ogolne_informacje();
$output[$i] = ob_get_clean();
$i++;
} endwhile;?>
<div id="test"></div>
<script>
var out = <?php echo $output; ?>;
$(document).ready(function () {
$('#test').html(out.toString());
});
</script>
How can I do that?
Thanks!
You can't loop like that, you need to loop the PHP array and push into javascript array:
<script type="text/javascript" language="javascript">
var pausecontent = new Array();
<?php while ( $mypod->fetch() ) :{
ob_start();
ogolne_informacje();
?>
pausecontent.push('<?php echo ob_get_clean(); ?>');
<?php } ?>
</script>
I written code below that will extract the js like this:
src="assets/js/jquery.min.js"
src="assets/smooth-scroll/smooth-scroll.js"
I would like to have it like: (I guess my regex is wrong):
<script src="assets/js/jquery.min.js"></script>
<script src="assets/smooth-scroll/smooth-scroll.js"></script>
Here is my code:
$htmlData = file_get_contents($url);
if ($htmlData === false) {
echo "error!!";// Handle the error
die();
}
preg_match_all("/\<script(.*?)?\>(.|\\n)*?\<\/script\>/i", $htmlData, $matches);
//example output #1
echo "<pre>";
echo print_r($matches[1]);
echo "</pre>";
//example output #2
$matches = $matches[1];
foreach ($matches as $val) {
//echo "<script";
echo $val;
//echo "</script>"; //<-- adding <script> tags breaks this code
}
So how would I add all scripts into a textarea from this point?
Not sure the regex for styles to do the same.
You need to include the script part in the captured segment.
preg_match_all("/(\<script(.*?)?\>(?:.|\\n)*?\<\/script\>)/i", $htmlData, $matches);
Ok I figured out my code:
$htmlData = file_get_contents($wurl);
if ($htmlData === false) {
echo "error!!";// Handle the error
die();
}
preg_match_all("/(\<script(.*?)?\>(?:.|\\n)*?\<\/script\>)/i", $htmlData, $scripts);
preg_match_all('/<link(.*?)?\>/is', $htmlData, $styles);
//$scripts.=implode(" ",$matches[2]);
//Print array for scripts to get array level;
echo "<pre>";
print_r($scripts[2]);
echo "</pre>";
//Print array for styles to get array level;
echo "<pre>";
print_r($styles[1]);
echo "</pre>";
$scripts = $scripts[2];
foreach ($scripts as $script) {
$all_scripts.= "%script ".$script."#%/scripts#"."\n";
}
$styles = $styles[1];
foreach ($styles as $style) {
$all_styles.= "%link ".$style."#"."\n";
}
$all_scripts = str_replace(array('%', '#'), array(htmlentities('<'), htmlentities('>')), $all_scripts);
$all_styles = str_replace(array('%', '#'), array(htmlentities('<'), htmlentities('>')), $all_styles);
echo "<p>My Scripts:<br/>";
echo $all_scripts;
echo "</p>";
echo "<p>My Styles:<br/>";
echo $all_styles;
echo "</p>";
?>
<textarea name="my_Styles" rows="8" cols="100">
<?php echo $all_styles; ?>
</textarea>
<textarea name="my_Scripts"rows="8" cols="100">
<?php echo $all_scripts; ?>
</textarea>
Im making a like system and am encorporating ajax to make it smooth. Everything works okay except it always defaults to the last post in for loop. My thinking is there is no way for the javascript to know which element of id "like" to post to.
main.js:
$(".like>a").click(function() {
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
Im passing through the post variable from the view file. I grab the postID of each post.
userprofile_view.php:
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
model_posts.php:
function likePost($post) {
$data['user_ID'] = $this->session->userdata('id');
$data['post_liked'] = $post;
$insert = $this->db->insert('user_post_likes', $data);
return $insert;
}
userprofile.php(controller):
public function like_post() {
$this->load->model('model_posts');
$post = $this->input->post('post');
$this->model_posts->likePost($post);
}
If someone couldhelp me out that would be great!
The problem is your usage of a global variable in a loop, so the variable will have only the last value of the loop.
You can use a data-* attribute like
<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
</script>
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<div class='posts'>
<div class='posts_img'>
<img src="<?php echo base_url() . 'img/profilepictures/thumbs/' . $profilepicture?>">
</div>
<div class='posts_user'>
<strong><?php echo $prefname; ?></strong>
</div>
<div class='posts_date'>
<?php echo $this->model_posts->getPostTime($post->post); ?>
</div>
<div class='post'>
<p><?php echo $post->post ?></p>
</div>
<?php if($this->model_posts->doesUserLike($me, $postID)) { ?>
<div class='unlike'>
<?php echo anchor('userprofile/unlike_post/' . $me . '/' . $postID, 'unlike'); ?>
</div>
<?php } else { ?>
<div class='like' data-post="<?php echo $postID; ?>">
<?php echo anchor('#', 'like', array('id' => 'like')); ?>
</div>
<?php } ?>
then
$(".like>a").click(function () {
var post = $(this).parent().attr('data-post');
$.post(base_url + "index.php/userprofile/like_post/", {
post: post
}, function (data) {
alert('liked');
}, "json");
return false;
});
if you're sending same ID field with different values stop, send unique IDs with selected values OR send ID with values as post array, PHP can deal with it
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
This is your problem. You're declaring these variables in global scope. So every time your PHP foreach loop iterates, you're redefining the variable in global scope, overwriting the previous value.
Instead, set an id attribute on each <a> tag to be the $postID, and get that ID in your click handler, like so:
$(".like>a").click(function() {
var post = this.id;
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
You would have to modify the code that creates the <a> tags to include the id attribute with the $postID value assigned to it...I don't see that part included in your code samples.
<script type="text/javascript">
var jvalue = 'this is javascript value';
<?php
$abc = "<script>document.write(jvalue)</script>" ?>
</script>
<?php echo 'php_'.$abc; ?>
<script type="text/javascript">
var test = "<?php echo $abc; ?>";
</script>
<?php
echo '<script language="javascript">';
echo 'alert(test)';
echo '</script>';
?>
How to alert test variable, which contains PHP value?
I would like to get the PHP value in javascript, for further execution in my project.
try this code
<?php
echo '<script language="javascript">alert("'.$test.'"); </script>';
?>
this is updated code for you using javascript and PHP
<?php
$user = "rebel";
echo '<script> var name = "'.$user.'";
alert(name);</script>';
?>
This is the third code for you if this does not work then you have other problem
<?php
$abc= "Hello";
?>
<script type="text/javascript">
var test="<?php echo $abc; ?>";
</script>
<?php
echo '<script language="javascript">';
echo 'alert(test)';
echo '</script>';
?>
why are you assigning the variable to a javascript variable and then echoing that? sounds like extra work to me...
echo 'alert("' . $abc . '");';
Your code is not so clear, i think you want something like this:
<?php
$test = "hi there!";
echo '<script type="text/javascript">';
echo 'alert("'.$test.'")';
echo '</script>';
?>
var test="<?php echo $abc; ?>"
<script language="javascript">alert(test); </script>
If you want to alert the value of $abc, you need to escape the slash in the following line with a backslash, like this.
<?php $abc = "<script>document.write(jvalue)<\/script>" ?>
You also need to remove this line (or escape the < and the > in $abc). If you don't, the script tags will mess up the rendered html code.
<?php echo 'php_'.$abc; ?>
I need to pass an array as a function argument from php to js.i am getting the values from
database.
while ($rows = pg_fetch_array($qry))
{
?>
<option value="<?php echo $rows['relation_name_local']?>">
<?php echo $rows['relation_name_local']?>
</option>
<?php
$app_relation_array[] = $rows['relation_name_local'];
}?>
i want to pass $app_relation_array[] values through addNewRow() this function
Can anyone please help me with this.
Thanks a lot.
Use json_encode() function and echo it in javascript
while ($rows = pg_fetch_array($qry))
{
?>
<option value="<?php echo $rows['relation_name_local']?>">
<?php echo $rows['relation_name_local']?>
</option>
<?php
$app_relation_array[] = $rows['relation_name_local'];
$new_data = json_encode($app_relation_array[]);
}?>
And in your html inside script tag
<script>
var data = JSON.parse("<?php echo $new_data; ?>");
alert(data);
</script>
Use json_encode function in php