Dynamically created form submitting with preventDefault - php

I have a page that lists a bunch of items with add to cart buttons, the user clicks the button it fires AJAX which adds the item to the php cart and adds the item to the sidebar for a visual cue of what's in the cart, with a remove button. Problem is, when i click the remove button it refreshes the page even though i have prevent default attached to the function
This works
$(document).ready(function(e) {
$('.additem').click(function(e) {
e.preventDefault();
$(this).html('Added').attr('disabled' , true);
$(this).closest('form.form_add').submit()
});
$('form.form_add').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "buy-page-handler.php",
data: $(this).serialize(),
dataType: "json",
success: function(result) {
var id = result.id;
var name = result.name;
var qty = result.qty;
var price = result.price;
$('#sidebar').append('<div class="cart_cont">'
+'<div class="desc">'+name+' '+price+'</div>'
+'<div class="remove">'
+'<form method="post" class="form_delete">'
+'<button type="submit" class="removeitem">Remove</button>'
+'<input type="hidden" name="id" value="'+id+'">'
+'<input type="hidden" name="item-remove" value="true">'
+'</form>'
+'</div>'
+'</div>');
}
});
});
This doesn't work
$('.removeitem').click(function(e) {
e.preventDefault();
$(this).closest('.form_delete').submit()
});
$('.form_delete').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "buy-page-handler.php",
data: $(this).serialize(),
success: function() {
alert("success")
}
});
});
This is my first attempt at using the jquery/ajax/php combination, so i'm sure its a bit rough.
Any help would be greatly appreciated.

The issue is that your class="removeitem" elements are added dynamically after the DOM is ready, so your new elements are not bound to $('.removeitem').click(). Try binding it by delegating to the parent -
$('#sidebar').on('click', '.removeitem', function(e) {
e.preventDefault();
$(this).closest('.form_delete').submit()
});

Just change:
<button type="submit" class="removeitem">Remove</button>
to:
<button type="button" class="removeitem">Remove</button>

Related

How to send AJAX request from a <form> created by jQuery

I have a jQuery textarea from where I am posting form values with a button. I don't want to refresh the page and use AJAX for this purpose so that the page does not get refreshed. I have tried a lot but the solution does not seem to be coming out. Here is my code for the same. Any insight will be really helpful.
Here is my code,
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.click_notes').on('click',function(){
var tid = $(this).data('question-id');
$(this).closest('ul').find('.demo').html("<div class='comment_form'><span onclick='$(this).parent().hide()'><b>X</b></span><form id = 'contactForm1' action='submit.php' method='post'><textarea required cols ='50' class='span10' name='notes' rows='6'></textarea><br><input class='btn btn-primary' id = 'submitnotes' name= 'submit_notes' type='submit' onclick = 'submitform()' value='Add Notes'><input type='hidden' name='submitValue' value='"+tid+"' /></form><br></div>");
});
});
</script>
<script type="text/javascript">
function submitform() {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
}
</script>
To achieve this hook to the submit event of the form itself, not the click event of the submit button. Also note that you shouldn't be using on* event attributes. As the HTML content of the form is dynamically appended to the DOM you can use a delegated event handler on both the form and span instead. Try this:
$(document).ready(function() {
$('.click_notes').on('click', function() {
var tid = $(this).data('question-id');
$(this).closest('ul').find('.demo').html('<div class="comment_form"><span><b>X</b></span><form id="contactForm1" action="submit.php" method="post"><textarea required cols="50" class="span10" name="notes" rows="6"></textarea><br><input class="btn btn-primary" id="submitnotes" name="submit_notes" type="submit" value="Add Notes"><input type="hidden" name="submitValue" value="' + tid + '" /></form><br></div>');
});
$(document).on('submit', '#contactForm1', function(e) {
e.preventDefault();
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function(data) {
console.log('Submission was successful.');
console.log(data);
},
error: function(xhr) {
console.log('An error occurred.');
console.log(xhr);
},
});
}).on('click', 'span', function() {
$(this).parent().hide()
});
});
Also note that you're including two versions of jQuery, one of which (1.6.1) is getting nearly 8 years out of date. I'd suggest using a single reference to jQuery 3.3.1 instead.

On button click perform ajax for sending values in forms are in while loop

How can I send input values through AJAX on button click? My code is below. Thanks in advance.
while
{
<form class="commentform">
<input type="hidden" class="proid" name="proid" value="<?=$rr['id']?>">
<input type="text" class="form-control" name="comval" placeholder="Write a comment.." autocomplete="off">
<button class="btn btn-post" type="button">Post</button>
</div>
</form>
}
$(document).ready(function() {
$(document).on('click', '.btn-post', function(){
var thePostID = $(this).val;
$.ajax({
url: 'fetch_comments.php',
data: { postID: thePostID },
type: 'POST',
success: function() {
alert(data);
}
});
Firstly, the correct method is $(this).val(), not just $(this).val.
Secondly, you can simplify your code by getting the data from the closest form element using serialize(). Try this:
$(document).on('click', '.btn-post', function() {
var $form = $(this).closest('form');
$.ajax({
url: 'fetch_comments.php',
data: $form.serialize(),
type: 'POST',
success: function() {
alert(data);
}
});
});
$("form").serialize();
Serialize a form to a query string, that could be sent to a server in an Ajax request.

Trying to hide specific div in jquery in php while loop

I have this form being outputted from a PHP while loop :
echo '<div id="postCont" class="postCont'.$pid.'" style="block;">
<div id="clLink">
<a id="clLink" href="'.$plink.'" target="_blank"" title="'.$ptitle.'">'.$ptitle.'</a>
</div>
<div id="clDate">Posted on '.$pdate.'</div>
<div id="clDesc">'.$pdesc.'</div>
<form method="post" class="ibadForm">
<input type="hidden" name="id" value="'.$pid.'">
<input type="hidden" name="hiddenBad" value="yes">
<input type="image" src="../img/bad.png" name="subBad" value="Bad" class="bad">
</form>
</div>';
I am trying to remove the individual .postCont when the ibadForm is clicked with jquery.
$(".ibadForm").submit(function(e) {
var url = "add_form.php";
var id = <?php echo $pid?>;
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data)
{
$('.postCont' + id).hide();
}
});
e.preventDefault();
});
It submits the form to add_form.php fine but doesn't hide the postCont. If I remove the id from the class then it hides all post Cont's. Can anyone tell me where I am going wrong?
You could use closest() to get the parent div then hide it using hide() method like :
$(".ibadForm").submit(function(e) {
var url = "add_form.php";
var id = <?php echo $pid?>;
var _this = $(this);
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data)
{
_this.closest('.postCont').hide();
}
});
e.preventDefault();
});
NOTE : You should store the $(this) object that refer to the clicked form in some variable (_this in my example) then use it inside the success callback since $(this) inside callback doesn't refer no more to the form, e.g :
_this.closest('.postCont').hide();
Hope this helps.

how to hide a button after clicking it and calling a php page

Why its not working ?
I want to hide a submit button after it is clicked and also run a php page in the background at the same time to insert the entry into the table. How both these functions can be accomplished at the same time ?
function click(){
$(".hide").hide();
$.ajax({
type: "POST",
url: "onProfile.php",
dataType: 'html',
data: {data you want to send},
success: function(data){
}
});
return false;
}
<input type="submit" onClick="click()" class="hide" value="Submit">
Add an id to your button called: submit. Then no need to add the onclick. (Or you can use the $('.hide') selector.)
<input type="submit" class="hide" value="Submit" id="submit">
After this, you can check the click:
$('#submit').click(function(e) {
e.preventDefault();
$(this).hide();
$.ajax({
type: "POST",
url: "onProfile.php",
dataType: 'html',
data: {data you want to send},
success: function(data) {
}
});
});
The input element has a function click and is called instead of your click function, easiest solution is to change the name of your function.
A better solution would be to not use inline event handling
$(".hide").on('click', click);
success: function(){
$(button).hide();
}

Ajax post form working 2 times then reloads page with a get URL

I am working on a login form that gets loaded inside a div (parent of .messageboxcontent) with .load on a button press. It all works till the 3rd time I press submit where the div disappears again (I guess by reload of the page and the div CSS is hidden). The URL has the $_POST data added after the 3rd submit (?username=<whatever_I_Fill_In_As_3rd>).
<div class="messageboxcontent">
<form id="ajaxform">
<table>
<tr>
<td>Gebruikersnaam: </td><td><input type="text" name="username" /></td><td>
</tr>
</table>
<input type="submit" value="Registreer" id="submit" />
</form>
</div>
<script>
$('form').on('submit', function( event )
{
var dataString = $(this).serialize();
event.stopPropagation();
//event.preventDefault();
$.ajax(
{
type: "POST",
url: "register.php",
data: dataString,
success: function(response)
{
$('.messageboxcontent').html(response);//FIXED by changing .messageboxcontent to parent.
}
});
return false;
});
</script>
I tried different kind of approaches like:
$('form').submit(function(event) {
//..
}
//
$('#ajaxform').submit(function(event) {
//..
}
//
$(document).ready(function()
{
$("#ajaxform").on("submit", function( event )
{
var dataString = $(this).serialize();
//event.stopPropagation();
event.preventDefault();
$.ajax(
{
type: "POST",
url: "register.php",
data: dataString,
success: function(response)
{
$("div.messageboxcontent").html(response);
}
});
return false; //with and without this.
});
});
Be consistent with quotes. Also close your div (<div class="messageboxcontent"></div>)
Try this:
$(document).ready(function(){
$("#ajaxform").on("submit", function( event ){
var dataString = $(this).serialize();
event.preventDefault();
$.ajax({
type: "POST",
url: "register.php",
data: dataString,
success: function(response)
{
$("div.messageboxcontent").html(response);
}
});
return false;
});
});
Hope that helps.
return false; or event.preventDefault(); inside your ajax function would stop the page from reloading.
Secondly, jQuery works with selector methods via class or id - so, in your case, you will want to use $('#ajaxform').
Lastly, the possible reason why you are facing with unexpected result like after 3rd time is because your form is wrapped inside a div that you want to manipulate the result. So, try rewrapping your DIV element to this: <div class="messageboxcontent"></div> and have your <form> stand on its own separately from messageboxcontent div.

Categories