ajax success function (with html method) only fires once - php

I'm having some problems with ajax callbacks that I'm hoping I could get some help with. Basically, this script replaces the #inbox div with archive.php (which normally would generate messages and matching modals, but for simplicity sake I just included generic modals).
The ajax callback is triggered when you close a modal. It currently returns the modals ID. However, this only works once - that's where I'm having the problem. The problem seems to lie with the jQuery html command. I've replaced it with alert(id) and the script will run as many times as I want. Any suggestions? Please let me know if I need to clarify more. Thanks.
HTML / JavaScript:
<div id="inbox"> <!-- Content should be put between this div -->
<?php include_once('archive.php'); ?>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="assets/js/bootstrap.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#inbox .modal').on('hidden', function() {
id = $(this).attr('id');
$.ajax({
type: "POST",
url: "archive.php",
data: {message_id : id},
cache: false,
success: function(data) {
$('#inbox').html(data); // problem is here
}
});
});
});
</script>
PHP (archive.php):
<?php echo $_POST['message_id']; // I've also used SQL inserts, which work fine when I'm not using the jQuery HTML command ?>
<!-- Modal 1 -->
Launch demo modal
<div id="modalOne" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
<!-- Modal 2 -->
Launch demo modal
<div id="modalTwo" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
<!-- Modal 3 (etc...) -->

When you run this:
$('#inbox .modal').on('hidden', function() {
It finds the current '#inbox .modal' objects and binds an event handler to them.
When you then do:
$('#inbox').html(data);
it replaces those DOM objects with new ones and you no longer have any event handlers active on those new objects.
You have two choices to fix it:
You can use delegated event handling which works with dynamically created objects.
You can rebind the event handlers after replacing the HTML.
I don't know about the hidden event you are using, but if it works with delegated event handling, then you can change to this to use delegated event handling:
$('#inbox').on('hidden', '.modal', function() {
Here, the event is bound to the #inbox object which is not recreated and it then checks events that bubble up to see if they originated on a .modal object. That's how delegated event handling works and it works with child objects that are dynamically created after the event handler is installed on the parent object.

You have bound the event to $('#inbox .modal'), so when you replace the content with $('#inbox').html(data) you are also removing (replacing) the element that the event is bound to. Instead try $('#inbox').on('hidden', '.modal', function() { for binding your event.

Related

Why does my jquery submit form popup disable any button clicking or page response?

I'm a bit new to jquery.
Currently, I have a contact 7 form on wp, and have created the function below in order to have a modal popup with a successful submission. However, while it works as intended, when the popup modal appears, the screen goes a tad darker, and neither the 'back to home' or close button will function - or anything else on the page for that matter.
The website is Deltadesigns.co -- Feel free to submit a form -- the inspect shows no errors in the console .
The code is as follows:
<div class="col-md-9 col-sm-10">
<div class="contact-form" id="contact-id">
<?php echo do_shortcode("[contact-form-7 id=\"86\" title=\"Contact form 1\" html_class=\"form-group\"]"); ?>
</div>
</div>
<div class="modal-fade" id="submitModal" tabindex="-1" role="dialog" aria-labelledby="submitModal" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="submitModalLabel">Success!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Thanks for reaching out! We'll reply within 1-2 business days.
</div>
<div class="modal-footer">
<a button type="button" href="https://deltadesigns.co/" class="btn btn-primary">Back to Home</button></a>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.slim.js" integrity="sha256-HwWONEZrpuoh951cQD1ov2HUK5zA5DwJ1DNUXaM6FsY=" crossorigin="anonymous"></script>
<?php add_action( 'wp_footer', 'mycustom_wp_footer' );
function mycustom_wp_footer() {
?>
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
if ( '86' == event.detail.contactFormId ) { // Change 123 to the ID of the form
jQuery('#submitModal').modal('show'); //this is the bootstrap modal popup id
}
}, false );
</script>
<?php } ?>
<script type="text/javascript">
document.querySelector('.close').addEventListener('click',
function(){
document.querySelector('.modal-fade').style.display='none';
});
</script>
<?php
get_footer();
?>
The problem was that the jquery function, bootstrap, or wordpress perhaps, added in a modal-backdrop element which I hadn't thought to look for, and the Z-index of the class was set higher than all other elements.
Once I changed it to be below that of the popup, all was well.
Here is the error in the modal-footer:
<div class="modal-footer">
<a button type="button" href="https://deltadesigns.co/" class="btn btn-primary">Back to Home</button></a>
</div>
The <a> and <button> tags are merged in your code.
Try this:
<div class="modal-footer">
<button type="button" class="btn btn-primary">Back to Home</button>
</div>

Laravel: Is it possible to load blade view into a jquery modal?

Below is my main blade file that I want to load into modal.
#extends('layouts.app')
#section('title', trans('pages.jobs.show.header_title') ?: trans('pages.jobs.show.title'))
#section('navigation')
#endsection
#section('content')
<div class="container">
<div class="page-dashboard">
{{ all teh content loaded: such as SVG grapgh using JS }}
</div>
</div>
<nav class="container-fluid nav-bottom" data-js="nav-bottom">
<div class="nav-bottom__overlay"></div>
</nav>
#push('scripts')
<script src=""></script>
#endpush
#endsection
I have tried using bootstarp.js modal but the modal is not loading, it loads in the main page.
Is it possible to load an entire blade with its own CSS and js included?
Kindly provide me any example. Maybe, I have to use ajax:
$('#modellink').click(function(){
$.ajax({
type : 'GET',
url : $(this).data('path'),
success: function(result, url) {
$('.modal-body').html(result);
$('#myModal').modal('show');
$('.modal-container').load($(this).data('path'),function(result){
$('#myModal').modal({show:true});
});
}
});
});
If you have a file call modal.blade.php, which has all the HTML, CSS and JS for that modal, you can include it on any page with #include("modal"). For example:
modal.blade.php
<style>...</style>
<div class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>One fine body…</p>
</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>
<script type="text/javascript">...</script>
Then, in your main file:
main.blade.php
#extends("layout")
#section("content")
#include("modal")
<div>...</div>
Return the HTML string
// SomeController::getModal()
return view('layouts.someview', $data_array)->render();
Load it into the modal
$.ajax(
// blah,
// blah,
success: function(response) {
$('#modal').html(response)
}
)
In short - yes.
Im not sure how you're loading your modal - as you don't provide much information, but, if you can load an external page into your modal, then simply point to the laravel route that displays your blade view.
Alternatively, use an #include('modal.name.blade') and have that as part of the page which uses the modal with the correct html/css of course for your relevant modal script.

Should I (and how) run a php script with modal bootstrap?

I have created a phpscript - calculator it's here
How to optimize this short script in php - salary calc
and it is working.
Now I would like to do sth like this. A person on my web page clicks the button, the calculator opens in sth like little window, he uses calculator and when he finishes, closes the window with calculator and is on the webpage again. As I understand I should do it with bootstrap modal like this: http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal_sm&stacked=h
Do I understand it right?
How should I link my phpscript with this modal?
thank You for your hints?
what you need is an Ajax method with modal event listener,
Modal HTML
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Small Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div id="showcal"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
B.S Modal event listener with Ajax Method
$(document).ready(function(){
$('#myModal').on('shown.bs.modal', function () {
$.ajax({
type: 'GET',
url: "calculator.php", //this file has the calculator function code
success:function(data){
$('#showcal').html(data);
}
});
});
});
and in last calculator.php
<?php
//Here comes the calculator code
?>
Lemme know if it worked and if not will make it work.

Using Bootstrap Modal for ZfcUser in ZF2?

as i am a complete newbie to Zend Framework this might be a total beginner question:
I did some tutorials and now i have a Zend-Framework skeleton-application with ZfcUser (and ZfcBase) up and running.
Everything works fine so far, but what i want to accomplish is that the Login and Registration opens up in a Bootstrap-Modal-Dialog.
So now i see that in ./vendor/ZfcUser/config/module.config.php you can define the routes, but i have no idea what to do, when i want the whole dialogs being "served" with the index of my main-application (i guess i will need this to let the login dialog open up from the main menu from anywhere in the application).
So can someone help me with getting this to work? I really have no idea how to start at all and any help is highly appreciated :)
best regards
If you want to use Bootstrap Model for ZfcUser login, You need to change approach of login a bit.
You should use ZfcUser API Calls to validate login instead of post data on /user/login page.
You need to override the ZfcUser login.html to change form action button from submit to simple button/link binded with ajax request.
Call ZfcUserLoginWidget into Bootstrap Model's body
Form/ajax action set to your custom auth page
Where ZfcUser API Calls validate & return json response with success/failure.
ZfcUser validation no more work automatically, You need to apply through jQuery, Javascript from Json Response.
So First copy vendor/ZfcUser/view/user/login.html to module/[YourModule]/view/zfc-user/user/login.phtml
Now replace submit button with normal button like that :
<input type="button" value="Sign in" onClick="javascript:verifyLogin(this.form);" />
--
--
<script type="text/javascript">
function verifyLogin(frm)
{
var data = $(frm).serialize();
$.ajax({
type: "POST",
url: "<?php echo $this->url('authurl') ?>",
data: data,
success: function(resp){
alert(resp.status);
},
error: function(resp){
},
dataType: 'json'
});
}
</script>
You should add a route for authurl for YourController/authAction
Add your html for Bootstrap model on parent template view :
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Login Box
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" 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" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<?php echo $this->zfcUserLoginWidget(); ?>
</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>
Now YourController/authAction code should work like that :
$request = $this->getRequest();
$data = $request->getPost();
$this->getRequest()->getPost()->set('identity', $data['identity']);
$this->getRequest()->getPost()->set('credential', $data['credential']);
$this->zfcUserAuthentication()->getAuthAdapter()->resetAdapters();
$this->zfcUserAuthentication()->getAuthService()->clearIdentity();
$adapter = $this->zfcUserAuthentication()->getAuthAdapter();
$adapter->prepareForAuthentication($this->getRequest());
$auth = $this->zfcUserAuthentication()->getAuthService()->authenticate($adapter);
if (!$auth->isValid()) {
//$this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
$adapter->resetAdapters();
$response_data = array(
'status' => 'Failure'
) ;
}
else
{
$response_data = array(
'status' => 'OK'
) ;
}
$response = $this->getResponse();
$response->setStatusCode(200);
$response->setContent(json_encode($response_data));
return $response;
The Login Widget viewhelper is probably what you are looking for. Within your desired .phtml template just add the viewhelper to render the login form.
<!-- Modal -->
<div class="modal fade" id="myModal" 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" aria-hidden="true">× </button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<?php //Add the Widget to the Modal Body here!?>
<?php echo $this->zfcUserLoginWidget(); ?>
</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>
If you want to alter the template of the widget you'll need to edit/add the zfcuser.global.php in your ../config/autoload/ folder and change/uncomment this the following to your desired login-widget template.
'user_login_widget_view_template' => 'your_module/whatever/login.phtml',

Reload modal-content inside modal on click

I have this very simple jQuery-script to change modal content based on link. Code:
$('#facebook-friends').on('hidden', function () {
$(this).removeData('modal');
});
And then I can control which content will be used, based on the buttons:
<i class="icon-facebook"></i> Use Facebook
It works perfectly! However, I have links inside this facebook-frame.php file, and I want all actions to stay within the modal, so that the outside page doesn't reload.
I have tried this solution inside facebook-frame.php but it doesn't work.
<a href="facebook-frame.php?all" data-target="#facebook-friends" role="button" class="btn btn-primary" data-toggle="modal">
This is the modal on my mainpage:
<div class="modal fade hide" id="facebook-friends" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" >
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Inviter veninder fra Facebook</h3>
</div>
<div class="modal-body text-center">
<p>Loading content...</p>
<p><IMG src="ajax-loader.gif"></p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Luk</button>
</div>
</div>
I especially love the "Loading content", as it seems very dynamic.
Is there any way to assign a special command/class/name to links/buttons inside facebook-frame.php so that when clicked it will temporary show the "Loading content" and then meanwhile load the requested page (inside href attribute)?
If I'm understanding correctly, inside facebook-frame.php can you just capture all <a> (or specific <a> classes) click events like so?
$(document).on('click', '#facebook-friends a', function(e) {
e.preventDefault();
// show the "Loading content" message
// load the content and whatever else you need to do
});
Note: .on() requires jQuery 1.7+. Before that you would use .live().

Categories