开发者

Javascript/JQuery POST "url" undefined (undefined)

I've attached an onlcick event to a form's submit button to override the default POST request, but I'm having some trouble getting it to work.

What I want is for the item clicked to add to the shopping cart, but only show a modal confirmation and not refresh the page.

This code was working in my static example but something I've done since integrating it has made it break.

function cartSubmit(addbtn)
{
var form = addbtn.parentNode.parentNode.parentNode; 
var formData = jQuery(form).serializeArray();
jQuery.post("/myurl/", formData, function(开发者_开发问答r){
jQuery.colorbox({html:'<div style="padding:10px;"><h2>Product added to cart.</h2></div>'});        
 });
 return false;
}

Now I get an error in console saying POST "http://localhost/myurl/" undefined (undefined) then the form submits normally (refreshes the page), but seems also to submit with the javascript because it adds the item to the cart twice.

Anyway, any help is greatly appreciated!


You could try binding that function to the form through the submit event, for example, assuming your form has an id of myform add the following into your document ready, and you wont need the onclick attribute of your submit button anymore:

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js" type="text/javascript"></script>
  </head>
  <body>
    <form id="someform-123" method="post">
      <input type="text" id="field1" />
      <input type="submit" class="add_to_cart" value="Add" />
    </form>
    <hr>
    <form id="someform-789" method="post">
      <input type="text" id="field2" />
      <input type="submit" class="add_to_cart" value="Add" />
    </form>

    <script type="text/javascript">
      $('.add_to_cart').closest('form').submit(function(e) {
        e.preventDefault();
        alert('form id: ' + $(this).closest('form').attr('id'));
      });
    </script>
  </body>
</html>


I was having the same issue, an aborted AJAX request. I've fixed it using a return false on my button. If you have (for example):

<form method="post" action="">
Name: <input type="text" name="whatever" id="whatever" />
<input type="submit" id="join" value="Join" />
</form>

And

$("#join").click(function(){
  $.ajax({
    url: 'whatever.php',
    type: 'POST',
    data: 'name=' + $("#join").val(),
    success: function(r){ alert(r); }
  });
});

That will have the ABORT on whatever.php To fix it, cancel the submission of the form, adding a return on the button:

$("#join").click(function(){
  $.ajax({
    url: 'whatever.php',
    type: 'POST',
    data: 'name=' + $("#join").val(),
    success: function(r){ alert(r); }
  });
  return false;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜