Hi all..

basically i want an ajax code that retrieve the data from the unique div(with php)..
what i mean by unique here is that my div got the id with the name+(the php code to make it unique).

okay i dont really know how to explain but here is my ajax code :

<script type="text/javascript">
$(document).ready(function(){
	$("form#post_reply").submit(function() {
 
	var discuss_text = $('#discuss_text').attr('value');
	var test5 = $('#test5').attr('value');
	
		$.ajax({
			do something....
			}
		});	
	return false;
	});	
});
</script>

and this is the html part which contain the div that i meant :

<ul id="wall">
                     <?php
                     include('insert.php');
                     $test=mysql_query("SELECT*FROM wall ORDER BY id DESC");
                     while($row=mysql_fetch_array($test)){
                     	$rel_id=$row['id'];
                     ?>     
                     <li class='stbody'>
                     	<div class='stimg'>
                        </div>

                        <div class='sttext'>
<span class='poster'>Name</span><span class='flag_bad'><a href="#">X Flag as bad post</a></span><br/>
                           <?php echo $row["message"];?>
                           <div class='below'>
                                   <div class='sttime'>a few seconds ago</div>
                                   <div class='help-toggle'>| Helpful |</div>

                               </div>

    <div class='trigger_default'><a href='#'>Discuss</a>
    </div>
     <div class='toggle_container_default'>
                                  <ul class="reply_text">
                                      <?php include('get_reply.php');?>
                                  </ul>
                               <div class='block'>
             <form name='disscuss_text' id='post_reply' id='post_reply'>
       <input type="hidden" name="test5" id="test5" value="<?php echo $row['id']; ?>">
        <textarea id='discuss_text' name='discuss_text'></textarea>
        <input type='submit' value='Post' name='Help' id='post-button' />
              </form>
                               </div>
		           </div>
	               </div>
	           </li>
                   <?php 
                   }
                   ?>
               </ul>
    </div>

So i got the above code and what i want to do is :

replace this HTML code :

<textarea id='discuss_text' name='discuss_text'></textarea>

with this :

<textarea id='discuss_text_<?php echo $row; ?>' name='discuss_text'></textarea>


and replace this ajx code which is:

var discuss_text = $('#discuss_text').attr('value');

with this :

var discuss_text = $('#discuss_text_<?php echo $row; ?>').attr('value');


When i tried to replace them, i cannot achive what i want to do..If you could understand what i am trying to do, could you give me the solution please??

I really hope that someone could help me out because there has been a week or two i have been thinking about this solution :(

Just curious...

Did you put var discuss_text = $('#discuss_text_<?php echo $row['id']; ?>').attr('value'); directly into the <script> section of the document or did you do this

<?php
  include('insert.php');
  $test=mysql_query("SELECT*FROM wall ORDER BY id DESC");
  while($row=mysql_fetch_array($test)){
     echo "<textarea id='discuss_text_{$row['id']}' name='discuss_text'></textarea>";
  }
?>

Cos you need to put in the $row from somewhere or else you will just get a blank. Check out your source code of the HTML file and see.

Hi,

Make the textarea field like sudeepjd said,

<textarea id='discuss_text_<?=$<?php echo $row['id']; ?>' name='discuss_text'></textarea>

and using jquery you can get the dynamic ids using this,

$(document).ready(function(){
	$("form#post_reply").submit(function() {
 	
	$("textarea[id^='discuss_text_']").each(function() {
	  var discuss_id = parseInt(this.id.replace("discuss_text_", ""));
	  var diszuss_id_value = $('#discuss_text_'+id).attr('value');
  	});
 	
	return false;
	});	
});

Just curious...

Did you put var discuss_text = $('#discuss_text_<?php echo $row['id']; ?>').attr('value'); directly into the <script> section of the document or did you do this

<?php
  include('insert.php');
  $test=mysql_query("SELECT*FROM wall ORDER BY id DESC");
  while($row=mysql_fetch_array($test)){
     echo "<textarea id='discuss_text_{$row['id']}' name='discuss_text'></textarea>";
  }
?>

Cos you need to put in the $row from somewhere or else you will just get a blank. Check out your source code of the HTML file and see.

I put

var discuss_text = $('#discuss_text_<?php echo $row['id']; ?>').attr('value');

directly into the <script> section..

Oops.. sorry, I missed out what I wanted to say in my previous post... I'm not very good at JQuery I prefer using Mootools as my JavaScript Library of Choice.

If I would have to do it in Mootools, I would create a class for every textarea and then call each of the textareas using the class and get their ID's that way. I believe PaulRajj has given the same implementation in JQuery.

If you were to do this without a library help. I would put the loop in the <script> tag.

<script type="text/javascript">
$(document).ready(function(){
	$("form#post_reply").submit(function() {
    
	var discuss_text = new Array();
	<?php
	  include('insert.php');
	  $test=mysql_query("SELECT*FROM wall ORDER BY id DESC");
	  $i=0;
	  while($row=mysql_fetch_array($test)){
	     echo "discuss_text[$i]=$('#discuss_text_{$row['id']}').attr('value');";
	     $i++;
	  }
	?>	
	
	var test5 = $('#test5').attr('value');
	
		$.ajax({
			do something....
			}
		});	
	return false;
	});	
});
</script>

This would create an array with the data which you can use later.

Oops.. sorry, I missed out what I wanted to say in my previous post... I'm not very good at JQuery I prefer using Mootools as my JavaScript Library of Choice.

If I would have to do it in Mootools, I would create a class for every textarea and then call each of the textareas using the class and get their ID's that way. I believe PaulRajj has given the same implementation in JQuery.

If you were to do this without a library help. I would put the loop in the <script> tag.

<script type="text/javascript">
$(document).ready(function(){
	$("form#post_reply").submit(function() {
    
	var discuss_text = new Array();
	<?php
	  include('insert.php');
	  $test=mysql_query("SELECT*FROM wall ORDER BY id DESC");
	  $i=0;
	  while($row=mysql_fetch_array($test)){
	     echo "discuss_text[$i]=$('#discuss_text_{$row['id']}').attr('value');";
	     $i++;
	  }
	?>	
	
	var test5 = $('#test5').attr('value');
	
		$.ajax({
			do something....
			}
		});	
	return false;
	});	
});
</script>

This would create an array with the data which you can use later.

But how about if my ajax code is actually this :

$.ajax({
type: "POST",
url: "reply.php",
data: "discuss_text="+ discuss_text +"&test5="+ test5 ,
success: function(){
$("ul.reply_text").prepend("<li style='display:none' class='reply_stbody'><div class='stimg_replier'></div><div class='sttext_reply'><span class='replier'>Name</span><br/>"+discuss_text+
"<div class='below'><div class='sttime'>2 seconds ago</div><div class='help-toggle'>| Helpful |</div><div class='help-toggle'>Unhelpful |</div></div></div></li>");
$("ul.reply_text li:first").fadeIn();

}
});

Then how do i want the +discuss_text+ to be uniquely i dentified?
Could i just modified your loop or what??

Samson,

I think I understand.

You have a set of little forms running down the page. These forms are identical in function but not content. Each form is to be submitted by ajax (not regular HTML form submission). On successful completion of the ajax, an <li> element is to be inserted into a specific container related to the submitted form (but not inside the form). The inserted <li> element is initially hidden but should fade-in immediately.

By writing the javascript correctly, it is not necessary to build any statements with php - all the code is fixed.

Because of the repeating nature of your forms, it's easier to find all the necessary DOM elements relative to the form rather than use ids. jQuery makes this easy.

Here's the javascript (untested) :

$(document).ready(function(){
	$("form.post_reply").submit(function() {
		$this = $(this);//a jquery object for the particular form that is being submitted
		var discuss_text = $this.find('[name=discuss_text]').val();//current discuss_text value, in this form
		var $form_container = $this.closest('.toggle_container_default');//the closest ancestor (div) element that is common to both the form and its corresponding "reply_text" list.
		var $reply_text = $form_container.find('ul.reply_text');//a jquery object for the corresponding "reply_text" list

		var $submit_button = $this.find('input:submit');
		var $submit_button.attr('disabled', true);//disable submit button to prevent user clicking it again

		$.ajax({
			type: "POST",
			url: "reply.php",
			data: $this.serialize(),//easier than building the string manually.
			success: function(){
				$reply_text.prepend("<li style='display:none' class='reply_stbody'><div class='stimg_replier'></div><div class='sttext_reply'><span class='replier'>Name</span><br/>" + discuss_text + "<div class='below'><div class='sttime'>2 seconds ago</div><div class='help-toggle'>| Helpful |</div><div class='help-toggle'>Unhelpful |</div></div></div></li>");
				$reply_text.find('li').eq(0).fadeIn();//should find, and fadeIn the li that was just added.
				$this.val('');//empty the textarea
			},
			error: function(){
				//you should display something to advise the user if ajax fails.
			},
			complete: function(){
				$submit_button.attr('disabled', false);//enable submit button.
			}
		});
		return false;
	});
});

And the corresponding HTML (fragment):

...
      <div class='toggle_container_default'>
        <ul class="reply_text">
<?php
	include('get_reply.php');
?>
        </ul>
        <div class='block'>
          <form name='disscuss_text' class='post_reply'>
            <input type="hidden" name="test5" value="<?php echo $row['id']; ?>">
            <textarea name='discuss_text'></textarea>
            <input type='submit' value='Post' name='Help' />
          </form>
        </div>
      </div>
...

Plenty of comments in the javascript to help you understand.

Airshow

Even better is to arrange for the reply.php to return the discuss_text and to modify the success funtion slightly:

success: function(discuss_text){
	$reply_text.prepend("<li style='display:none' class='reply_stbody'><div class='stimg_replier'></div><div class='sttext_reply'><span class='replier'>Name</span><br/>" + discuss_text + "<div class='below'><div class='sttime'>2 seconds ago</div><div class='help-toggle'>| Helpful |</div><div class='help-toggle'>Unhelpful |</div></div></div></li>");
	$reply_text.find('li').eq(0).fadeIn();//should find, and fadeIn the li that was just added.
	$this.val('');//empty the textarea
},

This has the following advantages :

  • The line var discuss_text = $this.find can be deleted because the string does not need to be held in the closure created by ....submit(function(){...} .
  • Any naughty-word sensoring performed by reply.php is immediately reflected in the displayed text.

Airshow

Samson,

I think I understand.

You have a set of little forms running down the page. These forms are identical in function but not content. Each form is to be submitted by ajax (not regular HTML form submission). On successful completion of the ajax, an <li> element is to be inserted into a specific container related to the submitted form (but not inside the form). The inserted <li> element is initially hidden but should fade-in immediately.

By writing the javascript correctly, it is not necessary to build any statements with php - all the code is fixed.

Because of the repeating nature of your forms, it's easier to find all the necessary DOM elements relative to the form rather than use ids. jQuery makes this easy.

Here's the javascript (untested) :

$(document).ready(function(){
	$("form.post_reply").submit(function() {
		$this = $(this);//a jquery object for the particular form that is being submitted
		var discuss_text = $this.find('[name=discuss_text]').val();//current discuss_text value, in this form
		var $form_container = $this.closest('.toggle_container_default');//the closest ancestor (div) element that is common to both the form and its corresponding "reply_text" list.
		var $reply_text = $form_container.find('ul.reply_text');//a jquery object for the corresponding "reply_text" list

		var $submit_button = $this.find('input:submit');
		var $submit_button.attr('disabled', true);//disable submit button to prevent user clicking it again

		$.ajax({
			type: "POST",
			url: "reply.php",
			data: $this.serialize(),//easier than building the string manually.
			success: function(){
				$reply_text.prepend("<li style='display:none' class='reply_stbody'><div class='stimg_replier'></div><div class='sttext_reply'><span class='replier'>Name</span><br/>" + discuss_text + "<div class='below'><div class='sttime'>2 seconds ago</div><div class='help-toggle'>| Helpful |</div><div class='help-toggle'>Unhelpful |</div></div></div></li>");
				$reply_text.find('li').eq(0).fadeIn();//should find, and fadeIn the li that was just added.
				$this.val('');//empty the textarea
			},
			error: function(){
				//you should display something to advise the user if ajax fails.
			},
			complete: function(){
				$submit_button.attr('disabled', false);//enable submit button.
			}
		});
		return false;
	});
});

And the corresponding HTML (fragment):

...
      <div class='toggle_container_default'>
        <ul class="reply_text">
<?php
	include('get_reply.php');
?>
        </ul>
        <div class='block'>
          <form name='disscuss_text' class='post_reply'>
            <input type="hidden" name="test5" value="<?php echo $row['id']; ?>">
            <textarea name='discuss_text'></textarea>
            <input type='submit' value='Post' name='Help' />
          </form>
        </div>
      </div>
...

Plenty of comments in the javascript to help you understand.

Airshow

First of all thank you so much for such a nice reply :D
I've tried to understand the codes u given me, but it is not working.

I also tried to find any syntax error or something, but unfortunately i couldnt found one..

So either theres really something wrong with the part of code you have given or there is the conflict with my whole index.php file,i dont know..

But could it possible the is actually with this code ? :

success: function(discuss_text){
$reply_text.prepend("<li style='display:none' class='reply_stbody'><div class='stimg_replier'></div><div class='sttext_reply'><span class='replier'>Name</span><br/>" + discuss_text + "<div class='below'><div class='sttime'>2 seconds ago</div><div class='help-toggle'>| Helpful |</div><div class='help-toggle'>Unhelpful |</div></div></div></li>");
	$reply_text.find('li').eq(0).fadeIn();//should find, and fadeIn the li that was just added.
	$this.val('');//empty the textarea
},

i ask u that,because there was a few times before ,where i need to arrange
that code in a several way(eliminating white spaces between the div and span and so on) so that it will work..Could it be?
Anyway, even if it is not the problem, is there any way around i could rearrange that code so that it will be more organize?

Thank you for helping :)

Samson,

Use this version until you have modified your reply.php to return discuss_text

success: function(){
...
},

Make sure you have made the necessary changes to the HTML. White may affect layout but not functionality.

If it still doesn't work then you need to debug the javascript. You can do this even if you don't understand every line.

Look at the error console (FF) or turn on error messages (IE). If there are errors, at what line number(s) do they occur?

If it doesn't work but also doesn't generate any errors then insert alerts to track progress and inspect the data.

Airshow

Correction: "White spance may affect layout but not functionality."

Samson,

Use this version until you have modified your reply.php to return discuss_text

success: function(){
...
},

Make sure you have made the necessary changes to the HTML. White may affect layout but not functionality.

If it still doesn't work then you need to debug the javascript. You can do this even if you don't understand every line.

Look at the error console (FF) or turn on error messages (IE). If there are errors, at what line number(s) do they occur?

If it doesn't work but also doesn't generate any errors then insert alerts to track progress and inspect the data.

Airshow

this is my code for the reply.php :

<?php
// Change this parameter with your connection's info.
$db_host="localhost";
$db_name="********";
$username="root";
$password="";
$db_con=mysql_connect($db_host,$username,$password);
$connection_string=mysql_select_db($db_name);
// Connection
mysql_connect($db_host,$username,$password);
mysql_select_db($db_name);
?>
<?php
if(isset($_POST['discuss_text'])){
	/* Connection to Database */

	/* Remove HTML tag to prevent query injection */
	$message = strip_tags($_POST['discuss_text']);
	$test5 = $_POST['test5'];
	
	$sql	='INSERT INTO reply (message,post_id) VALUES("'.$message.'","'.$test5.'")';

	mysql_query($sql);
	
	echo $message;
	} else { }
?>

i dont know how should i modify this to return the discuss_text as u said..
i think i've done it already, didnt i?

Yes, echo $message; is good. echo $message; exit(); would be better.

If it's still not working, it must be something else. Try the debug techniques I explained earlier.

Airshow

Samson,

Correction.

Replace :

var $submit_button.attr('disabled', true);//disable submit button to prevent user clicking it again

with :

$submit_button.attr('disabled', true);//disable submit button to prevent user clicking it again

Airshow

If it still doesn't work , then try this version:

$(document).ready(function(){
	$("form.post_reply").submit(function() {
		$this = $(this);//a jquery object for the particular form that is being submitted
		//var discuss_text = $this.find('[name=discuss_text]').val();
		var $reply_text = $this.closest('.toggle_container_default').find('ul.reply_text');//a jquery object for the form's corresponding "reply_text" list
		var $submit_button = $this.find('input:submit');
		$submit_button.attr('disabled', true);//disable submit button to prevent user clicking it again
		var li_template = '<li style="display:none" class="reply_stbody"><div class="stimg_replier"></div><div class="sttext_reply"><span class="replier">Name</span><br/>%s<div class="below"><div class="sttime">2 seconds ago</div><div class="help-toggle">| Helpful |</div><div class="help-toggle">Unhelpful |</div></div></div></li>';
		$.ajax({
			type: "POST",
			url: "reply.php",
			data: $this.serialize(),//easier than building the string manually.
			success: function(discuss_text){
				$(li_template.replace('%s',discuss_text)).prependTo($reply_text).fadeIn();//insert, then fadeIn a new li element and its contents.
				$this.val('');//empty the textarea
			},
			error: function(){
				//you should display something to advise the user if ajax fails.
			},
			complete: function(){
				$submit_button.attr('disabled', false);//enable submit button.
			}
		});
		return false;
	});
});

Airshow

If it still doesn't work , then try this version:

$(document).ready(function(){
	$("form.post_reply").submit(function() {
		$this = $(this);//a jquery object for the particular form that is being submitted
		//var discuss_text = $this.find('[name=discuss_text]').val();
		var $reply_text = $this.closest('.toggle_container_default').find('ul.reply_text');//a jquery object for the form's corresponding "reply_text" list
		var $submit_button = $this.find('input:submit');
		$submit_button.attr('disabled', true);//disable submit button to prevent user clicking it again
		var li_template = '<li style="display:none" class="reply_stbody"><div class="stimg_replier"></div><div class="sttext_reply"><span class="replier">Name</span><br/>%s<div class="below"><div class="sttime">2 seconds ago</div><div class="help-toggle">| Helpful |</div><div class="help-toggle">Unhelpful |</div></div></div></li>';
		$.ajax({
			type: "POST",
			url: "reply.php",
			data: $this.serialize(),//easier than building the string manually.
			success: function(discuss_text){
				$(li_template.replace('%s',discuss_text)).prependTo($reply_text).fadeIn();//insert, then fadeIn a new li element and its contents.
				$this.val('');//empty the textarea
			},
			error: function(){
				//you should display something to advise the user if ajax fails.
			},
			complete: function(){
				$submit_button.attr('disabled', false);//enable submit button.
			}
		});
		return false;
	});
});

Airshow

WOW! i dont believe it that it works like charm!
i dont know how to say to tell that i really appreciate your help..
You've helped me a lot..Thank You!

Hope you all could help me again if i got any problem regarding this matter soon!

:)

:cool:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.