Jquery .each method - php

learning Jquery and integrating with PHP - getting there, but have one last challenge in some code I'm working on.
I have HTML in a string, trying to pull html in tags, might be multiple elements in the HTML string, so trying to use each. My function worked fine without each, below is my each integration (returns nothing currently):
<?php
$info = '<li><strong>I want this text</strong></li><li><strong>I want this text too</strong></li>';
$info = json_encode($info);
?>
<script type="text/javascript">
$(document).ready(function () {
$("a", $( < ? php echo $info; ? > )).each(
function () {
alert($(this).html());
});
};
This code below does work, but only returns the first element in the HTML:
<?php
$info = '<li><strong>I want this text</strong></li>';
$info = json_encode($info);
?>
<script type="text/javascript">
$(document).ready(function () {
var output = $("a", $( < ? php echo $info; ? > )).html();
var link = $("a", $( < ? php echo $info; ? > )).attr("href");
alert(output);
alert(link);
});
</script>

This is a description and a working example of How to use .each() LINK
You can try this one as a example
$("a").each(function(index){alert($(this).html()});

Your code is not working because there are a few syntax issues.
First, change
< ? php echo $info; ? >
to
<?php echo $info; ?>
PHP doesn't like spaces and the opening and closing tags must appear without spaces.
Second, close the ready function and the script tag properly. Instead of
};
use,
});
</script>
Why are you encoding a piece of XML with JSON? That makes like no sense at all. Both are ways to encode data. HTML is XML too, btw. You can directly reference the $info variable since PHP will process everything first on the server.
<?php
$info = '<li><strong>I want this text</strong></li>';
?>
<script type="text/javascript">
$(document).ready(function() {
$("a", $("<?php echo $info; ?>")).each(
function () {
alert($(this).html());
}
);
});
Or just remove the temporary variable altogether. Makes it combersome to read, but that's essentially what PHP is doing.
$("a", $("<?php echo '<li><strong>I want this text</strong></li>'; ?>")).each(
Or to make it even simpler, since you already have the HTML, simply include it as part of the page and maybe give it an ID to make referencing it easier with jQuery.
<li id="myList">
<strong>I want this text</strong>
</li>
<script type="text/javascript">
$(document).ready(function() {
$("a", "#myList").each(function() {
alert($(this).html());
});
});
</script>
This last example gets rid of PHP completely, but you weren't really using it anyways.

Related

Use jQuery in external php file

I have a php file that I load into another php file with jQuery. This works, but the moment I start using jQuery in the 'external file', I get ERROR 500.
The reason I used this approach is because this is handy to refresh the data after an AJAX function.
This I have:
test.php:
<script type="text/javascript" src="js/modernizr.custom.29473.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function () {
$(document).tooltip({
items: ".plupic , .ingr",
content: function() {
var element = $( this );
if ( element.is( ".plupic " ) ) {
var src = element.attr('src');
return "<img src='" + src + "' style='max-height: 300px; max-width: 300px;'>";
}
if ( element.is( ".ingr" ) ) {
var txt = element.text();
return txt;
}
}
});
$('#kasticket').load('cart.php');
});
</script>
</head>
<body>
<div class="container">
<div id="kasticket"></div><!-- Load data with jQuery-->
cart.php:
I just do a select from the database and write some data to a table with echo();
This works perfectly, but the moment I want to use jQuery, I goes all wrong...(I know this for sure because the jQUery works in a local html file and putting this line in comment makes my php working again)
echo("
<script>
jQuery(document).ready(function() {
if($('#L$MyAant').width() < 70) {
$('.TR1$MyAant').show();
$('.TR2$MyAant').hide();
}else{
$('.TR2$MyAant').show();
$('.TR1$MyAant').hide();
}
});
</script>
");
I have no idea what I'm doing wrong.
If its any help: http://www.itreflex.be/TestAcc/test.php (with currently the jQuery line in comment).
And this is cart.php, exported to txt, it was to long to paste here.
hard to tell without the full source code but I have got a couple of ideas:
First Error 500 should be the HTTP code for internal server error, which basically means that the error lies on the server, then on the PHP side.
Could it be possible that you are mixing up PHP and jQuery on some of your other statements not posted here?
Second, you missed a single quote on your line
$('#kasticket').load(cart.php');
In your cart.php remove the brackets after echo ... For example
echo "<script>
jQuery(document).ready(function() {
if($('#L$MyAant').width() < 70) {
$('.TR1$MyAant').show();
$('.TR2$MyAant').hide();
}else{
$('.TR2$MyAant').show();
$('.TR1$MyAant').hide();
}
});
</script>";
Try this above line in your cart.php and see if that works.

running javascript from php?

I don't know if this is possible as i know php is server side and javascript is client side.
But i am trying to run this javascript code from an if isset inside a php page.
I am using this code:
<?php
if( isset($_POST['submit2'])){
echo "
<script type=\"text/javascript\">
$(document).ready(function(){
setTimeout(function () {
doWork();
window.location.reload();
}, 2000);
function doWork() {
$('#submit').trigger('click');
}
});
</script>";
}
?>
this javascript should click on the button named (submit) and it works fine if its not inside the PHP echo.. and I also checked to see if the if if( isset($_POST['submit2'])) actually returns a value and it does and it works as it should.
So, I don't know what the issue is here>
can some one please help me out with this?
I have always found it best to keep my main javascript/jquery code within the head tag and use php to check and set variables that allow my scripts to run; echoing a javascript boolean into my JS block using php. This way you know that the javascript is doing what it should natively and not worry about elements not being treated properly in the DOM.
So I would do this (I don't know the order in which you want things to happen so this might seem out of order but the principle should still be the same):
<?php
if( isset($_POST['submit2'])){
$varSet = "var set2 = 1;";
} else {
$varSet = "var set2 = 0;";
}
?>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type=\"text/javascript\">
$(document).ready(function(){
<?php echo $varSet; ?>
if(set2 == 1){
setTimeout(function () {
doWork();
window.location.reload();
}, 2000);
function doWork() {
$('#submit').trigger('click');
}
}
});
</script>
</head>

Is it possible to insert php variables into your js code? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
passing variables from php to javascript
I'm dynamically generating a list. I want to make each row hover on mouseover and clickable to a link. I want the link to pass the id of the content of the row.
Basically:
foreach ($courses as $cid=>cinfo){
$univ = $cinfo['univ'];
$desc = $cinfo['desc'];
$size = $cinfo['size'];
$start = $cinfo['start'];
print "<div class='rc_desc' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
}
<script>
$(function ()
{
$('#rc_desc$cid').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc$cid').click(function ()
{
$(location).attr('href','student.php?$cid');
});
});
</script>
The issue is in the js/jquery. I want to be able to grab the $cid and pass it to the student.php page upon click. The php code above works but the js won't of course. I know the fundamental of client-side vs server-side languages. This question doesn't warrant a lecture. I know I cannot do this exactly, but it is what I want to happen ultimately. Any thoughts on how I can achieve this simply? Thanks in advance my friends!
Yes, if you include the <script> section in your PHP code, you can do something similar to the following:
<script>
var foo = <?php echo $foo; ?>;
</script>
In your case, you would be looking into the following code structure:
<script>
$(function () {
$('#rc_desc<?php echo $cid ?>').hover(function () {
$(this).toggleClass('.tr');
});
$('#rc_desc<?php echo $cid ?>').click(function () {
$(location).attr('href', 'student.php?<?php echo $cid ?>');
});
});
</script>
The reason why this is possible is because although the Javascript is run on the client-side, it's processed on the server-side first prior to being presented on the page. Thus, it'll replace all necessary instances of $cid with the one you have included.
Enjoy and good luck!
EDIT:
<script>
$(function () {
$('.rc_desc').hover(function () {
$(this).toggleClass('.tr ');
});
$('.rc_desc').click(function () {
$(location).attr('href', 'student.php?' + $(this).attr('id').split('rc_desc')[1]);
});
});
</script>
You can do it like this :
$(location).attr('href','<?php echo $cid ?>');
The javascript code doesn't know it comes from php, it appears as a constant (a literal) for it.
Yes it is possible. All you have to do is put your <?PHP echo $cid; ?> in where you need it
<script>
$(function ()
{
$('#rc_desc<?PHP echo $cid; ?>').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc$cid').click(function ()
{
$(location).attr('href','student.php?<?PHP echo $cid; ?>');
});
});
This is possible because by the time the scrip is put into the page the cid has already been replaced by the string on the server. Since PHP is server driven, before it spits back the html/script it will be just like you put it in yourself.
There is almost no way to actually communicate PHP and JavaScript. However, the best and simplest way is to set the ID within an attribute. The new HTML5 data attributes would be perfect.
For example, have a anchor tag with
<span data-id="22">some event</a>
and then:
$(this).attr('href','student.php?'+$(this).attr('data-id'));
Or just use
<?php echo $id; ?>
if it is not external JS file
Try this code
foreach ($courses as $cid=>cinfo){
$univ = $cinfo['univ'];
$desc = $cinfo['desc'];
$size = $cinfo['size'];
$start = $cinfo['start'];
print "<div class='rc_desc' data-id='$cid' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
}
<script>
$(function ()
{
$('#rc_desc$cid').hover(function ()
{
$(this).toggleClass('.tr');
});
$('.rc_desc').click(function ()
{
$(location).attr('href','student.php?' + $(this).attr("data-id"));
// if you want to redirect the page do this
// window.location.href = 'student.php?' + $(this).attr("data-id");
});
});
</script>
I think you block should be :
<script>
$(function ()
{
<?php foreach($courses as $cid=>cinfo) : ?>
$('#rc_desc<?php echo $cid; ?>').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc<?php echo $cid; ?>').click(function ()
{
$(location).attr('href','student.php?<?php echo $cid; ?>');
});
";?>
<?php endforeach; ?>
});
</script>
UPDATE
But you don't really need to do this, you have
"<div class='rc_desc' data-id='$cid' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
You can try this
$(function (){
$('.rc_desc').hover(function ()
{
$(this).toggleClass('.tr');
});
$('.rc_desc').click(function ()
{
attrId = $(this).attr("data-id");
$(location).attr('href','student.php?'+id);
});
});

New to jQuery - why isn't this simple function working?

I'm building a web application inside CodeIgniter and I've decided to have a fiddle with jQuery and Javascript - something I've never really used before.
I have included jQuery in my header using Google Libraries:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
And now I'm fiddling with the SIMPLEST of jQuery but it's not working.
<p><?php if ($post->love) { echo $post->love; } else { echo 0; } ?></p>
<script type="text/javascript">
$("#lovecounter").click(function() {
alert("Click");
});
</script>
I am clicking on the lovecounter link but there is no alert. If I add simple javascript to the actual anchor tag it works though.
<p><?php if ($post->love) { echo $post->love; } else { echo 0; } ?></p>
Any ideas? What am I doing wrong?
Wrap your code in ready handler:
$(document).ready(function(){
$("#lovecounter").click(function() {
alert("Click");
});
});
Working Example
This works perfectly fine for me:
<p>asdf</p>
<script type="text/javascript">
$(document).ready(function() {
$("#lovecounter").click(function() {
alert("Click");
});
});
</script>
You should include a $(document).ready(function() {}); just like Sarfraz said. Otherwise, it would not find anything with an id of lovecounter because nothing on the page has loaded yet. If you wait for it to load, then it will find the element. Here is some documentation: http://www.w3schools.com/jquery/event_ready.asp. Here is a full jQuery lesson: http://www.codecademy.com/tracks/jquery.

javascript within php loop

Is it possible to run javascript code within a php loop?
the javascript works perfect the problem is that it is currently not executing more than once.
while(...) {
$l=$l+1;
$linha="#x".$l;
$linha2="x".$l;
?>
<script type="text/javascript">
$(document).ready(function () {
var mensagem = "<?= $mensagem ?>";
var id= "<?= $linha ?>";
var nextMsgOptions = {
msg: mensagem,
side: "bottomMiddle",
CSSClass: "nextMsg-LightTheme",}
$(id).click(function(){
$(id).nextMsg(nextMsgOptions);
});
});
</script>
}
any ideas? ;)
Yes you can output javascript within a PHP loop, to be executed by the browser, when the page loads.
The problem here is that you've got tons of variables colliding. You need to encapsulate each output of that script tag in order to keep that from happening. Here's one suggestion:
<script type="text/javascript">
<?php while(...): $l++; $linha = "#x" . $l; $linha2 = "x" . $l; ?>
(function($)
{
var mensagem = "<?= $mensagem; ?>",
id = "<?= $linha; ?>",
nextMsgOptions = {
msg: mensagem,
side: "bottomMiddle",
CSSClass: "nextMsg-LightTheme"
};
$(document).ready(function() {
$(id).click(function(){
$(id).nextMsg(nextMsgOptions);
});
});
})(jQuery);
<? endwhile; ?>
</script>
This keeps each $linha and $mensagem variable scoped away from each other for each iteration of the loop. What I think is/was happening is in your old code, you'd set $linha to some variable, and output id = <?= $linha; ?> however many times your loop executed. When $(document).ready() executed for each output, $linha had already been interpreted to be the last value that you loop output. This caused document.ready to attach an event N times (N = number of iterations of your while loop) to the same DOM element (whichever the last iteration of your while loop output $linha to be). With the above snippet, it keeps each id and $linha variable scoped away and private from each other, so you shouldn't have to worry about collisions.
I realize that explanation is kind of convoluted and might be hard to grok; but javascript interpretation/execution/scoping has special rules that aren't incredibly simple to convey without examples.
Yes you can:
<? while(...) { ?>
<script type="javascript">
// Here is you're js code
</script>
<? } ?>
it's be very hard to add in each container php tags.

Categories