12

I've built an ajax call that's submitted when a user clicks the submit button. I've included jquery and wrote the following code (taken from the jquery documentation):

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
  $("Shareitem").click(function(e){
      e.preventDefault();
    $.ajax({type: "POST",
            url: "/imball-reagens/public/shareitem",
            data: { id: $("Shareitem").val(), access_token: $("access_token").val() },
            success:function(result){
      $("sharelink").html(result);
    }});
  });
});
</script>

Html:

<div id="sharelink"></div>
[...]
<input type="hidden" name="id" value="" id="id"></dd>
<dd id="access_token-element">
<input type="hidden" name="access_token" value="xxxxxxxx" id="access_token"></dd>
<dt id="Shareitem-label">&#160;</dt><dd id="Shareitem-element">
<input type="submit" name="Shareitem" id="Shareitem" value="UpdatedByPreviousAjaxCall"></dd></dl></form>

The problem is, the submit action is executed but the ajax call is not, so the form is performing the requested submit action instead of staying on the same page and updating the content of the div tag.

What am I missing? Where am I wrong? Thanks in advance for any tips.

Hiebs915
  • 666
  • 1
  • 7
  • 22
softwareplay
  • 1,379
  • 4
  • 28
  • 64

1 Answers1

17

You did not add # before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.

See documentation: http://api.jquery.com/category/selectors/
its your friend.

Try this:

It seems that id: $("#Shareitem").val() is wrong if you want to pass the value of

<input type="hidden" name="id" value="" id="id">

you need to change this line:

id: $("#Shareitem").val()

by

id: $("#id").val()

All together:

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
    $(document).ready(function(){
      $("#Shareitem").click(function(e){
          e.preventDefault();
        $.ajax({type: "POST",
                url: "/imball-reagens/public/shareitem",
                data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
                success:function(result){
          $("#sharelink").html(result);
        }});
      });
    });
    </script>
fedorqui
  • 275,237
  • 103
  • 548
  • 598
Awlad Liton
  • 9,366
  • 2
  • 27
  • 53
  • Your answer is working and precise (and i was not cause it was too late in the evening so my mind was a bit obfuscated but, anyway i had to change even the manner in which jquery was included as i'm working with SSL i followed [this tutorial](http://stackoverflow.com/questions/18251128/why-am-i-suddenly-getting-a-blocked-loading-mixed-active-content-issue-in-fire) – softwareplay Jan 30 '14 at 09:15