Very brief, this is my php code in myPage.php:
<div class="table-responsive" id="items">
<table class="table" id="myTable">
<thead><tr><th>item<th>status<th>options</thead>
<tbody>
[...]
echo "<tr><td>$item<td>$status<td>to-be-added
[...]
echo "<tr><td colspan='3'>";
echo "<form method='post' id='newitem'>";
echo "<input type='hidden' id='uid' name='uid' value='$uid'>";
echo "<div><button type='submit' class='btn btn-info' id='submitbtn'>new item</button></div>";
echo "</form>";
[...]
And this is my .js file ajax code:
$(document).ready(function () {
$('form').submit(function (event) {
$('#errors').remove(); // remove the error text
$('#success').remove(); // remove the success text
var formData = $("#newitem").serialize();
$.ajax({
type: 'POST',
url: 'process.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
console.log(data);
if (!data.success) {
$('form').append('<div id="errors" class="alert alert-warning"></div>');
if (data.errors.validitem) {
$('#errors').append('<p>' + data.errors.validitem + '</p>');
}
} else {
$('#addresses').append('<div id="success" class="alert alert-success">' + data.message + '</div>');
$("#myTable").load("mypage.php #myTable");
}
})
.fail(function (data) {
console.log(data);
});
event.preventDefault();
});
});
I Don't show the process.php function as that is not most likely the problem.
When I first load the page and press submit following things happen:
a new item is created via ajax
table gets populated with new entry w/o page refresh but using the load option: *$("#myTable").load("mypage.php #myTable");*
in conclusion, everything works as expected!
Note: only after I add the table load the problem appears. $("#myTable").load("mypage.php #myTable");
Without this reload of the table after submit, submit always work, just that the table doesn't show real time the changes and I need to do F5 ... which is not the plan.
After the load of the table, when I press the button again, nothing appears to happen, except that my success message disappears.
At this stage I need to press the button twice. Only after I press submit a second time, the ajax executes ok and table shows the new item created.
This behavior is consistent for all next submits. All execute only after second submit.
I need some help here please. What is happening?
I want to reload only a section of the myPage.php, so only the full table #myTable or whole div #items, with all the validation functions I have in myPage.php
I don't want to recreate full table in the process.php and send it over via POST as I have seen some recommend in other forums.
The issue is here : $("#myTable").load("mypage.php #myTable");
mypage.php is your main page. And you load it once. Then, inside the table, you use that .load() to overwrite it all. Which is no good.
You then have a brand new table where no handler is binded to the submit button. So on submit button click (second time), the form is submitted using the "normal behavior" of a <form> element... And the page is fully reloaded.
As a possible solution, I would use .load() on the form... Not the table, like this:
$("#newitem").load("mypage.php #newitem");
But you should try $("#newitem").reset() and just remove #error and #success... Instead of that .load().
EDIT
Second taugth:
Try $(document).on("submit", "form", function (event) {
instead of $('form').submit(function (event) {
That is delegation... So your submit button always will be binded to the function, even if it is overwritten.
Related
I have this code bellow and I need it to make a post inside a div.
<script type="text/javascript">
$(function() {
$(".loader").click(function(event) {
event.preventDefault(); // stop the link loading the URL in href
$('#content').load($(this).attr('href'));
});
});
</script>
<form method="post">
some random inputs and checkbox's goes here
<input type="submit" href="/consulta/consulta_produto.php" class="loader" value="Consultar">
</form>
When submiting, the javascript is sucessfully loading the consulta_produto.php inside a div called "content", however, I need to adapt the script to make it possible to POST too
Someone at other topic said to Use $(".loader").parent("form").submit instead of $(".loader").click, however i didnt understood what he meant, I tried changing it in a lot of different ways, but none of them worked
I researched a few topics about how to post with javascript, but I could adapt none of them to keep the function to load consulta_produto.php inside the div "content"
So I wonder, how can I adapt my javascript to keep loading consulta_produto.php inside content div while posting the data from some inputs and check boxs?
First of all, you need to either:
Place all of your <script> code after the relevant HTML has been loaded, OR
Wrap it all in a $(document).ready(function() {...}); to achieve the same effect
Then, instead of executing code at your inputs click() event, you can do it upon your forms submit() event. (This is basically what you mentioned someone told you in another topic). I changed your submit input to a submit button, doesn't really matter.
So, instead of loading the href attribute, you load the action attribute of the form itself into the div.
Of course you want to submit actual data along with the form - no problem. You just use an AJAX method. This is in order to stop the page from reloading.
First you do the preventDefault() to stop the usual page reload. Then you initialize the $.ajax() method.
Data: The first parameter 'data' contains all the form data to pass
along.
Type: Represents the type of request (POST)
URL: This is the form action (/consulta/consulta_produto.php).
Success: Finally, the 'success' parameter contains a function
which loads it all into the specified <div>.
AJAX is essential when avoiding page reloads in PHP, play around with it!
<script type="text/javascript">
$(document).ready(function() {
$("#form").submit(function(event) {
event.preventDefault();
$.ajax({ //AJAX Method
data: $(this).serialize(), //Gets data from form
type: $(this).attr('method'), //Gets the method, in your case POST
url: $(this).attr('action'), //Gets the form action
success: function(r) {
$('#content').html(r); //Loads data into div
}
}); //End of AJAX Method
}); //End of form submit event
});
</script>
And here is your HTML:
<div id="content" style="width:100%; height:500px; ">
</div>
<form id="form" action="/consulta/consulta_produto.php" method="post">
some random inputs and checkbox's goes here
<button type="submit">Consultar<button>
</form>
I have a small issue which I can't seem to fix for 3 days. I don't think it
is a code error but my understanding variables and why onClick event doesn't (work) properly
Basically I have a page a table and many rows in it. Each row has comment icon, and when you clicked on this icon, a jquery modal opens up with a textarea and your write your
comment press submit (on the modal) and the comment is sent via ajax.
Everything works except:
The problem is that if I have 10 rows, and without refreshing/reloading the page if I open each of those 10 icons in
one by one, submit my comment, all comments get inserted in the first row.
It is as if, If I open the first popup and submit and when I open a second popup then something about the first popup
is being persisted.
Here is an example code.
this is a simple code to represent the modal
<!-- very minimilized example because the modal has no issues -->
<div class="modal fade" id="comment-viewer">
<input type="comment" name="" id="my-comment">
<input type="button" name="submit" class="btn-primary">
</div>
the table with rows and comment icon that triggers the modal to show (onclick)
<table>
<td><i class="title_row_id_1" onClick="open_comment_modal(this)" data-id="1"></i> </td>
<td><i class="title_row_id_2" onClick="open_comment_modal(this)" data-id="2"></i> </td>
<td><i class="title_row_id_3" onClick="open_comment_modal(this)" data-id="3"></i> </td>
<td><i class="title_row_id_4" onClick="open_comment_modal(this)" data-id="4"></i> </td>
<td><i class="title_row_id_5" onClick="open_comment_modal(this)" data-id="5"></i> </td>
</table>
a function to open modal, and send submitted content to php file
function open_comment_modal(e){
var id = e.dataset.id
// code to display the modal goes here. (has no issues)
$('.btn-primary').click(function(){
var comment = $("#my-comment").val()
var dataString = "id=" + id + "&comment=" + comment
ajaxRequest = jQuery.ajax({
type: "POST",
url: "foo.php",
data: dataString,
success: function(response) {
$("#my-comment").val('') // no effect
}
});
$("#my-comment").val('') // no effect
})
$("#my-comment").val('') // no effect
}
So, in the above example it on each comment icon press it should update the id, get the comment
and send it to db.
But all it does is insert into the database all comments with the 'id' of the first opened comment.
I have disabled caching but nothing still
It's simply because of the id variable scope issue. You are attaching the click handler inside the open_comment_modal method. which you should not. Instead of this you should attach the click handler out side of that function and get the id from the dom dataset inside the click handler.
Second try ;). Please try to change open_comment_modal(e) like:
function open_comment_modal(e){
var id = e.dataset.id
// code to display the modal goes here. (has no issues)
$('.btn-primary').off('click');
$('.btn-primary').click(function(){
...
Because everytime you call open_comment_modal, you append another click handler to the .btn-primary and the old ones are still there. So you have to clear the previous (not valid) handler, before you attach new one.
You need to reset the fields when the popup is closed and repopulate the fields with new values when the modal is shown again.
For example suppose when you close the popup your comment box must be emptied like this
$("#comment-viewer").on("hidden.bs.modal", function () {
$('#my-comment').val('');
});
hope you understand the point..
You need to reset the text once modal is open and read the text once submit button is clicked.
Here is the updated code
var _Id;
var _comment;
function open_comment_modal(e){
_Id = e.dataset.id;
$("#my-comment").val('');
// code to display the modal goes here. (has no issues)
}
$( document ).ready(function() {
$('.btn-primary').click(function(){
_comment = $("#my-comment").val();
var dataString = "id=" + _Id + "&comment=" + _comment
ajaxRequest = jQuery.ajax({
type: "POST",
url: "foo.php",
data: dataString,
success: function(response) {
$("#my-comment").val('');
// code to hide the modal goes here.
}
});
});
});
I've copied a working jQuery form from one page to another, the original works as intended but the duplicate does not.
The original works like so:
So i have an onclick function attached to an image which opens up a confirmation modal window with an "OK" button (aka) my submit button, pressing this submits a post function, closing the window and creating a post on another page (the main page).
I've copied this working form to my main page so users wouldn't have to travel to the above mentioned page to accomplish this task. However, upon clicking the "OK" button on the duplicated form, it closes the window and refreshes the page, but the post function does not seem to be triggering.
The code is below:
<script>
jQuery(function (){
jQuery('#form-bumb .button-waiting, #form-bumb .waiting-updated').hide();
jQuery('#form-bumb').submit(function (e){
e.preventDefault();
//product_id
jQuery('#form-bumb .waiting-updated').hide();
jQuery('#form-bumb .button-waiting').show();
jQuery.ajax({
url : the_ajax_script.ajaxurl,
type : 'post',
data : {
action : 'product_bump',
product_id : <?php echo $product_id; ?>
},
success : function( response ) {
jQuery('#form-bumb .button-waiting').hide();
jQuery('#form-bumb .waiting-updated').show();
jQuery('#form-bumb button[type=submit]').hide();
remaining_bump = jQuery('.products-total-wrap #products-total-bumps').text();
if (remaining_bump > 0){
remaining_bump = parseInt(remaining_bump) - 1;
jQuery('.products-total-wrap #products-total-bumps').text(remaining_bump);
}
}
});
});
jQuery('#modal_product_message_confirmation h4.modal-title').html('Bump Confirmation '+
'<img src="<?php echo get_template_directory_uri();?>'+
'/assets_consumer/assets/img/bump-icon.png" width="20" />');
});
</script>
I have no idea what the problem is, if anyone would be so kind to point me in the right direction it would be greatly appreciated.
perhaps your form is generated dynamically and #form-bumb doesn't exist at time of running jQuery('#form-bumb').submit(function (e){....})
you should try instead
$(document).on('submit','#form-bumb',function(e){....})
which will also work on the form if it's dynamically created
i have run into a little issue for closing a data modal with bootstrap i have showed a bit of code below basically at the current stage the ajax validates the form via the input submit field this works however it doesn't close the modal it resides in
so my question how can i utilize the same ajax code but allowing the data modal to close on submission please bare in mind the modals id is webapp_customers_modal but is dynamic with a number on the end as its used in multiple places
this is the preferred method i would like to use but doesn't submit the form
<button type='submit' data-dismiss='modal'data dismiss='modal'>Save</button>
This is the current form submit im using this works but doesn't close the modal
<input type='submit' class='btn btn-info' value='Save' >
this is the ajax code
<script>
$(function() {
$('form.frm_details').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: '/limitless/functions2.php',
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
if(data.status == '1')
{
$('#info').addClass('alert alert-danger no-border').html(data.message);
}
if(data.status == '2')
{
$('#info').addClass('alert alert-danger no-border').html(data.message);
webapp_get_customers();
}
}
});
});
});
</script>
If you only have one of your modals open at a time you can add a common class, like my-modals to them and then use this in you script. This way you don't need to keep track of your dynamic created id's.
$('.my-modals').modal('hide');
Why not close modal using javascript? Give your modal an Id
$('#myModal').modal('hide'); //This closes modal with id 'myModal'
PS: you can add the above code inside success callback.
In a div on my page called total_records is a database field binding which counts up the total records submitted. i use jquery for the submission so the page doesn't refresh when i click on the button. But i'm only able to get the total records submitted when i refresh the page or press F5. i know there a way out to add 1 to the binding on the page on button click but i don't know how. this is the jquery i use for the submission
$(document).ready(function(){
$("#form2").on('submit',function(event){
$("#comment_loader").fadeIn(); //show when submitting
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "insert.asp",
data: data
}).success(function(msg) {
$('#new_entry').html(msg);
$("#comment_loader").fadeOut('fast');
$("#msg_div").append("<div class='messages' style='border:1px purple solid; padding:2px; margin:5px;'>Your comment has been saved </div>");
setTimeout(function() {
$(".messages").fadeOut(function(){
$(".messages").remove();
});
}, 3000);
$("input[type=text]").val("");
});
});
});
Either you can have have the insert.asp script return the total number of records submitted or within success you can call the script that runs the appropriate query and in either case you can use jQuery to update the div with the number returned:
$('div.total_records').text( 'number-of-records-submitted' );
If you do it this way you would not need to refresh the page.