0

I am doing a rating application in php,here I want to write a for loop inside a jQuery ajax function call.I dont know how the correct syntax.

PHP code I used is

for(i=1;i<=4;i++)
{
<div class="like">
<a href="#" class="like" id="1" name="up"><img src="images/likebig.png"></a>
<a href="#" class="like" id="1" name="down"><img src="images/dislike.png"></a>

 <form>
 <input type="hidden" id="<?php echo $i; ?>" value="<?php echo $_SESSION['r_id'][$i]?>">
 </form>
}
</div>

The above code gives four results.Here I want to get the value ($_SESSION['r_id'][$i]) of each result on the click of their corresponding click

The jQuery function I used is

<script type="text/javascript">

    $(document).ready(function()
    {
    $(".like").click(function(e)
    {
    e.preventDefault();
    var id=$(this).attr("id");
    var name=$(this).attr("name");
    var fname = $("#fname").val();
    var lname = $("#lname").val();
    var email = $("#email").val();
    for(var i=1;i<=4;i++)
    {
    var rel[i] = $("#i").val();
    }
    var dataString = 'id='+ id + '&name='+ name + '&fname='+ fname + '&lname='+ lname + '&email='+ email;
     $.ajax
      ({
      type: "POST",
      url: "rate.php",
      data: dataString,
      cache: false,
      });
     });
    });
</script>
1
  • Shouldn't this for(i=1;i<=4;i++) be for($i=1;$i<=4;$i++)? Commented Jul 4, 2012 at 4:53

1 Answer 1

1

change this

var rel[i] = $("#i").val();

to:

var rel[i] = $("#" + i).val();

alternatively you can use .serialize() method:

The .serialize() method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements. The form elements can be of several types:

$.ajax({
   type: "POST",
   url: "rate.php",
   data: $('form').serialize(),
   cache: false,
 });
Sign up to request clarification or add additional context in comments.

6 Comments

sorry but how did this answer the for-loop "question"?
@tradyblix his for loop syntax is correct i think he wants $("#" + i) instead of $("#i").
@undefined Hi friend Thnks for your answer.But when I tried to alert the value it shows error "missing ; before statement" in firebug error console
@undefined Hi.I changed the line [var rel[i] = $("#i").val();] to [var rel[i] = $("#" + i).val();] and tried to alert the value rel[1].
@Balu define the rel[] array outside of the for loop in each iteration you are defining it again and again. do you have form elements by id #2 #3 ... ? if no, the array values will be undefined.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.