Good day! There is a search form:

<form method="POST" action="simple_search.php" id="form_id" enctype="multipart/form-data"> <input type="text" name="usersearch" size="50" /> <input type="submit" name="submit" value="Искать" id="submit" /> </form> 

And a div to display the results:

 <div id="result></div> 

Ajax sends a request to the php handler:

 $("#submit").click(function(e) { var $form = $("#form_id"); $.ajax({ cashe: false, type: $form.attr('method'), url: $form.attr('action'), data: $form.serialize(), }).done(function() { console.log('success'); }).fail(function() { console.log('fail'); }); e.preventDefault(); }); 

The handler searches the database and displays the results

 $user_search = $_POST['usersearch']; if(!empty($user_search)) { $query_usersearch = "SELECT * FROM docs WHERE title LIKE '%$user_search%' OR description LIKE '%$user_search%' OR keywords LIKE '%$user_search%'"; $result_usersearch = mysqli_query($link, $query_usersearch); while($array_usersearch = mysqli_fetch_array($result_usersearch)) { echo $array_usersearch['title']; echo $array_usersearch['description']; } } 

Question: how to put these results using the same ajax request in the #result div? Thank!

    2 answers 2

    There is a great example on this page :

     $.ajax({ url: "some.php", success: function(data){ alert( "Прибыли данные: " + data ); } }); 

    This means that you better use the callback function success (with ajax it is generally better to use always callback), and your code will change something like this:

     $("#submit").click(function(e) { var $form = $("#form_id"); $.ajax({ cashe: false, type: $form.attr('method'), url: $form.attr('action'), data: $form.serialize(), success: function(data) { $("#result").html(data); console.log('success'); }, error: function() { console.log("error"); } }); e.preventDefault(); }); 
    • All OK! Thank! - humster_spb
    • @humster_spb you are strange community people :) the answer below is given earlier and is absolutely the same, and you (the author of the answer) later edited it. Adding the same solution as in the previous answer. - Naumov
    • I did not edit the answer - I left a comment, but then deleted it for meaninglessness) and I am not the author of the answer - I am a questioner :)) - humster_spb
    • @Naumov I think that it’s necessary to give not just a ready-made code, but to explain why I did it, which I did first, then I realized that it’s better to attach the ready-made code. - Victor Evlampiev
     $("#submit").click(function(e) { e.preventDefault(); var $form = $("#form_id"); $.ajax({ cache: false, type: $form.attr('method'), url: $form.attr('action'), data: $form.serialize(), success: function(result) { $('#result').html(result); } }).done(function() { console.log('success'); }).fail(function() { console.log('fail'); }); });