How to pass PHP variable (from loop process) to Jquery - php

i have a while loop in my coding
while (($i < $num3b)&&($i < ($start+$perpage))) {
$tododetail_id=mysql_result($result3b,$i,"tododetail_id");
$comment=formatUrlsInText(mysql_result($result3b,$i,"comment"));
$staff_name=mysql_result($result3b,$i,"staff_name");
echo "<tr><td><span><font color='#5858FA'>" . $staff_name . nl2br($comment) . "</font>
<span style='float:right' id='create-user'>Reply Message</span>";
$i++;}
How can onclick "Reply Message" jquery will popup $staff_name and $comment accordingly.
This is my jquery code
$( '[id^="create-user"]')
.click(function() {
var nameStf = $(this).data('id');
alert (nameStf);
$( "#dialog-form" ).dialog( "open" );
});
Thanks

You could use the data-attributes
HTML
<span style='float:right' class="reply" data-staffname="staffname" data-comment="staff comment">Reply Message</span>
jQuery
$(document).ready(function() {
$('span.reply').click(function() {
var staffname = $(this).data('staffname');
var comment = $(this).data('comment');
alert(staffname + ': ' + comment);
});
});

When you echo tags, I can't see you are closing them anywhere. Your HTML must be correct in order for jQuery to work properly. Also ID must be unique so use class.
HTML
<tr>
<td>
<span style="color: #5858FA;">SOMETHING 2</span>
<span class="create-user">Reply Message</span>
</td>
</tr>
JS
$('.create-user').click(function(){
var $text = $(this).prev().text();
alert($text);
});
DEMO

Your HTML is a mess, and your jQuery doesn’t correspond with it. You have this line:
$( "#dialog-form" ).dialog( "open" );
But you haven’t shown us any HTML that includes an element with the ID dialog-form.
You should restructure your HTML so you don’t use the font tag, every ID is unique, and tags are properly nested and closed. Run your output HTML through the validator if you’re not sure.
Then, you can do something like this:
$('span').click(function(){
alert($(this).closest('.comment'));
});
Obviously you’ll have to put the comment data in an element with the class comment.
Also, if you want to select an element by its ID with jQuery:
// Incorrect
$('[id^="create-user"]')
// Correct
var $createUser = $('#create-user');
// Also correct (normal JavaScript)
var createUser = document.getElementById('create-user');

id must be unique give it as something like the id from the database. Then put the jquery script inside the loop. or else in the html use a onclick function which passes the id to the JavaScript function.
<?php
echo "<tr><td><span><font color='#5858FA'>" . $staff_name . nl2br($comment) . "</font>
<span style='float:right' id="<?php echo $row['id'];">Reply Message</span>";
$i++;
?>
<script type="text/javascript">
$( "#<?php echo $row['id']; ?>")
.click(function() {
var nameStf = $(this).data('id');
alert (nameStf);
$( "#dialog-form" ).dialog( "open" );
});
</script>
<?php }?>
Try not to use html inside an echo statement since echo is a php statement which loads from the server which is slower than normal html which loads in the browser.

Related

Display a loop of div's with a href click me button to display the text in that div

I have a bit of an issue. I am trying to do a while loop in a database which will load information about each person. In the field I want it to load a contact form but hide it on initial load. I have this working My problem is when I go to click the button it displays all the Div's when I only want it to display that div the button was clicked on. Below is just a simple example
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<?php
$x = 1;
while($x <= 5) {
echo '<div class ="Test_name">Hello World</div> <br>
<a href = "#" class = "Click_ME" > Click to show</a>';
$x++;
}
?>
<script>
$( document ).ready(function() {
$( ".Test_name" ).hide();
$('.Click_ME').html('TEST');
$( ".Click_ME" ).click(function() {
$( ".Test_name" ).show();
});
});
</script>
The jquery selector should be point to the respective div on click of button.
Inside click event using $(".Click_ME").index(this) we can able to find index of clicked button's index and using it div can show using $( ".Test_name" ).eq($(".Click_ME").index(this)).show();.
Please check below snippet.
$( document ).ready(function() {
$( ".Test_name" ).hide();
$( ".Click_ME" ).on('click',function() {
//$(".Click_ME").index(this) will find the index of clicked button and based on that index div can show/hide.
$( ".Test_name" ).eq($(".Click_ME").index(this)).show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class ="Test_name">Hello World</div> <br>
<a href = "#" class = "Click_ME" > Click to show</a>
<br/>
<br/>
<div class ="Test_name">Hello World</div> <br>
<a href = "#" class = "Click_ME" > Click to show</a>
folow this simple steps.
In the div include the style display:none
<div style='display:none'>
// you all php data here
</div>
on click remove the style
$( ".Click_ME" ).click(function() {
$(".Test_name").css('display','block');
});
replace $( ".Test_name" ).show(); with $(this).prevAll('.Test_name').first();

jquery aren't working on the url that i load in div(.load)

Let's say that in a document I have a div and a button that will show the div:
<div id="dvExternal" style="display: none;">
</div>
<button type="button" id="btnShow">
<span>Show</span>
</button>
and a jquery that commands it to show:
$("#btnShow").click(function(){
$("#dvExternal").css("display","block");
$("#dvExternal").load("whattheitsnotworking.php");
});
and that page contains jquery functions, php, iframe etc.
The problem is when it loads on the div the jquery on that page isn't working.
Thanks in advance :)
The page that I was trying to load in the div contains(for example):
<script type="text/javascript">
$(document).ready(function(e)){
$("#inputDate").val("<?php echo date("Y"); ?>");
});
</script>
This script doesn't load or work.
Try to use live function of jquery, it will help you...
$("#btnShow").live("click",function(){
$("#dvExternal").css("display","block");
$("#dvExternal").load("whattheitsnotworking.php");
});
Make sure you have
<script src="http://code.jquery.com/jquery-1.10.0.min.js">
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js">
in the parent page head
I have it working # http://www.damienkeitel.com/pr.php
<script type="text/javascript">
$( document ).ready( function( e )){
$( "#inputDate" ).val( "<?php echo date('Y'); ?>" );
}
</script>
should be
<script type="text/javascript">
$( document ).ready( function( e ){
$( "#inputDate" ).val();
});
</script>
jQuery .val() is only to get a value of an element.
To set a value you can use this method.
$( "#inputDate" ).attr( "value", "<?php echo date('Y'); ?>" );
you had one to many ) after function(e) and also didnt close off the function with );

Ajax update css of HTML elements

I want display and hide HTML div with ajax,
Situation:
progressbar('on');
very_long_function();
progressbar('off');
I want display div when working very_long_function(); , bUt when finish working I want hide div
Progress bar function:
function progressbar($status){
if($status == "on"){
echo "
<script>
$(document).ready(function() { function() {
$('#load').css('display','inline');
});
</script>
";
}
else{
echo "
<script>
$$(document).ready(function() { function() {
$('#load').css('display','none');
});
</script>
";
}
}
Problem is that div not showing when very_long_function(); working, maybe is possible to solve this priblem with AJAX or jQuery
HTML
<div id="load" style="display: none;"><img src="loading_baras.gif" style="width: 550px; height: 10px; margin-top: -10px"></div>
I think, that you architecture is wrong. You have to user JS for it.
Like next:
$(function(){
$('#load').css('display','inline');
$.post('/very_long_function.php', {url: 'http://www.google.com'}, function(result){
alert(result);
$('#load').css('display','none');
});
});
PHP: very_long_function.php
$url = $_POST['url'];
$result = very_long_function($url);
echo $result;
die;
Are sure that you included jquery lib for using it . Also there is no double $$ in jquery.
Please give the html and after we will correct it.

How can i use ajax with javascript function

I am very new with Ajax.
i am using the following javascript function to get the value from the list those user select the li.
but using this function each time the page is reloading. i am trying to use ajax using this function.how can i use ajax with this need syntax.
My function:
<script type="text/javascript" language="javascript">
function pagelim(index)
{
var page_lim=$('#page_num li').get(index).id;
self.location="<?php echo get_option('head'); ?>"+'?details&limit=' + page_lim ;
}
</script>
<script type="text/javascript" language="javascript">
function dateby(index)
{
var date_by=$('#sort-by-date a').get(index).id;
var cls=document.getElementById(date_by).className;
if(date_by=="ASC")
{
date_by="DESC";
}
else
{
date_by="ASC";
}
self.location="<?php echo get_option('head'); ?>"+'?details&sort=' + date_by ;
}
</script>
Value get from list:
<div class="sort-links">
<span class="by-date" id="sort-by-date">Sort by: <a href="#" id='<?php _e($sort_by)?>' class='<?php _e($class)?>' onclick="dateby($(this).index())" >Date</a>
</span>
//list to select value
<span id="view-on-page">View on Page: <?php if($lim=="") { _e($limit); } else { _e($lim); } ?>
<ul id="page_num">
<li id="5" onclick="pagelim($(this).index())">5</li>
<li id="10" onclick="pagelim($(this).index())">10</li>
<li id="15" onclick="pagelim($(this).index())">15</li>
</ul>
</span>
</div>
Welcome to the wonderful world of functional programming.
I'm assuming you are doing a "get" request based on "index" which is a url? If that's the case, then you need to provide a callback.
$('#page_num li').get(index. function(id) {
var page_lim = id; // assuming that's what you sent back.
self.location="<?php echo get_option('head'); ?>"+'?details&limit=' + page_lim ;
});
Notice that you have to put everything in a function that is called after the ajax request is finished. I'm assuming that all you are sending back from the request is the id you need.
jQuery AJAX calls are asynchronous, meaning that the the function $(...).get(url, callback); returns a value BEFORE the AJAX call has finished. That callback function only happens after the AJAX call is completed. I'd advise some time spent with the jQuery API documentation.
You might also Google "javascript functional programming" and see if you can get an explanation of how JavaScript (and thus jQuery) does not always return the value you expect from functions. It's very different from other languages like PHP or ASP.NET in that regard.
Hi hope this will help you... Create a div (say "MyDiv") and put all the elements which you want to change dynamically(without page refresh)... Then try jQuery.load() method...Like
<div id = "MyDiv">
<div class="sort-links">
<span class="by-date" id="sort-by-date">Sort by: <a href="#" id='<?php _e($sort_by)?>' class='<?php _e($class)?>' onclick="dateby($(this).index())" >Date</a>
</span>
//list to select value
<span id="view-on-page">View on Page: <?php if($lim=="") { _e($limit); } else { _e($lim); } ?>
<ul id="page_num">
<li id="5" onclick="pagelim($(this).index())">5</li>
<li id="10" onclick="pagelim($(this).index())">10</li>
<li id="15" onclick="pagelim($(this).index())">15</li>
</ul>
</span>
</div>
</div> //end of MyDiv
Then change your script like
<script type="text/javascript" language="javascript">
function pagelim(index)
{
var page_lim=$('#page_num li').get(index).id;
$("#MyDiv").load("<?php echo get_option('head'); ?>"+'?details&limit=' + page_lim);
}
</script>
<script type="text/javascript" language="javascript">
function dateby(index)
{
var date_by=$('#sort-by-date a').get(index).id;
var cls=document.getElementById(date_by).className;
if(date_by=="ASC")
{
date_by="DESC";
}
else
{
date_by="ASC";
}
$("#MyDiv").load("<?php echo get_option('head'); ?>"+'?details&sort=' + date_by);
}
</script>
Please note that I havnt tested this...
Its very simple to use jQuery to perform AJAX requests... So pls refer this page
Try binding to the click event of your links. This way you can remove any inline javascript and its all neatly contained in your function.
$("li a").click(function() {
//should alert the id of the parent li element
alert($(this).parent.attr('id'));
// your ajax call
$.ajax({
type: "POST",
// post data to send to the server
data: { id: $(this).parent.attr('id') }
url: "your_url.php",
// the function that is fired once data is returned from your url
success: function(data){
// div with id="my_div" used to display data
$('#my_div').html(data);
}
});
});
This method means your list elements would look something like,
<li id="5">5</li>
This doesn't look ideal though as id="5" is ambiguous.
Try something like,
<li class="select_me">5</li>
then your click event binding can look like this,
// bind to all li elements with class select_me
$("li.select_me").click(function() {
// alert the text inside the li element
alert($(this).text());
});

jquery comment system on.(...click) issue

I'm having trouble keeping event handlers attached to future loaded selectors. For example, when pull.php is loaded, the confirmdelete is no longer hidden, and also the click event handlers no longer exist. I am new to jquery and ajax. Below is my code.
$id= (int)strip_tags($_GET['id']);
$(document).ready(function() { //make a comment delete js file eventually, just so we can reference the source
$('.confirmdeletecomment').hide();
$('.deletecomment').on("click", function(e){
var cid = $(this).attr("id");
$('a#c'+cid).show(500, function(){ //right now as call back
$(this).on("click", function(e){
var id = $(this).attr("id");
var did = id.substring(1);
$.post(
'deletecommentdata.php?cid='+did,
function(data)
{
$("#commentarea").load("pull.php?id=<? echo $id; ?>");
$("#comment").val("");
$('.confirmdeletecomment').hide();
}
)
e.preventDefault();//so it doesn't interpret is as an anchor link
});
});
e.preventDefault();//so it doesn't interpret is as an anchor link
});
});
</script>
the below script is the php part:
<div id="commentarea">
<?
$query = mysql_query("SELECT users.user_id, users.username, users.miniavatar, comments.comment_id, comments.comment, comments.time_stamp FROM users INNER JOIN comments ON users.user_id=comments.products_users_user_id WHERE comments.products_products_id = '$id' ORDER BY comments.time_stamp DESC");
while($row2 = mysql_fetch_array($query)) {
?>
<div id='singlecomment'>
<hr class="comment" />
<table>
<col width="*" />
<col width="400" />
<col width="*" />
<tr>
<td valign = "top" rowspan="2">
<img src="<? echo $row2['miniavatar']; ?>" height="52" width="52" /> <br />
<?
if ($user_id == $row2['user_id']) {
$cid = $row2['comment_id'];
echo "<a id='$cid' class='deletecomment' title='Delete Post'>X</a> &nbsp";
echo "<a id='c$cid' class='confirmdeletecomment'>confirm</a>";
}
?>
</td>
<td valign="top">
<a class="blue" href="collection.php?profile=<? echo $row2['user_id']; ?>"> <? echo $row2['username']; ?> </a>
</td>
<td>
<span class="date"><? echo date("F j, Y g:i a ", strtotime($row2['time_stamp'])); ?> </span>
</td>
<tr>
<td colspan="2">
<? echo stripslashes($row2['comment']); ?> <br/><br/>
</td>
</tr>
</table>
</div>
What you need to do is use 'on' like it's meant. Right there all you're doing is binding a .click event to that element in the selector.
What you want is:
$('body').on("click", ".deletecomment", function(e){
or something in place of 'body' that is a wrapper that can watch that level of the DOM for new elements to apply the event too.
I am guessing the event got messed up since you are the passing the event handler from
$('.deletecomment').on("click", function(e){
to
$(this).on("click", function(e){
Change the event names, if you really want to handle them separately. More like updating your second handler as these will do goo
$(this).on("click", function(event){
Since I dont have your markup structure, I am guessing, when you are loading pull.php to #commentarea, another element with class confirmdelete should have been loaded as well, thus making the code execution incomplete logically.
Put, $(".confirmdelete").hide(); right above e.preventDefault() to see if I am right.
You should look into the event delegation system http://api.jquery.com/on/
Try JQuery live. more info It should be something like the following
<script type="text/javascript">
$(document).ready(function() { //make a comment delete js file eventually, just so we can reference the source
$('.confirmdeletecomment').hide();
$('.deletecomment').live("click", function(){
var cid = $(this).attr("id");
$('a#c'+cid).show(500, function(){ //right now as call back
$(this).on("click", "a", function(e){
var id = $(this).attr("id");
var did = id.substring(1);
$.post(
'deletecommentdata.php?cid='+did,
function(data)
{
$("#commentarea").load("pull.php?id=<? echo $id; ?>");
$("#comment").val("");
$('.confirmdeletecomment').hide();
}
)
e.preventDefault();//so it doesn't interpret is as an anchor link
});
});
e.preventDefault();//so it doesn't interpret is as an anchor link
});
});
</script>

Categories