I am loading a form via jquery load, which populates the content div, the form etc is showing up fine, but when I go to update the form with values it doesn't trigger my on("submit"
My jquery
<!-- process update profile form without refreshing, then load the div with the new information !-->
$("#content").on("submit", "#update_profile_form", function() {
alert("jfjf");
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: $(this).serialize(),
success: function(data) {
if(data.success == "false"){
$.notify(data.error, "error");
}else{
$.notify(data.success, "success");
$("#content").load("<?php echo Config::get('URL'); ?>user" + " #inner_main_content");
}
}
});
return false; <!-- important: prevent the form from submitting !-->
});
<!-- end process update profile form without refreshing, then load the div with the new information !-->
My form:
<form action="<?php echo Config::get('URL'); ?>/user/update_personal_information" method="POST" id="update_profile_form">
<!-- inputs here !-->
<input type="submit" class="btn vd_btn vd_bg-green col-md-offset-10" name="submit" id="submit" value="<?php echo System::translate("Update"); ?>">
<span class="menu-icon">
<i class="fa fa-fw fa-check"></i>
</span>
I am simply loading the form in to content via this code:
//populate the div
$('.list-group-item').click(function(e){
e.preventDefault();
var link = $(this).attr('href');
$('#content').fadeOut('slow', function(){
$("#content").load( link + " #inner_main_content", function(){
$('#content').fadeIn('slow');
});
});
The alert trigger in the on submit isn't even popping up which makes me beleive that it's not triggering, and I am receiving no errors neither. I am binding the on submit to the content id because that's the main div it loads to, so how can I iniate the form to work?
Here's the full form: http://pastebin.com/iGsPZmWT
I'm not sure to clearly understand the whole of your architecture, nor the precise case of your issue, but here is how I can summarize what I understand:
#content part includes the #submit element
#content part is first the direct content of the initial page, and is functional (triggers on submit)
when submit happens, #content part is overwritten by the .load() process
then #content part becomes non-functional (nothing happens on submit)
If it is really so, then the issue is pretty "normal": the submit event you attached to #content is lost when you load a new #content content (sorry for the repeat, but it comes from the id you'd choosen!).
Even if the new content also includes a #submit element, this one has no event attached to it now.
One solution is to execute the attachment again when a new content has been loaded, like this:
function attachSubmit() {
$("#content").on("submit", "#update_profile_form", function() {
alert("jfjf");
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: $(this).serialize(),
success: function(data) {
if(data.success == "false"){
$.notify(data.error, "error");
}else{
$.notify(data.success, "success");
$("#content").load("<?php echo Config::get('URL'); ?>user" + " #inner_main_content");
attachSubmit(); // <<-- here we attach event again to new content
}
}
});
return false; <!-- important: prevent the form from submitting !-->
});
}
(note that you also have to initially invoke attachSubmit() somewhere in a $(document).ready() sequence)
Alternatively you might attach a delegated event, so once is enough. In this case, though, you'll have to attach it to a parent element of #content, instead of #content itself, something like this:
// Here #parent is supposed to be a parent of #content
// The on() method got a #submit arg, as selector for delegation
$("#parent").on("submit", "#submit", "#update_profile_form", function() {
alert("jfjf");
$.ajax({
// ... same as YOUR previous version (nothing added)
});
return false; <!-- important: prevent the form from submitting !-->
});
Related
I have an email sign-up form on a website.
The form appears in two areas of each web page: the header and the footer
It's the same exact form, just available on the top and bottom of the page for better UX and accessibility.
The form uses a jQuery/AJAX script to provide success and error responses to the user. (i.e., "Success! Your subscription is complete." and "Error. Please review and re-submit")
The problem I'm having is that the header form processes but the footer form does not.
Any ideas what's wrong with this code? Thanks.
P.S. The form was working perfectly when the header and footer forms each had their own script. The problem started when the scripts were consolidated into one file. I've posted the original scripts at the bottom. Also, nothing has been changed in the PHP, so I don't think the problem is there.
$(function() {
// get the forms
var form = $('#header-form, #footer-form');
// set up event listener
$(form).submit(function(e) {
// disable html submit button
e.preventDefault();
// get the submit button
var submitButton = $('[type=submit]', this);
// get the messages element
var formResponses = $('#header-form-responses, #footer-form-responses', this);
formResponses.text(" ");
// serialize form data
var formData = $(form).serialize();
// disable submit button to prevent unnecessary submission
submitButton.attr('disabled', 'disabled');
// tell users that form is sending
submitButton.text('Processing...');
// submit form via AJAX
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// make sure formResponses element has 'success' class
$(formResponses).removeClass('error');
$(formResponses).addClass('success');
// set message text
$(formResponses).text('Your subscription is complete. Thank you!');
// clear form
$('input').val('');
})
.fail(function(data) {
// make sure formResponses element has 'error' class
$(formResponses).removeClass('success');
$(formResponses).addClass('error');
// set the message text
$(formResponses).text('Input error. Please review and re-submit.');
})
.always(function(data) { // this will always fire even if the request fails
submitButton.removeAttr('disabled');
submitButton.text('Send');
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- simplified HTML -->
<form action="form_processing.php" method="post" id="header-form">
<input type="email" name="email_subscription">
<button type="submit" id="header-form-submit">Submit</button>
<div id="header-form-responses"></div>
</form>
<form action="form_processing.php" method="post" id="footer-form">
<input type="email" name="email_subscription">
<button type="submit" id="footer-form-submit">Submit</button>
<div id="footer-form-responses"></div>
</form>
Here's the original header code (works perfectly):
$(function() {
var form = $('#header-form');
var formResponses = $('#header-form-responses');
var submitButton = $("#header-form-submit");
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
submitButton.attr('disabled', 'disabled');
submitButton.text('Processing...');
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formResponses).removeClass('error');
$(formResponses).addClass('success');
$(formResponses).text('Your subscription is complete. Thank you!');
$('input').val('');
})
.fail(function(data) {
$(formResponses).removeClass('success');
$(formResponses).addClass('error');
$(formResponses).text('Input error. Please review and re-submit.');
}).always(function(data) {
submitButton.removeAttr('disabled');
submitButton.text('Send');
});
});
});
Here's the original footer code (works perfectly):
$(function() {
var form = $('#footer-form');
var formResponses = $('#footer-form-responses');
var submitButton = $("#footer-form-submit");
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
submitButton.attr('disabled', 'disabled');
submitButton.text('Processing...');
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formResponses).removeClass('error');
$(formResponses).addClass('success');
$(formResponses).text('Subscription complete.');
$('input').val('');
})
.fail(function(data) {
$(formResponses).removeClass('success');
$(formResponses).addClass('error');
$(formResponses).text('Input error. Please review and re-submit.');
}).always(function(data) {
submitButton.removeAttr('disabled');
submitButton.text('Send');
});
});
});
Within the $(form).submit( you're still using $(form), eg
var formData = $(form).serialize();
as form = $('#header-form, #footer-form') any call to $(form) (or just form) will affect/apply to/read from both forms. This depends on what the call is, eg form.attr("action") will always get the action from the first form.
Within the handler, change all $(form) (or just form) to $(this):
var formData = $(this).serialize();
...
url: $(this).attr('action'),
be careful using this inside a callback, so if you do need the relevant form then instead, change to
$('#header-form, #footer-form').submit(function(e) {
var form = $(this);
and continue to use form.
Note that in your code form is already a jquery object, but jquery allows you to "double wrap" - ie $(form) is the same as $($(form))
I recommend you remove the outer form variable completely, ie change to
// set up event listener
$('#header-form, #footer-form').submit(function(e) {
which will help to remove the issue of using form not meaning this form.
I have a page where I'm displaying some information. You can select a option and the page will then display a form by loading the form using ajax response:
$("body").on("change", "#patient_id", function(event){
var prescription_id = $(this).val();
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var curr_data = {
action: 'refferedcall',
prescription_id: prescription_id,
dataType: 'json'
};
$.post(hmgt.ajax, curr_data, function(response) {
$('.prescription_content').html(response);
return true;
});
});
This works fine. But this view is a form. I want to then submit the included form with Ajax as well. But I can't seem to do it. I think it is because if I set up a button handler for the form it doesn't work as the form isn't present when the main page and JQuery script is loaded.
So to be clear, I'm loading this div onto my main page using JQuery and Ajax load. I then want to simply submit this form with Ajax also.
<div class="prescription_content">
<div class="title">Submit News</div>
<form role="form" id="ref_form" name="ref_form_p">
<div class="form-group">
<label for="pat_ref_hosp">Hospital to Refer:</label>
<input type="text" class="form-control" id="pat_ref_hosp" name="pat_ref_hosp" value="<?php if(!empty($result->reffer_hospital)){ echo $result->reffer_hospital; }?>">
</div>
<input type="hidden" class="form-control" id="pres_note" name="pres_note" value="<?php echo $result->priscription_id ;?>">
<button type="button" id="<?php echo $result->priscription_id ;?>" class="btn btn-success reffering_status">Refer Now</button>
</form>
</div>
TIA
Then I submitted form again using ajax through below button click event:
$("body").on("click", ".reffering_status", function(event){
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var prescription_id = $("#pres_note").val();
var pat_ref_hosp = $("#pat_ref_hosp").val();
var curr_data = {
action: 'reffering_status',
dataType: 'json',
prescription_id: prescription_id,
pat_ref_hosp : pat_ref_hosp,
};
console.log(curr_data);
)};
Here is log displaying
Object {action: "reffering_status", dataType: "json", prescription_id: "1", pat_ref_hosp: ""}
pat_ref_hosp is empty
I don't know how to display ajax in jsfiddle
https://jsfiddle.net/3ggq3Ldm/
Yes the way you are doing it will not work because the contents of the DIV you are loading-in is not loaded into the DOM when your initial
$("body").on("click", ".reffering_status", function(event){});
call is made.
If I am understanding you correctly, this is the behaviour you want to achieve:
$("#patient_id").on("change", function(event) {
var prescription_id = $(this).val();
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var curr_data = {
action: 'refferedcall',
prescription_id: prescription_id,
dataType: 'json'
};
$.post(hmgt.ajax, curr_data, function(response) {
$(".prescription_content").html(response);
$(".reffering_status").on("click", function(event){
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var prescription_id = $("#pres_note").val();
var pat_ref_hosp = $("#pat_ref_hosp").val();
var curr_data = {
action: 'reffering_status',
dataType: 'json',
prescription_id: prescription_id,
pat_ref_hosp : pat_ref_hosp
};
console.log(curr_data);
)};
return true;
});
});
You simply need to run the code that attaches your click listener AFTER the DOM has already been updated with the new information.
Please let me know if this code does what you were intending it to.
I know My question Title is not perfectly describe my question extremely sorry about that. I don't know how to tell this as a summery. anyway this is my question.
I am making a admin panel to change some of the content in my web page. this scenario is for change slideshow images.
ok then after someone logged into my page I am loading three pages. like this.
$this->load->view('admin/header');
$this->load->view('admin/menu');
$this->load->view('admin/table_and_editor_holder');
all the page contents I have mentioned below. so basic path is like this. once someone logged he can click the button [slide manage] to load the images and details of already inserted slides. these are getting from a database. so once he clicked the menu button. this jquery function is executing.
$('.menu-item > a').on('click', function() {...})
this function simply getting a html page. filled with previous slide details. this is the controller function handle the menu request.
function slider_edit_delete() {
$sdata['slide_imgs'] = $this->admin_basic_curd->get_all_items('sider_images');
$slide_manager = $this->load->view('admin/slider_manager', $sdata, TRUE);
echo $slide_manager;
}
so previous jquery function is then appending this page content to a div like this.
$('#table_container').html(data);
so inside this page content I have a buttons call edit for each slide already inserted. so by clicking on of this button I can edit that slide image or some test content of it. that button is like this.
<a class="onclick_post_by_a" href="<?php echo base_url() . 'adm_edit_this_slide/' . $sl->id; ?>">
<button class="btn btn-info"> Edit </button>
</a>
so by clicking this button must execute this function in the header section and this function must add a html form (in a separate page) to the #editor-form-container div as previously
$('.onclick_post_by_a').on('click', function() {...})
but the problem is once I click the edit button it couldn't find this function. so it is opening the content as a separate page
How can I make this to work? Thank you
the header page contains all the css and js file links. and some jquery functions. like this.
<script>
$(document).ready(function() {
$('.menu-item > a').on('click', function() {
var url = $(this).attr('href');
var pdata = "";
var rdata = posting_url(url, pdata);
rdata.success(function(data) {
$('#table_container').html(data);
});
return false;
});
$('#editor-form-container').css({
display: "none"
});
function posting_url(url, pdata) {
return $.ajax({
url: url,
data: pdata
});
}
$('.onclick_post_by_a').on('click', function() {
var url = $(this).attr('href');
var pdata = "";
var rdata = posting_url(url, pdata);
rdata.success(function(data) {
$('#editor-form-container').css({
display: "block"
});
$('#editor-form-container').html(data);
});
return false;
});
$('.post_with_image').on('submit', (function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log("success");
console.log(data);
},
error: function(data) {
console.log("error");
console.log(data);
}
});
}));
});
</script>
</head>
then I have load menu page. it is like this.
<div class="admin-navi">
<div class="menu-item">
Home
</div>
<div class="menu-item">
Side Manage
</div>
</div>
<div class="clearfix"></div>
table_and_editor_holder.php page. it is like this.
<div class="col-lg-12">
<div class="col-lg-2"></div>
<div id="table_container" class="col-lg-8">
</div>
</div>
<div id="editor-form-container" class="col-lg-6">
</div>
Dynamically created element does not respond to direct call to events like below -
$('.onclick_post_by_a').on('click', function() {...})
So you have to write like this
$(document).on('click', '.onclick_post_by_a', function() {...})
Just try it out.
So, I'm trying to make a row containing a delete button to .hide after pressing delete.
The problem is.. The delete button submits a form, I can't pre-define my button class/ID because it's beeing echo'd multiple times (php script reads a dir, then puts all files in a table)
this is the current script, It does post the form in the background, But it doesn't hide the element, I tried some stuff myself but the script then ended up hiding all the buttons on the page or it won't work at all..
The button beeing echo'd:
echo "<input type='submit' value='delete' name='submit'>";
The Script behind it:
$("#delform").submit(function() {
var url = "../../setdel.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#delform").serialize(), // serializes the form's elements.
success: function(data)
{
// location.reload(); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
Catch the button's onclick instead of catching the submission. Example:
echo "<input type='submit' value='delete' name='delete' class='trigger_delete'>";
// ^^ don't name your buttons as submit
// it will conflict to .submit() method
The on JS:
$('.trigger_delete').on('click', function(e){
e.preventDefault(); // prevent triggering submit
var url = "../../setdel.php";
$.ajax({
type: 'POST',
url: url,
data: $("#delform").serialize(),
success: function(response) {
console.log(response);
$(e.target).closest('tr').hide(); // or .fadeOut();
}(e) // <--- this one
});
});
I am trying to display data after being submitted with ajax. The ajax works so far when submitting, but I have to refresh to see it.
Here's the jquery:
$('#submit-quote').live("submit", function(){
var formdata = $(this).serialize();
$.post("add.php", formdata, function(data) {
console.log("success");
});
return false;
});
The php in add.php:
require('includes/connect.php');
$quote = $_POST['quote'];
$quotes = mysql_real_escape_string($quote);
echo $quotes . "Added to database";
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
Here's the HTML/PHP that I use to fetch the data and display it:
<?php
require("includes/connect.php");
$result = mysql_query("SELECT * FROM entries", $link);
while($row = mysql_fetch_array($result)){ ?>
<div class="quote-wrap group">
<span>Like</span>
<div class="quote">
<p>
<?php echo htmlentities($row['quote']); ?>
</p>
</div><!-- /.quote -->
</div><!-- /.quote-wrap -->
<?php } ?>
If needed, here's the form:
<form id="submit-quote" method="post" >
<h2> Submit A Quote </h2>
<textarea name="quote">
</textarea>
<input type="submit" name="submit" value="Submit!">
</form>
Ajax works when submitting, but I need to display it after being sent also, how can I do this?
The data variable in your success callback function stores the server response. So to add the server response to the DOM:
$(document).delegate("'#submit-quote'", "submit", function(){
$.post("add.php", $(this).serialize(), function(data) {
$('.inner').append('<div class="quote-wrap group"><span>Like</span><div class="quote"><p>' + data + '</p></div></div>');
});
return false;
});
If you need to use event delegate (e.g. the form isn't always present in the DOM) then use .delegate() instead of .live() as the latter has been depreciated as of jQuery 1.7.
Also you don't really need to cache $(this).serialize() in a variable since it is only being used once (creating the variable is unnecessary overhead).
Since your PHP code is outputting echo $quotes . "Added to database";, the server response will be the quote with "Added to database` appended to the string, which will be added to your list of quotes.
UPDATE
$(document).delegate("'#submit-quote'", "submit", function(){
var quoteVal = $(this).find('[name="quote"]').val();
$.post("add.php", $(this).serialize(), function() {
$('.inner').append('<div class="quote-wrap group"><span>Like</span><div class="quote"><p>' + quoteVal+ '</p></div></div>');
});
return false;
});
Notice that I am no longer referencing the server response (in fact I removed the data variable all together). Instead I am saving the value of the name="quote" element within the form being submitted and using it after the AJAX request comes back (this way the quote is added to the database before being added to the DOM). You could move the .append() code outside the success callback to run it right as the form is submitted (in the submit event handler).
UPDATE
If you want to create a DOM element to append rather than concocting a string:
$(document).delegate("'#submit-quote'", "submit", function(){
var quoteVal = $(this).find('[name="quote"]').val();
$.post("add.php", $(this).serialize(), function() {
//create parent div and add classes to it
$('<div />').addClass('quote-wrap group').append(
//append the "like" span to the parent div
$('<span />').text('Like');
).append(
//also append the .quote div to the parent div
$('<div />').addClass('quote').append(
//then finally append the paragraph tag with the quote text to the .quote div
$('<p />').text(quoteVal)
)
//then after we're done making our DOM elements, we append them all to the .inner element
).appendTo('.inner');
});
return false;
});