Caro_deb
Caro_deb

Reputation: 279

Variable doesn't get passed to Ajax call : undefined variable

I've edited this question from the original OP to better represent my issue.

How can I pass the variable data-uid with AJAX ?

Right now the variable doesnt get passed.

var uid = $(this).data("uid"); doesn't work = undefined

var uid = '199'; gets passed. works.

is it possible to have something like : var uid = $uid; ?

HTML

 <form>
  <fieldset>
  <textarea id="post_form" type="text" data-uid="<?php echo $uid ?>"/></textarea>
  <button type="submit" id="add" value="Update" name="submit" />OK</button>
  </fieldset>
 </form>

JS

$(function() {
$("#add").click(function() {
    var boxval = $("#post_form").val();
    var uid = $(this).data("uid");  // this needs to be changed
    var dataString = 'post_form=' + boxval + '&uid=' + uid;
    if (boxval == '') {
        return false;
    } else {
        $.ajax({
            type: "POST",

        $.ajax({
            type: "POST",
            url: "add.php",
            data: dataString,
            cache: false,

            success: function(html) {
            parent.html(html);
            }
        });
        return false;
    });
});

Upvotes: 0

Views: 661

Answers (2)

Iłya Bursov
Iłya Bursov

Reputation: 24229

problem in your code in:

var uid = $(this).data("uid");

you're trying to wrap this into jquery object, but it is button object in this context, then you're trying to obtain something unassigned from it

you shoud use:

var uid = $('#post_form').attr('data-uid');

or, you can add <input type="hidden" name=... value=... and get id from it, this is more general way

Upvotes: 1

McRui
McRui

Reputation: 1955

Looks like your issue is with the data attribute that should be data-uid="somevalue" <a href="#" class="like" id="1234" data-uid="7687687">Like</a>.

Check this fiddle to see if this solves your main problem

Upvotes: 1

Related Questions