Rebind dymanically created forms after jQuery ajax response - php

I'm kinda new to jQuery but understand it for the most part. My problem is that when my ajax call which refreshes the entire div is done, all my dynamically created forms don't work. If you try and submit them, the event doens't work properly and just tries to do a normal form submit. I have all the other items such as links bound using the .live() which seem to work great. Just the form dies.
How do I rebind the dynamically created forms after the ajax call? They all have id of formname_id. I tried to use bind but it doesn't work as below. Any help is appreciated.
Here is the code
jQuery(document).ready(function(){
jQuery("form[id^='commentform_']").each(function(){
var id = parseInt(this.id.replace("commentform_", ""));
jQuery(this).bind('submit', function(e) {
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: "action="+ action +"& act_id="+ act_id,
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
return false;
});
});
});

Try doing something like this:
jQuery("form[id^='commentform_']").live('submit',function(){
var id = parseInt(this.id.replace("commentform_", ""));
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: {"action": action, "act_id": act_id},
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
return false;
});
No need to loop over the forms to bind to them. If you can use delegate instead of live do so.

Why don't you over-ride the normal form submit:
function addNewitem() {
$('#new_item_form').submit(function() {
$.get("includes/ItemEdit.php", {
newItem: true
},
function(msg) {
isNewItem = true;
$("#new_item").hide();
$('#item_list').hide();
$("#item_edit").html( msg );
$("#item_edit").show();
editActiveEvent();
});
return false;
});
}
Don't forget to return false. or do a .preventDefault

I have gotten this to work adding the event in the function call and using event.preventDefault(); BUT of course only in FF. Doesn't work in IE7..
jQuery("form[id^='commentform_']").live('submit',function(event){
var id = parseInt(this.id.replace("commentform_", ""));
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: {"action": action, "act_id": act_id},
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
event.preventDefault();});
But IE7 still tries to sumbit the action. arrgggh.. Anything I'm doing wrong??

Related

Form loaded via ajax wont append data to parent window

So I am basically creating a Restaurant Menu editor for their website. The issue I am having is when the click a category named Brunch, I load the file edit_cat.php via ajax onto the page. All data is passed correctly, but on success of the form being filled out I would like to post a success message on the parent window and am having no luck. Coincidentally, upon success the alert(data) does popup with the response.
edit_cat.php both handles the form submission and is the form
$(document).ready(function(){
$('.editBtn').on('click', function(e) {
e.preventDefault();
var $this = $(this),
id = $this.data('id'),
type = $this.data('type');
if (type == 'cat') {
data = "&cat=" + id;
$.ajax({
data: data,
type: 'POST',
url: 'edit_cat.php',
success: function(data) {
$('#contentLeft').html(data);
}
});
}
});
$('#contentLeft').on('click', 'input[type="submit"]', function(e) {
e.preventDefault();
var $this = $(this),
frm = $('#edit-cat-frm'),
id = $('form').data('id'),
name = $(frm).find('input[name="name"]').val(),
desc = $(frm).find('textarea[name="desc"]').val(),
send = $(frm).find('input[name="submit"]').val();
data = "&cat=" + id + "&name=" + name + "&desc=" + desc + "&submit=" + send;
$.ajax({
data: data,
type: 'POST',
url: 'edit_cat.php',
success: function(data) {
window.parent.$('.left-container-head').innerHtml(data);
}
});
});
});
Can you please try this as simply,
$('.left-container-head').html(data);
Try this:
$(".left-container-head", window.parent.document).html(data);

jquery ajax: how to keep record not dissapear when the page is refresh

i use this script
<script type="text/javascript">
$(function () {
$(".comment_button").click(function () {
var element = $(this);
var boxval = $("#content").val();
var dataString = 'content=' + boxval;
if (boxval == '') {
alert("Please Enter Some Text");
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "update_data.php",
data: dataString,
cache: false,
success: function (html) {
$("ol#update").prepend(html);
$("ol#update li:first").slideDown("slow");
document.getElementById('content').value = '';
$("#flash").hide();
}
});
}
return false;
});
$('.delete_update').live("click", function () {
var ID = $(this).attr("id");
var dataString = 'msg_id=' + ID;
if (confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete_data.php",
data: dataString,
cache: false,
success: function (html) {
$(".bar" + ID).slideUp('slow', function () {
$(this).remove();
});
}
});
}
return false;
});
});
</script>
this script combine live update and delete record using jquery and ajax
the problem is when I refresh the page, the record will disappear .. how to keep records that show up are not dissapear when the page is reloaded?
First Check the comment list. Did you put any limit in query, if so then use Order by Primary ID desc.So it would display latest records first.
When you delete any record, check whether it is actually deleted from database or not. Because you are not checking whether record actually deleted or not as per the code you given.
Assuming you are using update_data.php and delete_data.php to manipulate some database, you could use PHP to render the page initially using the data that is currently on the database.
If that is not the case, and you don't have access to that database (it could be a third party web service, right?), or you don't want to do that for any reason, you could use cookie like Saeed answered.

jQuery, ajax multiple checkboxes into $_POST array

I'm trying to send $_POST data to another page to add sessions for a simple shopping cart.
I have a multiple forms within a PHP while loop each with multiple checkboxes, everything works apart from the checkboxes.
My question is how do I change this piece of code to change "item_extras" into an array?
if(this.checked) item_extras = $(this).val();
I have tried the following but, this just creates one line with all the values instead of another row within the array. If this is too confusing I could create a sample if it helps.
if(this.checked) item_extras += $(this).val();
$('form[id^="add_item_form"]').on('submit', function(){
//alert("On Click Works");
event.preventDefault();
addItem($(this));
});
function addItem(ele) {
//alert("I'm in the addItem Function");
var item_id = ele.parent().parent().find("input[name=item_id]").val(); // get item id
var item_name = ele.parent().parent().find("input[name=item_name]").val(); // get item name
var item_options = ele.parent().parent().find('#options').val(); // get selected option
var item_extras = "";
$item_extras = ele.parent().parent().find('input[name^="extra"]'); // find all extras
$item_extras.each(function() {
if(this.checked) item_extras = $(this).val(); // how do i make this into an array???
});
alert("BEFORE AJAX");
var dataString = 'item_id=' + item_id + '&item_name=' + item_name + '&item_options=' + item_options + '&item_extras[]=' + item_extras;
alert(dataString);
$.ajax({
type: "POST",
cache: false,
url: "includes/cart.php",
data: dataString,
success: function () {
$.ajax({
url: 'includes/cart.php',
success: function(data) {
$('#cart').html(data);
alert("AJAX SUCCESS");
}
});
}
});
return false;
}
you can use serialize method. Form.serialize()
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
var data = $(this).serialize();
});

When I use jQuery AJAX to submit tinyMCE forms on my page, it takes two clicks to actually submit to database

I've been trying different options for over a week now and nothing seems to work. What makes this slightly more complicated is that I have multiple forms on the page that all need to be tied to this same submit function. They all have different IDs.
The following is a simplified version of my jQuery:
$('form').on('submit', function(form){
var data = $(this).serialize();
$.ajax({
type: 'POST',
cache: false,
url: 'inc/process.php',
data: data,
success: function(){
// The following fires on first AND second submit
console.log("Updates have successfully been ajaxed");
}
});
return false;
});
I have also tried using $('form').submit() with the same results.
Relevant sections of process.php:
$query = 'UPDATE pop_contents
SET ';
$id = $_POST['content_id'];
/* to avoid including in MySQL query later */
unset($_POST['content_id']);
$length = count($_POST);
$count = 0;
foreach($_POST as $col => $value){
$value = trim($value);
$query .= $col."='".escapeString($value);
// don't add comma after last value to update
if(++$count != $length){ $query .= "', "; }
// add space before WHERE clause
else{ $query .= "' "; }
}
$query .= 'WHERE id='.$id;
$update_result = $mysqli->query($query);
After much hair pulling and swearing, I've solved the problem.
TinyMCE editor instances do not directly edit textareas, so in order to submit the form, I needed to first call tinyMCE.triggerSave() from the TinyMCE API. So, the working code looks like this:
$('form').on('submit', function(form){
// save TinyMCE instances before serialize
tinyMCE.triggerSave();
var data = $(this).serialize();
$.ajax({
type: 'POST',
cache: false,
url: 'inc/process.php',
data: data,
success: function(){
console.log("Updates have successfully been ajaxed");
}
});
return false;
});
I was confused when i pass the Ajax String data via tinyMce ..but it is not save to database with php...then i use the
tinyMCE.triggerSave();
event.preventDefault();
then fine.........
$("#save").click(function() {
tinyMCE.triggerSave();
event.preventDefault();
var data = $(this).serialize();
var position = $("#position").val();
var location = $("#job_location").val();
|
|
|
|
var end_date = $("#end_date").val();
var dataString = '&position='+ position + '&job_location=' + location + '&job_category=' + category + '&job_des=' + job_des +'&job_res='+ job_res + '&job_requ='+ job_requ + '&start_date='+ start_date + '&end_date='+ end_date;
alert(dataString);
$.ajax({
type: "POST",
url: "regis.php",
data: dataString,
success: function(data){
}
});
return false;
});
i believe the problem is that you don't prevent the default action of the form. try this
$('form').bind( 'submit', function(event) {
event.preventDefault(); // added
console.log("Binding"); // changed to console.log
$.ajax({
type: "POST",
url: "inc/process.php",
data: $(this).serialize(),
success: function() {
console.log("Your updates have successfully been added."); // changed to console.log
}
});
});
Another neat trick to go along with this is setting the progress state on the tinymce editor, giving you a very simple way to add a loading icon. This article in the TinyMCE docs explains how to do that.
Also from that article, using ed.setContent() will allow you to set the text showing in the editor. I used it to blank the editor, but only after a successful post.

Unresponsive Fade-In Fade-Out in Jquery

I am implementing a twitter-style follow/unfollow functionality with the following jquery.
$(function() {
$(".follow").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$("#loading").html('<img src="loader.gif" >');
$.ajax({
type: "POST",
url: "follow.php",
data: info,
success: function(){
$("#loading").ajaxComplete(function(){}).slideUp();
$('#follow'+I).fadeOut(200).hide();
$('#remove'+I).fadeIn(200).show();
}
});
return false;
});
});
I have a similar unfollow function. However i have the following problem:
When I have N items {1,2..i.N} each with id = followi and I click on the follow button. I find that some of the items respond while others do not. I suspect it is a pure javascript issue...otherwise i figure none of the buttons would respond at all.
Is it a timing issue...all help is appreciated. Also i'd appreciate it if you could point me to a simpler method.
Thanks!
Well you are doing the UI update in your ajax success handler, so the reaction time for the UI updated is based on the speed of the Ajax response. And if the server doesn't return successfully, the UI update won't happen at all.
A simpler method with instant response:
$(function() {
$(document.body).delegate(".follow","click",function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$("#loading").html('<img src="loader.gif"/>');
$('#follow'+I).fadeOut(200); // act instantly since we assume it will go well
$('#remove'+I).fadeIn(200); // act instantly since we assume it will go well
$.ajax({
type: "POST",
url: "follow.php",
data: info,
complete: function(){ //always remove the loader no matter if it goes well or not
$("#loading").slideUp();
},
error: function() {
//handle error
$('#follow'+I).fadeIn(200); // correct mistake
$('#remove'+I).fadeOut(200); // correct mistake
}
});
return false;
});
});

Categories