許家瑄
許家瑄

Reputation: 97

jQuery get id from element

I have a problem in Jquery. Here's part of my code in php file.

echo '<form action="add.php" method="post" id="'.$data["pro_id"].'">';
echo '<input style="display:none" type="text" name="img_link" value="'.$data["img_link"].'">';                   
echo '<input style="display:none" type="text" name="pro_url" value="'.$data["pro_url"].'">';
echo '<input style="display:none" type="text" name="pro_price" value="'.$data["pro_price"].'">';                    
echo '<input style="display:none" type="text" name="total_fb" value="'.$data["total_fb"].'">';                    
echo '<input style="display:none" type="text" name="pro_id" value="'.$data["pro_id"].'">';
echo '<input style="display:none" type="text" name="pro_name" value="'.$data["pro_name"].'">';
echo '</form>';

I need to submit the form but stay on the same page so I used the code below. It really works on not turning to other page but how can I get the ID of this form? When I output id but the result will be NoneType.

$('form').live('submit', function() {
  $.post($(this).attr('action'), $(this).serialize(), function(response) {
    var id = $(this).attr('id');
    document.write(id);
  }, 'json');
  return false;
});

Upvotes: 3

Views: 82

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You're using the right approach, but your issue is that this in the $.post() call does not refer to the element which triggered the submit event. As such you need to move that line in to the outer scope.

There's also a couple of things which need addressing here. Firstly note that live() was deprecated a long time ago. You should check what version of jQuery you're using, as it should be at least 1.12.1, or better still 3.3.1 (at time of writing), and you should be using on() instead.

Secondly you should not use document.write(). Instead you could select the element to be updated using jQuery then call html() on it. Try this:

$(document).on('submit', 'form', function(e) {
  e.preventDefault();
  var id = this.id;
  $.post(this.action, $(this).serialize(), function(response) {
    $('#targetElement').html(id);
  }, 'json');
});

Upvotes: 2

Related Questions