Placing a JavaScript event on a dynamically loaded PHP form - php

Solution:
Thanks to Shmiddty, I figured this out:
$( static parent element ).on('submit', '#add_client', function(e) {
e.preventDefault();
firm.addUser( $(this), '/ci/firm/add_client', 'client' );
});
Description:
I building some forms for a client. I want this form to be dynamically created depending on the link he clicks. This form is going to be auto-populated with some data.
Here is the jQuery that will create the dynamic content:
$('.create').on('click', function(e) {
e.preventDefault();
utility.create_modal(); // dynamic div with form
});
This is the function that creates the div and place the PHP form in the html:
$(document.createElement('div')).attr({
'class' : 'span3'
}).html( create_div( '/ci/firm/return_user_form/client', 'html' ) ),
Here is the ajax function:
var result = '';
$.ajax({
url: path,
type: 'get',
dataType: type,
async : false,
success: function(data) {
result = data;
}
});
return result;
This is the html that is pulled from the PHP file: (it's a huge form, i'm just going to include the button in question)
<input type="submit" name="submit" value="Add Client" id="add_client">
Problem:
This dynamic html content has a form in it. I want to place a JavaScript event ON the form that I included. Is this possible? If so, how can I do it?
This does not work (#add_client is the id of the button in the form):
$('#add_client').on('click', function(e) {
e.preventDefault();
});

$('some_parent_selector').on('click', '#add_client', function(e) {
e.preventDefault();
});
The on listener needs a parent object (that is not dynamic) to listen for a click event that bubbles up. Then, when the event bubbles up to the parent, it determines whether or not it originated from '#add_client', and if it does, it calls your anonymous function.

Related

Ajax requests are failing to send after an initial ajax request is made - trying to figure out what is causing a conflict

I have a form with multiple types of ajax calls.
- general form update that saves all input fields
- per-field uploads
- per-upload deletion
The per-field and per-upload ajax calls are targeted by the class name of the button that is clicked. So there are only 3 scripts in the page.
Each of the scripts work. When the page loads fresh, I can complete any of the form update, field upload, or upload deletion actions.
However, after I have completed an initial action, subsequent actions don't work.
Example:
If I click the "save" button to update the form, this causes the per-field upload and per-upload deletion buttons not to work.
If I click the "per-field" upload, the upload works, but then I'm not able to delete anything.
If I click a "per-upload" delete button, I can no longer upload anything.
But in each case, I am still able to click "save" to update the form.
Here's a visual of how the page is set up:
When a file or image is uploaded to a field, it appears in a container div within the field's markup. The uploaded asset comes with a 'delete' button allowing the user to remove the upload.
Here's the basic HTML of the page
<form id = "form" action = "/process.php" method = "post">
<div class="field">
<label class="field-label">
<span class="field-label-text">Upload 1</span>
<input type="file" data-name="answer1" name="files_answer1[]" />
</label>
<!-- destination for ajax response messages -->
<div id="ajax-message-answer1" class="ajax-field-message"></div>
<!-- upload button -->
<button type="button" class="ajax-button" data-field="answer1" data-type="files">Upload</button>
<!-- container div for uploads -->
<div class="assets" id="assets-answer1">
<div class="asset file">
Name of file
<label class="asset-action">
<!-- deletion button to remove asset -->
<button type="button" data-asset="asset1" data-parent="answer1" class="ajax-delete" value="asset1" onclick="return confirm('You are about to delete this item. Press OK to proceed.')">Delete</button>
</label>
</div><!-- .asset.file -->
</div><!-- .assets -->
</div><!-- .field -->
.... more fields of the same kind ...
<button type = "submit" id = "save">Save</button>
</form>
JS
There are several other scripts in the page, such as jQuery, jQuery UI, Bootstrap, and some custom ones for generating slugs, etc. But I'm thinking these aren't to blame since the problem began only when I started running more than one Ajax request in the page. Here's the JS:
Form Update script
<script type="text/javascript">
$(document).ready(function() {
// process form
$('#form').submit(function(eform) {
// stop regular form submission
eform.preventDefault();
// set variables
var form = $('#form');
// serialize form data
var fdform = form.serializeArray();
// make request
$.ajax({
url: '/account/ajax.php',
type: 'post',
data: $.param(fdform),
dataType: 'json',
success: function(data) {
// get URL for redirect if supplied
if (data.redirect) {
window.location.href = data.redirect;
} else {
// replace with updated template from response
$('#form').html(data.html);
// place template js in specified div
$('#ajax-js').html(data.js);
}
},
error: function(report) {
console.log(report.responseText);
}
});
}); // .click
}); // .ready
</script>
Per-Field Upload script
<script>
$(document).ready(function() {
$(".ajax-button").click(function() {
var fdUpload = new FormData();
// get field info from the clicked button
var field = $(this).data('field');
var uploadType = $(this).data('type');
var input = $('#' + field)[0];
var container_id = '#assets-' + field;
var button_id = '#button-' + field;
// add each file to uploads array
$.each(input.files, function(i, upl) {
// add each file to target element in fdUpload
fdUpload.append(uploadType + '[]', upl);
});
// make request
$.ajax({
url: '/account/ajax.php',
type: 'post',
data: fdUpload,
dataType: 'json', // returns success(data) as object
contentType: false,
processData: false,
success: function(data) {
// put received html in container
$(container_id).html(data.html);
// put received js in #ajax-js
$('#ajax-js').append(data.js);
// clear file input after upload completes
input.value = '';
if (!/safari/i.test(navigator.userAgent)) {
input.type = '';
input.type = 'file';
}
},
error: function(report) {
console.log(report.responseText);
}
});
});
});
</script>
Per-Upload Deletion script
<script>
$(document).ready(function() {
$(".ajax-delete").click(function() {
var fdDelete = new FormData();
// get asset info from clicked button
var asset = $(this).data('asset');
var parent = $(this).data('parent'); // answer
var container_id = '#assets-' + parent;
var button_id = '#delete-' + asset;
var message_id = '#ajax-message-' + asset;
// make request
$.ajax({
url: '/account/ajax.php',
type: 'post',
data: fdDelete,
dataType: 'json',
contentType: false,
processData: false,
success: function(data) {
// put received html in container
$(container_id).html(data.html);
// put received js in #ajax-js
$('#ajax-js').html(data.js);
// retrieve and display response status
$(message_id).html(data.status);
$(message_id).addClass('show');
},
error: function(report) {
console.log(report.responseText);
}
});
});
});
</script>
Summary
Again, each ajax request works when activated after a fresh page load. But after the form has been updated or after an upload or deletion, the upload and deletion no longer fire.
The 'error' callback doesn't display anything in console when this failure occurs.
Do you see a conflict somewhere in the scripts? Maybe the scripts need function names defined? Or is it a problem that the returned response object is called 'data' in each script?
I haven't been working with Ajax very long, so I'd really appreciate your help. I've been banging my head on this all day.
You're using $(".ajax-...").click(...) but in ajax success handler you're updating HTML code for container, thus loosing any attached click handlers for elements in this container.
If you switch to using $("#form").on('click', '.ajax-...', ...) then you'll catch click events even after directly replacing HTML.
jQuery.on() documentation

jQuery trigger previously defined onclick from link in new window

I am submitting a form using jquery onclick. On the PHP side, it checks to see if there is already an existing document by the same name. If true, a small form is returned in the response with 3 options, dependent on the record data. Those options are displayed in a message window. One of those selections needs to resubmit the previous form data, substituting the new name.
The problem is, the change name form does not exist when the page is loaded and thus does not recognize the ClickCheck class in the new form.
How can I resubmit this form with the new DocName?
The submit in the main form (actually this is one of four submits)
<a class="ClickCheck" id="Create" href="javascript:void(0)">Create Bill</a>
The jQuery:
$('.ClickCheck').click(function()
{
var ButtonID = $(this).attr('id');
$('#Clicked').val(ButtonID);
var Form = $('#TheForm');
if(ButtonID == "Save")
{
// Do save code
}
else
{
var FormData = Form.serialize();
$.ajax(
{
type: "POST",
url: "scripts/Ajax.php",
data: FormData,
success: function(response)
{
$('#MWContent').html(response);
$('#MessageWindow').show();
}
});
}
});
Then, in the response, I have:
<form id="ChangeName" name="ChangeName">
Use another name:
<input type="text" id="DocName" name="DocName" size="60" maxlength="60" value="" placeholder="Document Name" />
<a class="ClickCheck" id="NewName" href="javascript:void(0)">Go</a>
</form>
The idea is to have the "NewName" resubmit the form (with the new name, of course.) I can, of course, detect that in the click function.
You can attach the click() event to the document to make it global.
$(document).on('click', '.ClickCheck', function(e){
e.preventDefault() // <<<< Either this
// Do stuff
return false // <<<< Or this
})
http://api.jquery.com/on/
Also don't use href="javascript:void(0)", use return false or e.preventDefault() in the callback function.

Getting jquery to work with dynamic content

I am currently using a very similar AJAX post request across many parts of my page:
$(document).ready(function() {
$("#name").change(function(e){
var vname = $("#name").val();
$.post("addit.php", {name:vname}, function(response, status) {
$("#table").html(response);
});
});
});
The above code works perfectly.
I am having a problem getting any functionality with dynamically loaded content. So for example a form grabbed by an AJAX call and put into my page this above does not work.
If we can pretend that I was running the same AJAX call as above but on dynamically loaded content from a PHP script using AJAX. what would my call look like. #table is a static element that is always present on the page.
I have tried this but it is not working:
$(document).ready(function() {
$("#table").on("click", "#btn1", function(e){
e.preventDefault();
var vname = $("#name").val();
$.post("addit.php", {name:vname}, function(response, status) {
$("#table").html(response);
});
});
});
Currently I am getting nothing show up on console and it just does not work.
Is what I am doing here correct?
The html would look like this: echoed from php:
<table id='table'>//this is the static element form is echoed
<form method='post'>
<input id='name' name = 'name'>
<button id='btn1' type='submit'>Add me</button>
</form>
</table>
I have changed my code slightly click on button rather than on change.
Try updating the code with following
$(document).ready(function() {
$("#table #btn1").on("click", function(e){
e.preventDefault();
var vname = $("#name").val();
$.post("addit.php", {name:vname}, function(response, status) {
$("#table").html(response);
});
});
});
It is not possible to set a function on a dynamically added element, when the element is not there in document
And instead of <table> use <div> if possible
I think your problem is that you miss
$( document ).ajaxComplete(function() { "script here will run and be available after ajax load" });

ajax inject html into a div but keep the html elements including their ids

I am using some ajax to call a php file that returns some html (an image and couple of buttons) and then place the contents of this into a div. The trouble is that I want to be able to use the id of one of the buttons that is returned from the php to hook up an event handler. The output of the source if I do view source in browser simply shows the div that the html is injected into and not the html:
<div class="displaysomething"></div>
My AJAX is as follows:
$(document).ready(function () {
getServiceDisplay();
$('#stop-service').click(function(e)
{
e.preventDefault();
runHDIMService();
});
}
function getServiceDisplay(){
$.ajax(
{
url: 'includes/dosomething.php',
type: 'POST',
success: function(strOutput)
{
$(".displaysomething").html(strOutput);
}
});
};
PHP - Ultimately returns a button amongst other stuff. This is what I need to hook up to the event handler, based on its id.
echo '<input id="stop-service" type="button" value="Run" class="'.$strRunActionButtonClass.'"/>';
If I simply put a button on the page without injecting it using AJAX into the div my button hookup code works great.
Does anybody have any ideas?
Thanks
In jQuery, the .click(... method of adding an event handler will only add the event to existing elements. New elements added later are no included.
You can use the jQuery on method of event binding to include elements added later.
$("body").on("click", "#stop-service", function(e){
e.preventDefault();
runHDIMService();
});
I have created a simple example on JSFiddle.
The problem is that
$(document).ready(function () {
getServiceDisplay();
$('#stop-service').click(function(e) // this doesn't exists yet
{
e.preventDefault();
runHDIMService();
});
This should work:
function getServiceDisplay(){
$.ajax(
{
url: 'includes/dosomething.php',
type: 'POST',
success: function(strOutput)
{
$(".displaysomething").html(strOutput);
// so after you attached the div from ajax call just register your event
$('#stop-service').click(function(e)
{
e.preventDefault();
runHDIMService();
});
});
};

jquery form submit does not work after using a load function

I have an index.html page which, using jquery, calls somepage.php residing within the same site to load the contents of this index.html page.
So this is the intended page load sequence:
index.html -> somepage.php -> submit.php (if submit button is clicked)
The index.html has only the "main-div" and no contents as such. When the somepage.php is called, the "main-div" contents are loaded by running the php script. The main-div contains a sub div with a small form with a submit button. Using jQuery,I see if the submit button is clicked, and when clicked, the submit.php script is called.
This is the barebone code:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$('document').ready(function(){
$("#main-div").load("http://www.someurl.com/somepage.php");
$('#item-submit').click(function(){
jsURL = $('#input').val();
submit(jsURL);
});
function submit(jsURL){
$.get(
'http://www.someurl.com/submit.php',
{ item: jsURL },
function(data){
if(data=="success")
{
$('#submit-status').html(data);
}
else
{
$('#submit-status').html(data);
}
}
);
}
});
</script>
</head>
<body>
<div id="main-div"> </div>
</body>
</html>
Now the issue:
The index.html page loads with everything displayed correctly (the small form with the submit button, all other main-div contents, everything is displayed). However, the submit button does not call the submit.php script, meaning I believe that the jQuery code corresponding to the click event is not being registered.
I am fairly new to jQuery. Does this have something to do with how I have "ordered" the code in the jQuery .ready()? Something to do with the DOM not being ready before the function is called, or maybe an issue with the .load() in jQuery?
Try this :
<script>
$(document).ready(function(){
$("#main-div").load("http://www.someurl.com/somepage.php",function(){
$("#main-div").on('click', '#item-submit', function(e){
e.preventDefault();
var jsURL = $('#input').attr('value');
submit(jsURL);
});
});
});
function submit(jsURL){
$.ajax({
url:'http://www.someurl.com/submit.php',
type :'GET',
success: function(data){
$('#submit-status').html(data);
}
});
}
</script>
$(document).ready(function(){
$("#main-div").load("http://www.someurl.com/somepage.php");
$("#main-div").on('click', '#item-submit', function(e){
e.preventDefault();
var jsURL = $('#input').val();
submit(jsURL);
});
function submit(jsURL){
$.get('http://www.someurl.com/submit.php', {item: jsURL}, function(data){
$('#submit-status').html(data);
});
}
});
Do not quote the document
load() is a shortcut for $.ajax, and it's async, so #item-submit does'nt exist when you attach the event handler, you need a delegated event handler for that.
If it's really a submit button inside a form, make you sure you prevent the default action so the form does'nt get submitted.
The load function works asynchronously. With your code #item-submit is not yet there when you try to bind the event handler.
Bind the event handler on succes:
$("#main-div").load("http://www.someurl.com/somepage.php", function () {
$('#item-submit').click(function () {
jsURL = $('#input').val();
submit(jsURL);
});
});
load loads the data asynchronously, which means time by the time you are assigning a click handler on submit button the button itself might not be yet on the page. To overcome this you have two options:
Specify a success handler for load.
$("#main-div").load("http://www.someurl.com/somepage.php", function(){
$('#item-submit').click(function(){
jsURL = $('#input').val();
submit(jsURL);
});
});
Use on to indicate that the click handler should be assigned to elements that are or will be on the page.
$('#item-submit').on('click', function(){
jsURL = $('#input').val();
submit(jsURL);
});
As all pointed out, the load function works asynchronously so, your click handler is not working for the 'future' div.
You can bind handler to a future element like this:
$(document).on('click', '#item-submit', function(event){
jsURL = $('#input').val();
submit(jsURL);
});
This way you can bind your handler in the jQuery document ready function.

Categories