views:

12

answers:

1

I have a form with two input fields, one text and one send button. I want to submit via jQuery .ajax() without reloading the document. It works as long as the button is clicked, but not when you press return/enter, then it submits without ajax methodology. I tried onEnter() or onSubmit(), but that didn't work either.

These are the code bits:

//HTML

<div id="search_form">
   <form method="POST" action="search.php">
    <input id="search_text" type="text" name="query"/>
    <input id="search_button" type="button" value="send"/>
   </form>
</div>
<div id="results"></div>

//Javascript

jQuery(function(){

$("#search_button").click(function(){
 var query = "query="+$("input[name=query]").val();   

 $.ajax({
      type: "GET",
      url: "request.php",
      data:query,
      cache:false,  
      success: function(result){ 
       $('#results').fadeIn();
      },
      error:function(xhr,err){
      alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
      alert("responseText: "+xhr.responseText);
   }  
     });
 });
});
+2  A: 

Instead of a click on the button, rig up to the submit event on the <form>, like this:

$(function() {   
  $("#myFormId").submit(function() {
    $.ajax({
      type: "GET",
      url: "request.php",
      data: $(this).serialize(),
      cache: false,  
      success: function(result){ 
        $('#results').fadeIn();
      },
      error:function(xhr,err){
        alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
        alert("responseText: "+xhr.responseText);
      }  
    });
    return false;
  });
});
Nick Craver
Thanks, and it sounds right, but it is still reloading the whole page for me. Oh and maybe that's a hint - clicking the button stopped working with this change
J. Frakes
@JFrakes - you need a `.preventDefault()` or `return false` to stop that - check the updated answer :) Also change your `type="button"` to `type="submit"`.
Nick Craver
Great! That return false really did it, thanks for your quick and precise answer
J. Frakes
@JFrakes - welcome :)
Nick Craver