0

Can't figure out what's wrong but all that happens is the URL changes to "http://localhost/?search=test" if I enter "test" for instance.

index.php

<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>

<script>

$("#Form").submit(function(e) {

    $.ajax({
           type: "POST",
           url: "search.php",
           data: $("#Form").serialize(),
           success: function(data)
           {
               alert(data); 
           }
         });

    e.preventDefault();
});

</script>
</head>
<body>

<form id=Form> 
Search: <input type="text" name="search" id="search" /><br /> 
<input type="submit" value="Submit" /> 
</form> 

</body>
</html>

search.php

<?php 
echo 'The search is '. $_POST['search'];
?>
Arno
  • 307
  • 1
  • 4
  • 14

2 Answers2

1

1st you forget " Form id and good to add method=""

<form method="post" action="#" id="Form">

2nd try to use e.preventDefault(); in the beginning not the end

3rd try to rearrange the code

<body>

<form method="post" action="#" id="Form">
Search: <input type="text" name="search" id="search" /><br /> 
<input type="submit" value="Submit" /> 
</form> 
<script>

$("#Form").on('submit',function(e) {
    e.preventDefault();  // use it here
    $.ajax({
           type: "POST",
           url: "search.php",
           data: $("#Form").serialize(),
           success: function(data)
           {
               alert(data); 
           }
         });
});

</script>
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
1

You're missing the action and method on your form, which are necessary for the form to generate a submit event.

<form id="Form" method="post" action="search.php" />

Now that we have the action and method defined, why not just take it from the form instead of re-writing it in Javascript? That would be better for re-usability. Also note that you have to assign event handlers when the DOM is ready. At the time you're assigning the event, the DOM element doesn't exist, so it will do nothing:

<script type="text/javascript">
    $(document).ready(function() { // Here, after DOM is ready
        $('#Form').submit(function(e) {
            e.preventDefault();

            $.ajax({
                type:    $(this).attr('method'),
                url:     $(this).attr('action'),
                data:    $(this).serialize(),
                success: function(data) {
                    // At this point, we already have the response from the server (we got it asynchronously)
                    // Lets update a div, for example <div id="response_message"></div>
                    $('#response_message').text( data );
                    // Div already has data, show it.
                    $('#response_message').show();

                    // Another option (same as before but with a function): Pass the response data to another function already defined: processData() in this case
                    // Use one or another, they're the same
                    processData( data );
                },
                error:   function(err) {
                    alert('An error just happened...');
                }
            });
        });
    });

    // This functions only receives data when the asynchronous call is finished
    function processData( data )
    {
        $('#response_message').text( data );
        // Div already has data, show it.
        $('#response_message').show();
    }
</script>

Note that in asynchronous calls you DO NOT expect a return. It simply doesn't exist by design (because the script would be blocked until the data is ready, and that's called synchronous). What you do in asynchronous calls is to define a function/method that will be called at any time when the data is ready (that's the success handler function). You don't know at what time it will be called, you only know that it will be called when data has been fetched and the argument will be the actual response from the server.

Alejandro Iván
  • 3,969
  • 1
  • 21
  • 30
  • @ArnoVR you could do that in the success handler. Do that update instead of `alert(data);`. `e.preventDefault();` avoids the form submitting normally (i.e avoids the page reloading on submit). – Alejandro Iván Nov 05 '15 at 20:48
  • Thanks that's nice and clean and works perfectly. I'm reading [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) to try and figure out how I can use the returned data somewhere else on my page. More specifically I've made the submit button of the same form .show a div which I'd like to see the result in. I'm too newb to this to know which route to go. Any suggestion? – Arno Nov 05 '15 at 21:52
  • @ArnoVR updated the answer, check it out. You **can't** `return` on asynchronous calls, you **wait** until data is fetched and it's given to your success handler as an argument. That means you already have the data in the `success` handler and just have to use it. That's the whole point. – Alejandro Iván Nov 05 '15 at 22:03