0

I don't know why ajax instead of sending request to specified url, it makes request to the same link. Only this ajax request in the whole page is acting weird. Please give me some light over this issue

       $(document).ready(function(){
          $("#phoneForm").submit(function(){
     $.ajax({
             type: "POST",
             url: "http://example.com/chat.pl",
             data: $('form#phoneForm').serialize(),
             success: function(data)
            {   
            if(data==="1")
            {
             $('#phoneResult').html('Thank you');//hide button and show thank you
             $('#phone_modal').modal('toggle');
            }
             },
                       error: function(){
                        alert("failure");
                   }
       });
      });
     });

Form content:

      <form class='horizontal' id='phoneForm' name='phoneForm' accept-charset='utf-8'>
    <input type='text' pattern='\\d*' id='phoneNumber' name='number'/>
        <button class='btn btn-dark' type='submit'>submit</button>  
</form>

Edited:

I added the ajax error function. Its giving the alert before ajax submission and give request to the same page

gzix
  • 271
  • 3
  • 20

2 Answers2

1

If I understand correctly, you want to submit your form asynchronously?

Try with an event.PreventDefault() like this:

$("#phoneForm").submit(function (event) {
    $.ajax({
        type: "POST",
        url: "http://example.com/chat.pl",
        data: $('form#phoneForm').serialize(),
        success: function (data) {
            if (data === "1") {
                $('#phoneResult').html('Thank you');//hide button and show thank you
                $('#phone_modal').modal('toggle');
            }
        },
        error: function () {
            alert("failure");
        }
    });
    event.preventDefault();
});
valentin
  • 667
  • 2
  • 12
  • 19
  • Hi i used return false and thought of answering my own answer yesterday. But i don't know how it is working. Please explain why its not working without event.preventDefault() or return false. – gzix Mar 01 '14 at 05:58
  • 1
    Sorry for taking so long to answer. It's because your submit handler (the function (event)) doesn't _replace_ the submit event by default, it only allows you to execute additional code before it's triggered. The preventDefault or return false simply cancels that trigger. Also, see [this](http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false) for a difference between preventDefault and return false. – valentin Mar 03 '14 at 09:26
0

Try to add

method="POST" 

into the

<form class='horizontal' id='phoneForm' name='phoneForm' method="POST" accept-charset='utf-8'>
madushak
  • 250
  • 1
  • 5