1

I used Firebug to debug my code. In the "Net" panel, I don't see the .ajax() firing at all. (didn't see any outgoing request url)

What is wrong with my code?

Edited: After i added $(document).ready(). to my code, everything just works fine. Why do I need $(document).ready() ? I thought when the button is clicked, the document is ready for sure. Needed to add "return false;" as well

function doSubmit() {
        alert('button is clicked.');

        $.ajax({
          type: 'Post',
          url: "http://mysite.com/list/json",
          dataType: "json",
          context: [],
          success: function(data){
              alert('got data');
          }
        }); 
}       
<form name="my_form" id="myform">
    <div class="mydiv">
        <input class="button" type="submit" value="Save" onClick="doSubmit();">
    </div>
</form>
3
  • Did you mean to check the Console instead? Commented Sep 11, 2011 at 0:35
  • Just as a note, you are using context wrong. Context is what "this" should be in your handlers. Try using data instead. Commented Sep 11, 2011 at 0:40
  • You need document.ready in your case because the jquery library might not be loaded yet. It's also a good idea to put everything into a .ready function because the DOM might not be filled in by the time your script runs and if you have selectors running at start then they might miss elements. Commented Sep 11, 2011 at 0:58

2 Answers 2

4

You have to return false, otherwise it just submits that form

function doSubmit() {
        alert('button is clicked.');

        $.ajax({
          type: 'Post',
          url: "http://mysite.com/list/json",
          dataType: "json",
          context: [],
          success: function(data){
              alert('got data');
          }
        }); 
       return false;
}       
Sign up to request clarification or add additional context in comments.

4 Comments

Do I have to do return false? Cuz i want to do conditional check, if ajax returned data is good, then submit the form, else do "return false"
@Shadow_boi: you can add $("form").submit(); in success response, but you have to include that return false after your ajax command, too
Since this question is tagged as jQuery note that it's better practice to use preventDefault rather than return false. api.jquery.com/event.preventDefault
This also makes it easier to conditionally determine whether the form should submit and ommits the need to re-fire the submit event.
1
$('#myform').submit(function() {
    $.ajax({
        // ...
    });
});

Comments

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.