1

I have started learning AJAX today. I wrote a simple ajax call, but instead of getting response asynchronously, it just load the PHP script page. Just like normal form submission.

html

<form id="form" method="POST" action="name.php">
   <input type="text" name="Name">
   <input type="submit" value="Submit" /> 

JS

$("#form").submit(function(e) {
    e.preventDefault();
    var url = "name.php";
    $.ajax({
           type: "POST",
           url: url,
           data: $("#form").serialize(),
           success: function(data)
           {
               alert(data);
           }
         });
});

PHP

<?php
     $data=  $_POST['Name'];
     echo $data;
 ?>

Instead of getting Alert on the same page, I am being redirected to name.php with the value I have submited.

Aown Muhammad
  • 156
  • 1
  • 16
  • You could try to return false from your submit function after the ajax call. Or maybe there is a JS error firing preventing the function from running properly from either running the callback or setting up the event handler. Double check that developer tools (F12) is showing no errors. – Jonathan Kuhn Jul 08 '16 at 17:53
  • 2
    If you're not getting a JS error, put the JS code inside `$(document).ready()`. – Barmar Jul 08 '16 at 17:54
  • using `$(document).ready()` did a trick. Because i am not using CDN, therefore I thought i dont need to use `$(document).ready()`. Thanks @Barmer – Aown Muhammad Jul 08 '16 at 18:07
  • It seems like you are totally confused about what it's for. Why would it make a difference where you're loading the script from? – Barmar Jul 08 '16 at 19:29
  • I still don't understand what actually `ready()` function has to do in this case. I have seen many AJAX calls with out `ready()` function. My document contains only a simple form and javascript & jq in header on localhost. – Aown Muhammad Jul 08 '16 at 19:47

2 Answers2

3

Wrapping ajax call inside $(document).ready() solved the problem.

Aown Muhammad
  • 156
  • 1
  • 16
2

Due to the inherent functionality that comes magically with forms and submit buttons, it is usually better to avoid them when working with AJAX. So for example, you can still use a <form> element as a field wrapper, but don't bother putting the attributes in as you are not using them from there. Also, replace your submit button with a standard anchor you can set an event on. Here is a rough example:

<form id="myForm">

    <input type="text" name="myValue">

    <a href="#" class="btn-submit">Submit</a>

</form>

and the JS:

$('.btn-submit').on('click', function(e) {
   e.preventDefault();
   var url = '/my/route/to/call';
   $.ajax({
        type: "POST",
        url: url,
        data: $("#myForm").serialize(),
        success: function(data)
        {
            alert(data);
        }
   });
});

What is happening is the form submit button is propagating an event that you are not stopping. Taking this approach removes the possibility for weird bugs like this.

Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
  • But he IS stopping the event with `e.preventDefault()`. – Barmar Jul 08 '16 at 17:56
  • Not exactly: http://stackoverflow.com/questions/5963669/whats-the-difference-between-event-stoppropagation-and-event-preventdefault – Jeremy Harris Jul 08 '16 at 17:57
  • Most likely he has another problem that's preventing the event handler from being bound to the element, and these changes won't fix that. – Barmar Jul 08 '16 at 17:57
  • I don't see what `stopPropagation` has to do with this. Forms can't be nested, so there's nothing to propagate to. – Barmar Jul 08 '16 at 17:58
  • 2
    I'll bet anything that the real problem is either that he has a syntax error that's preventing the code from running, or he needs to put it in`$(document).ready()`. You're overthinking it. – Barmar Jul 08 '16 at 17:59
  • using `$(document).ready()` solved the problem. – Aown Muhammad Jul 08 '16 at 18:11
  • very interesting but what did it do actually in this case? – Iceman Jul 08 '16 at 18:11
  • Seems you are right @Barmar. I think it is still not a great idea to make AJAX calls on top of existing form functionality unless you have code to fallback and handle it correctly in the event AJAX is not supported for some reason. – Jeremy Harris Jul 08 '16 at 18:18