Ajax/PHP - How to Get Posted Data to Load into a Modal on the Same Page

Bootstrap 3 - How to load content in modal body via AJAX?

Check this SO answer out.

It looks like the only way is to provide the whole modal structure with your ajax response.

As you can check from the bootstrap source code, the load function is binded to the root element.

In case you can't modify the ajax response, a simple workaround could be an explicit call of the $(..).modal(..) plugin on your body element, even though it will probably break the show/hide functions of the root element.

Filling modal content using PHP and AJAX?

Alright, here's my implementation on this issue, it will be a bit simpler to just provide the basics and let you edit your own code accordingly.

First of all my entire modal content is a div with an id, <div id="modalcontent"> </div>

Then, suppose this button should open and populate my modal with data

<a href="#" onclick="openModal()">Open</a>

openModal() will look something like this

$.post("alerts.php", {
id: ID
}, function(data) {//data will contain whatever alerts.php prints
document.getElementById("modalcontent").innerHTML = data;//insert data into modal
$('#my-modal').modal('toggle');//open modal
});

Again, there are many ways to do this. There are better ways to do this. But you should understand how something like this works, you can only get the output of the PHP file in javascript and edit your contents with javascript. You can get your data from another PHP script, which will be executed by javascript whenever you need it, but the PHP script itself can not modify the contents of your already loaded page.

Using this code and assuming alerts.php will echo "you have a notification";, <div id="modalcontent"> </div> will change to <div id="modalcontent">you have a notification</div> and then the modal will be toggled. This method also ensures the modal is only opened after the data is fetched so it's impossible for the modal to open without the data inside.



Related Topics



Leave a reply



Submit