jQuery trigger previously defined onclick from link in new window - php

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.

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

Multiple submit buttons with ajax & php not being processed

I'm very new to PHP & AJAX. I have two submit buttons in HTML and I'm passing/extracting some values to/from a PHP file using ajax serialize() or say ajax. The problem is that serialize() is not able to distinguish which button is used, the "reject" button or the "accept" button which is creating problem for PHP file as it is neither processing for accept button nor for reject button.
At the end, my main purpose is to add some data to DB when a user hits Accept Button & remove some data from DB if a user hits Reject Button But using Ajax.
HTML
<button class="p" type="submit" value="accept"></button>
<button class="p" type="submit" value="reject"></button>
PHP
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST["accept"]){
// doSomething
}else if(isset($_POST["reject"]){
// doSomethingElse
}
}
...
...
...
Ajax (It's not the complete code, just to have basic idea)
var form = $d('#formName');
$('.p').click(function(){
var formData = $d(form).serialize();
$d.ajax({
type: 'POST',
url: $d(form).attr('action'),
data: formData
})
.done(function(response){
window.location.reload(true);
})
});
You will need to give your submit a name attribute. Example:
<button class="p" name="action" type="submit" value="accept"></button>
<button class="p" name="action" type="submit" value="reject"></button>
And your PHP code can check the $_POST value for action.Example:
if($_POST["action"] == 'accept'){
// doSomething
}else if($_POST["action"] == 'reject'){
// doSomethingElse
}
Submit buttons are not serialized, you can get the data from them manually.
Also make sure the buttons have name attribute.
$('.p').click(function(e){
e.preventDefault();
var formData = $(this).attr('name') + '=' + encodeURIComponent(this.value) + '&' + $d(form).serialize();
$d.ajax({
type: 'POST',
url: $d(form).attr('action'),
data: formData
})
.done(function(response){
window.location.reload(true);
});
});

Sending form ID to AJAX on button click

I have a question that's blowing my mind: how do I send a form ID stored in a PHP variable to my AJAX script so the right form gets updated on submit?
My form is a template that loads data from MySQL tables when $_REQUEST['id'] is set. So, my form could contain different data for different rows.
So, if (isset($_REQUEST["eid"]) && $_REQUEST["eid"] > 0) { ... fill the form ... }
The form ID is stored in a PHP variable like this $form_id = $_REQUEST["eid"];
I then want to use the button below to update the form if the user changes anything:
<button type="submit" id="update" class="form-save-button" onclick="update_form();">UPDATE</button>
and the following AJAX sends the data to update.php:
function update_form() {
var dataString = form.serialize() + '&page=update';
$.ajax({
url: 'obt_sp_submit.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: dataString, // serialize form data
cache: 'false',
beforeSend: function() {
alert.fadeOut();
update.html('Updating...'); // change submit button text
},
success: function(response) {
var response_brought = response.indexOf("completed");
if(response_brought != -1)
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn(); // fade in response data
$('#obt_sp')[0].reset.click(); // reset form
update.html('UPDATE'); // reset submit button text
}
else
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn();
update.html('UPDATE'); // reset submit button text
}
},
error: function(e) {
console.log(e)
}
});
}
I'd like to add the form's id to the dataString like this:
var dataString = form.serialize() + '&id=form_id' + '&page=update';
but I have no idea how. Can someone please help?
The most practical way as stated above already is to harness the use of the input type="hidden" inside a form.
An example of such would be:
<form action="#" method="post" id=""myform">
<input type="hidden" name="eid" value="1">
<input type="submit" value="Edit">
</form>
Letting you run something similar to this with your jQuery:
$('#myform').on('submit', function(){
update_form();
return false;
});
Provided that you send what you need to correctly over the AJAX request (get the input from where you need it etc etc blah blah....)
You could alternatively include it in the data string which; I don't quite see why you would do.. but each to their own.
var dataString = form.serialize() + "&eid=SOME_EID_HERE&page=update";
Sounds like a job for a type=hidden form field:
<input type="hidden" name="eid" value="whatever">
You have to write the string dynamically with PHP:
var dataString = form.serialize() + "&id='<?php echo $REQUEST['eid'] ?>'+&page=update";
On the server you can write Php code on the document, and they will be shown as HTML/JS on the client.

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();
});
});
};

Placing a JavaScript event on a dynamically loaded PHP form

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.

Categories