Andy Andy - 1 month ago 14
PHP Question

Bootstrap 3 - showing ajax search results in a modal, then posting the modal elsewhere

I have a text input where a user can perform a search (for a username or email address held in a database). I already have a PHP script which does the searching etc.

I want to display the search results in a Bootstrap 3 modal - or an error message if there are none.

I'm struggling to understand the full logic of doing this.

What I have so far:

Search input and button:

<input type="text" name="search">
<button id="searchBtn">Search</button>


PHP function (accessible via
/ajax/search/
) which accepts POST data (e.g.
$_POST['search']
), queries the database. At the moment this returns an array - empty if no results.

What is the correct order to run things? I know that I need to pass my search input to
/ajax/search/
. But I also need to open a modal - both of these are presumably done on clicking Search (
searchBtn
). Do I submit the form with jquery's ajax method first, and then get the success to open the modal?

To further complicate matters, once this modal is shown there will be a series of tickboxes next to users that were found. This will need to be posted elsewhere... But I'm not even getting this far yet.

I'm struggling to understand this and have read a few posts already such as Bootstrap 3 with remote Modal and this Placing the results of a form post into a modal in Bootstrap 3

If there are any tutorials which show this please could someone point me at one as I can't find one, particularly where things aren't marked "this has been deprecated".

Answer

A simple example to consider:

JS

$('#myModal').on('shown.bs.modal', function() {
  $(".modal-body").html("Loading...");
  $.ajax({
    url: "/path/to/request",
    data: { 
         // Parameters if needed
    },
    method: "POST",
    success: function(data) {
      $(".modal-body").html(data);
    }
  })
});

Example (mockup) at:

https://jsfiddle.net/4bkhLatg/