I have some PHP code that generates out a bunch of store items from my database. Each item has a quantity text box and an add to cart submit button and a hidden value with the special ID.
Here is basically how my form is generated:
<form class='form-inline' id='addtocart_form' action='
additem.php?iid=$SaleItem_Id&u=".$_SESSION['id']." ' method='post' role='form'>
<div class='form-group'>
<div class='input-group'>
<input type='text' class='form-control' style= 'float: left; width:50%;' id='quantity'
name='quantity' value='0'></input>
<button type='submit' name='add_to_cart' id='add' class='btn btn-success'>Add to
Cart</button>
</div>
<input type='text' name='$SaleItem_Id' style='display: none;' id='$SaleItem_Id'
value='$SaleItem_Id'>
</form>
My cart works perfectly, except it refreshes and puts you back up to the top of the screen. So then I decided to implement jQuery. All of these generated forms have the same id: addtocart_form.
$(function() {
$("#addtocart_form").on('submit' , function(e) {
e.preventDefault();
var thisForm = $(this);
var quantity = $("#quantity").val();
var dataString = $("#addtocart_form").serialize();
$.ajax({
type: "POST",
url: thisForm.attr('action'),
data: dataString,
});
$("#quantity").val("0");
return false;
});
});
The first item that is displayed on the screen works perfectly. It adds the item to the cart without refreshing the screen.
All of the other forms on the page are being submitted without the jQuery. They add the item, but redirect to the URL of my action.
How can I fix this without rewriting my entire store? I assume it has something with which form is being told to submit.
The id attribute should be unique in same document so try to replace the id addtocart_form by class, and all the other id's by classes to avoid duplicated id.
HTML :
<form class='form-inline addtocart_form' action=...
JS :
$("body").on('submit', '.addtocart_form', function(e) {
e.preventDefault();
var quantity = $(this).find(".quantity").val();
var dataString = $(this).serialize();
var action = $(this).attr('action')
$.ajax({
type: "POST",
url: action,
data: dataString,
});
$(this).find(".quantity").val("0");
return false;
});
Hope this helps.
You should not have more than one element with the same id on a page. If all of your forms use the same id, that's a problem.
Since you are using JQuery with AJAX, there's really no need to use a form at all. Just use a regular button (type="button") and tie a click event to it. Find the parent div of the button and get the values of the inputs within that div.
If your markup looks like this:
<div class='form-group'>
<input type='text' class='form-control quantity' style='float: left; width:50%;' value='0'>
<button type='button' class='btn btn-success add'>Add to Cart</button>
<input type='text' style='display: none;' class='saleItem_Id'>
</div>
<div class='form-group'>
<input type='text' class='form-control quantity' style='float: left; width:50%;' value='0'>
<button type='button' class='btn btn-success add'>Add to Cart</button>
<input type='text' style='display: none;' class='saleItem_Id'>
</div>
You can iterate over the inputs within the div like so:
$(".add").on('click', function() {
var parentDiv = $(this).closest("div");
//in this example, you only have one element, but this is how you would iterate over multiple elements
parentDiv.children('input').each(function() {
console.log($(this).prop('class'));
console.log($(this).val());
});
//do your ajax stuff
});
JS Fiddle demo
Related
I have multiple images on a page that I'm hoping to have a like button on each. Right now it works up to a point, on click it updates the database of the image you've liked and changed the image to a red heart, but 2 things happen:
When clicking one like button, it sets all of them off, but only the one clicked will get committed to database.
I can't click again to unlike.
I've tried using jQuery and Ajax, when clicking the heart/like button it will then change all the parameters with 'attr' to reflect the unlike form.
//Here is the form for the like button
<form class='like_form_p' name='like' action='/like.php' method='post'>
<input type='hidden' style='display:none;' name='aid' id='aid' value='".$results['aID']."'>
<input type='hidden' style='display:none;' name='uid' id='uid' value='".$uid."'>
<input type='hidden' style='display:none;' name='currenturl' id='currenturl' value='".$currentURL."'>
<input type='hidden' style='display:none;' name='pId' id='pId' value='".$cover['pId']."'>
<input type='image' class='like_btn' src='/images/heart.png' alt='submit' width='24' height='20'>
</form>
//Here is the form for the unlike button
<form class='unlike_form_p' name='unlike' action='/unlike_cover.php' method='post'>
<input type='hidden' style='display:none;' name='aid' id='aid' value='".$results['aID']."'>
<input type='hidden' style='display:none;' name='uid' id='uid' value='".$uid."'>
<input type='hidden' style='display:none;' name='currenturl' id='currenturl' value='".$currentURL."'>
<input type='hidden' style='display:none;' name='pId' id='pId' value='".$cover['pId']."'>
<input type='image' class='like_btn' src='/images/heart_a.png' alt='submit' width='24' height='20'>
</form>
//Here is the jQuery script that runs
<script>
function like()
{
$('.like_form_p').attr('action', '/unlike.php');
$('.like_form_p').attr('class', 'unlike_form_p');
$('.like_btn').attr('src', '/images/heart_a.png');
};
function unlike()
{
$('.unlike_form_p').attr('action', '/like.php');
$('.unlike_form_p').attr('class', 'like_form_p');
$('.like_btn').attr('src', '/images/heart.png');
};
$(document).ready(function(){
$('.like_form_p').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
console.log(form_data);
$.ajax({
url:'/like.php',
method:'POST',
data:form_data,
success:function(data)
{
like()
},
error:function(xhr, status, error)
{
alert("I have failed");
}
})
})
});
$(document).ready(function(){
$('.unlike_form_p').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
console.log(form_data);
$.ajax({
url:'/unlike.php',
method:'POST',
data:form_data,
success:function(data)
{
unlike()
},
error:function(xhr, status, error)
{
alert("I have failed");
}
})
})
});
</script>
I expected this to fire off the one ajax, then once all the details were changed on the form with the like/unlike function it would then be able to fire off the other ajax.
But I actually got one click fires off the one ajax, all the like buttons are activated, and I can't click it again.
I'm working on add to compare feature of a website,so on current page there are some results which have a checkbox named add to compare attached.
So when user click on add to compare checkbox the selected result get appended to one compare box div and this process go on.
my problem is,when user want to uncheck or remove the selected result from compare div box he should be able to remove it.
Here's is my code which i have done till yet
html
<div id='compare_box'>
<form action="compare_results.php" method="POST">
<div id='result'>
</div>
<button id="compare_submit" type="submit" class="btn btn-primary btn-sm">compare</button>
</form>
</div>
<div class="col-md-3 photo-grid " style="float:left">
<div class="well well-sm">
<h4><small><?php echo $title; ?></small></h4>
<br>
<div class="features">
<div id="compare_feature">
<input type ='checkbox' name="compare" class="compare" value="<?php echo $id;?>">add to compare
</div>
<button class='btn btn-sm btn-info favourite_feature' value="<?php echo $id;?>">add to favourite</button>
</div>
</div>
</div>
css
#compare_box
{
display: none;
}
ajax call
$(".compare").change(function() {
if(this.checked) {
$('#compare_box').show();
var check = $(this).val();
$.ajax({
type: 'POST',
url: 'compare.php',
dataType : "JSON",
data:{value : check},
success: function(data)
{
console.log(data);
console.log(data.id);
var output = "<div class='col-md-3 photo-grid' style='float:left'>";
output += "<div id='course_title' class='well well-sm'>";
output += "<h4>"+data.title+"</h4>";
output+="<textarea class='hidden' id='hidden_title' name='course_title[]' value=>"+data.title+"</textarea>";
output+="</div>";
output+="<input type='hidden' id='hidden_id' name='course_id[]' value="+data.id+">";
output+="</div>";
$('#result').append(output);
}
});
}
});
PS: I'm trying to implement something like this
What is '#compare_box' ? Is it the element that appears when the checkbox disappear (in your exemple at 'your selection')?
Then bind an action on '#result' - precise something that can link your element to check box like an id (when you prepare your html in ajax response).
$('#result').on('click', function() {
$($(this).data('id')).prop('checked', false); // uncheck it
$(this).remove();
});
Do the same for when you uncheck a checkbox (find the element with data-id of your check box and remove it)
EDIT : it's not the perfect code to make it work, you might adapt depending on where you bind click or place the data-id
i have a form with four elements. i need to open a jquery popup when click on image that i set as fourth element in my form. popup window contains another form and a submit button. herepopup not coming. what wil i do.
this is my form
echo "<div class=\"addform\">
<form method='GET' action=\"update_events.php\">\n";
echo " <input type=\"hidden\" name=\"column1\" value=\"".$row['event_id']."\"/>\n";
echo " <input type=\"text\" name=\"column2\" value=\"".$row['event_name']."\"/>\n";
echo " <input type=\"text\" name=\"column3\" value=\"".$row['description']."\"/>\n";
echo " <input type=\"image\" src=\"images/update.png\" id=\"update_event\" alt=\"Update Row\" class=\"topopup\" onClick=\"callPopup(".$row['event_id'].")\"; title=\"Update Row\">\n";
}
echo "</table></form><br />\n";
this is my jquery
<script type="text/javascript">
function callPopup(id) {
console.log(id);
var datastring = "&event_id="+id;
$.ajax({
url: 'event_edit_popup.php', //enter needed url here
data: datastring,
type: 'get', //here u can set type as get or post
success: function(data) {
$('.popupContent').html(data);
console.log(data);
$('.loader1').hide();
$("#popup_content").after(data);
// u can see returned data in console log.
// here, after ajax call,u can show popup.
}
});
};
</script>
and this is my popup div
<div id="toPopup">
<div class="close"></div>
<span class="ecs_tooltip">Press Esc to close <span class="arrow"></span></span>
<div id="popup_content"> <!--your content start-->
<p align="center">edit company</p>
</div> <!--your content end-->
</div> <!--toPopup end-->
<div class="loader"></div>
<div id="backgroundPopup"></div>
You just need to give the image an id.. say id="clickme"
and in the jquery script:-
$('document').ready(function(){
$('#clickme').click(function(){ $('#topopup').show(220);}); });
Again u can add in transitions in the css of the topopup to give it various effects.
Also to hide the pop up:-
$('document').ready(function(){
$('#backgroundPopup').click(function(){ $('#topopup,#backgroundPopup').hide(220);}); });
//This is assuming that you want the popup to be closed when u click on the background
First mistake in your form is not complete and second is there is no input type='image' if you want to display image than you use image tag.
Please follow the code I hope it will be helpful to you:
<div class='addform'>
<form method='GET' action='update_events.php'>
<input type='hidden' name='column1' value="123"/>
<input type='text' name='column2' value="456"/>
<input type='text' name='column3' value="789"/>
<img src='images/update.png' id='update_event' alt='Update Row' class='topopup' onClick='callPopup("1")' title='Update Row'/>
</form>
</div>
Now jQuery code:
$("#update_event").click(function() { alert('sdf'); });
Now instead of alert you can use your ajax call for pop up.
I want to add a div without refreshing the page.
Here is my Javascript:
<input class="btnsubmit" type="button" value="+Add Trivia" id="add_triviamodal">
function add_trivia()
{
var PHOTO_TRIVIA = CKEDITOR.instances.Trivia_Photo.getData();
var TITLE_TRIVIA = $('#TRIVIA_TITLE').val();
var CAPTION_TRIVIA = CKEDITOR.instances.triviacap.getData();
$.post('insert_home.php',{TRIVIA_TITLE:TITLE_TRIVIA,TRIVIA_PHOTO:PHOTO_TRIVIA,TRIVIA_CAP:CAPTION_TRIVIA}).done(function(data){
alert ("Trivia Successfully Added");
location.reload(); \\what i do is just refresh the page
});
}
This is how i output the the data that will be added using the ajax above
echo "<div class=\"view view-sixth\">
".$Tri_IMAGE."
<div class=\"mask\">
<div class=\"divbutton\">
<input onclick='TRIVIA_EDIT($Tri_ID);' class=\"btnsubmit\" type=\"button\" value=\"Edit\" id=\"edit_trivia\">
<input onclick='TRIVIA_DELETE($Tri_ID,this);' class=\"btnsubmit\" type=\"button\" value=\"Delete\" id=\"delete_trivia\">
</div>
<h2>".$Tri_TITLE."</h2>
<p>".$Tri_CAPTION."</p>
</div>
</div>";
}
You can use append() in jQuery to append elements to the DOM. If the div is returned by your PHP. Then append it to a DOM element by using i.e. $('#trivias').append(data);
EDIT (using the question authors code as an example):
I've replaced the location.reload() part with the code to append the returning div.
$.post('insert_home.php',{TRIVIA_TITLE:TITLE_TRIVIA,TRIVIA_PHOTO:PHOTO_TRIVIA,TRIVIA_CAP:CAPTION_TRIVIA}).done(function(data){
$('#trivias').append(data);
}
Here I assume you've got a element with the trivias id. For example <div id="trivias">...</div> somewhere in your code already.
just put your response data into whatever you want it in
$.post('insert_home.php',{TRIVIA_TITLE:TITLE_TRIVIA,TRIVIA_PHOTO:PHOTO_TRIVIA,TRIVIA_CAP:CAPTION_TRIVIA}).done(function(data){
alert ("Trivia Successfully Added");
$('#idOfTheDivYouwantToPutResponseIn').html(data);
});
Change your $.post() callback to also append the HTML response from insert_home.php into the DIV.
$.post('insert_home.php',{
TRIVIA_TITLE: TITLE_TRIVIA,
TRIVIA_PHOTO: PHOTO_TRIVIA,
TRIVIA_CAP: CAPTION_TRIVIA
}).done(function(data){
alert ("Trivia Successfully Added");
$('#trivias').html(data);
});
in PHP use json_encode
$str = "<div class=\"view view-sixth\">
".$Tri_IMAGE."
<div class=\"mask\">
<div class=\"divbutton\">
<input onclick='TRIVIA_EDIT($Tri_ID);' class=\"btnsubmit\" type=\"button\" value=\"Edit\" id=\"edit_trivia\">
<input onclick='TRIVIA_DELETE($Tri_ID,this);' class=\"btnsubmit\" type=\"button\" value=\"Delete\" id=\"delete_trivia\">
</div>
<h2>".$Tri_TITLE."</h2>
<p>".$Tri_CAPTION."</p>
</div>
</div>";
echo json_encode($str);
then use he post request like this
$.ajax({
type: "POST",
url: 'insert_home.php',
data: {TRIVIA_TITLE:TITLE_TRIVIA,TRIVIA_PHOTO:PHOTO_TRIVIA,TRIVIA_CAP:CAPTION_TRIVIA},
dataType:'json',
success: function (data) {
$('#your_id').html(data);
}
});
I have a little problem with my AJAX jQuery script and n number of forms...To be more precise, PHP script generate N number of forms (form include one textarea and one button), and in head tag I included jquery script. Problem is that jquery work only for first form and not with others (second, third...). I needed to work with all forms...This is the code:
<script>
$(document).ready(function() {
$("#submitForm").click(function() {
var text = $("#comment").val();
var id = $("#id").val();
$.ajax(
{
url: "addcomment.php",
type: "POST",
data: "t="+ text +"&id="+id,
success: function(data)
{
alert(data);
}
});
});
});
</script>
And this is PHP code
for($i=0; $i<$num; $i++)
{
echo "<div style='border: 1px solid black;'>
<textarea id='comment'></textarea>
<input type='hidden' id='id' value='".$id."'/>
<input type='button' id='submitForm' value='Add Comment'>
</div>";
}
What is problem???
On your PHP side you should change with something similar to this to ensure that all the html elements has a unique id.
for($i=0; $i<$num; $i++)
{
echo "<div style='border: 1px solid black;'>
<textarea id='comment".$i."'></textarea>
<input type='hidden' id='id".$i."' value='".$id."'/>
<input type='button' id='".$i."' class='submitForm' value='Add Comment'>
</div>";
}
and change the Javascript with something similar to this to reflect the changes made on the php side
<script>
$(document).ready(function() {
$(".submitForm").click(function() {
var formNumber = $(this).attr("id"); // Get the form number that was clicked, the id attribute of the clicked button
var text = $("#comment"+formNumber).val(); // Get the comment of that particular form
var id = $("#id"+formNumber).val(); // get the id of that particula form
$.ajax(
{
url: "addcomment.php",
type: "POST",
data: "t="+ text +"&id="+id,
success: function(data)
{
alert(data);
}
});
});
});
</script>
For every form you're creating you're using the same ID.
IDs must be unique and only appear once on the page.
You should use a class instead as suggested in the comments.
So more like this:
<?php for ($i = 0; $i < $num; $i++): ?>
<div>
<textarea class="comment"></textarea>
<input type="hidden" class="id" value="<?php echo $id; ?>">
<input type="button" class="submitForm" value="Add Comment">
</div>
<?php endfor; ?>
I'm not sure where your $id variable comes from.
Your JavaScript will need to be updated as well to work with this, I'd do something like this (elaborated so you can see what's going on):
$('.submitForm').click(function(e) {
e.preventDefault(); // stops the default form action (if there is one)
var $submitButton = $(this);
var $div = $submitButton.parent(); // gets the div container
var id = $div.find('.id').val();
var text = $div.find('.comment').val();
// now do your ajax
});