Văn Cao Trần Văn Cao Trần - 2 months ago 24
Ajax Question

Create modal when use onclick event with Ajax

i have a file need to have 90 modals with many long text, because that i need to create modal when clicking a link.

In my index.php file:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>

<!-- Bootstrap -->
<link href="inc/bootstrap.css" rel="stylesheet">
<script src="inc/jquery.min.js"></script>
<script src="inc/bootstrap.min.js"></script>
</head>
<body>
<script>
$(function(){
$('a').click(function(){
var link = $('#name').html(); // I need sent this to my calculator file
$.ajax({
url : "result.php",
type : "post",
dataType:"text",
data : {
name: link
},
success : function (a){
$('#result').html(a);
}
});
});
});
</script>
<div id="result"></div>
<a href="#" id="name">I need this text for php script</a>
</body>
</html>


In my resuilt.php file

/* I used PHP becase i need more functions, this only a example how
* to creat and call a modal after click on a link.
*/
function create_modal($modal_ID = 'myModal')
{
return "<div class='modal fade' id='$modal_ID' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>
<div class='modal-dialog'>
<div class='modal-content'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal'><span aria-hidden='true'>&times;</span><span class='sr-only'>Close</span></button>
<h4 class='modal-title' id='myModalLabel'>Nhãn</h4>
</div>
<div class='modal-body'>
Nội dung
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>
<button type='button' class='btn btn-primary'>Save changes</button>
</div>
</div>
</div>
</div>";
}
echo create_modal();
?>


The result is, i need click on the link 2 times to show my modal. But it cant close or does anything. Where i wronged and have any way to make my idea better? i just a newbie of Java script. Thanks a lot and sory for my bad English!

Answer Source

you can add

success : function (a){
                        $('#result').html(a);
                        $('#myModal').modal('show');
                    }

just add $('#myModal').modal('show'); when ajax load your modal in #result