I have developed a shopping website where i am using ajax to process add to cart and remove from cart. Add to cart is working fine but remove from cart is creating an strange issue. I am able to delete only one record from it and if i want to delete more i need to manually refresh the page and then i would be able to delete only one more. This is so strange and i am unable to find where the bug is.
here is the code :
jQuery('.remove').click(function(data) {
var pi = jQuery(this).attr('name');
var y = jQuery(this).attr('name');
$.ajax({
url: "delcart.php?pid="+pi+"&data="+y,
type: 'GET',
success: function(s){
var $container = $("#content");
// $container.refresh("index.php");
$("#content").load(location.href + " #content");
$("#success2").show().fadeOut(6000);
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
HTML Button.
<button name="<?php echo $ca['ID'];?>" class="remove close_product color_dark tr_hover">x</button>
this button is into the while loop and each time name property consisting the unique ID of database cart table.
here is the delcart.php :
<?php
include_once "config.php";
$id = $_GET['pid'];
$ip = $_SERVER['REMOTE_ADDR'];
$de = mysqli_query($con,"DELETE from cart where ID='{$id}' and ip='{$ip}'");
?>
can anyone please figure what have i missed or where the bug is. This would be a huge help. Thanks in advance.
Not sure if I have the solution for you but I guess it's worth a shot.
My guess is that your buttons with class remove are located somewhere in div with id of container, correct?
if so, then you "lose" the .click handler when you call the .load function that replaces the content of #container div.
the solution would (could) be to change the .click listener to sth like
$('#some-div-container-that-stays').on("click", ".remove", function(data) {
Or at least try to put an console.log() into the .click action to see if it triggers or not
Related
I need a dynamic form which is supposed to work like this:
When user press "ADD" button, appear a new ..<.div> DOM to select a package.
Depending on the package, the row must change color (by adding/removing some classes).
But I can't get it working. Here is my HTML:
<button onclick='addDay();'>
<div class='content'>
</div>
My Javascript:
//FUNCTION 1: LOAD AJAX CONTENT
function addDay()
{
baseUrl = $('input#helper-base-url').val();
//Set caching to false
$.ajaxSetup ({
cache: true
});
//Set loading image and input, show loading bar
var ajaxLoad = "<div class='loading'><img src='"+baseUrl+"assets/images/loading.gif' alt='Loading...' /></div>";
var jsonUrl = baseUrl+"car/add_day/"+count;
$("div#loading").html(ajaxLoad);
$("div#content").hide();
$.getJSON(
jsonUrl,
{},
function(json)
{
temp = "";
if(json.success==true)
{
temp = json.content;
}
//Display the result
$("div#content").show();
$("div#content").html($("div#content").html()+temp);
$("div#loading").hide();
});
}
//FUNCTION 2: MODIFY AJAX CONTENT
$("#content").on("change", "select.switch", function (e) {
e.preventDefault();
//Get which row is to be changed in background's color
id = this.id;
id = id.substr(6);
//Add class "package1" which change row's background color
row = "row"+id;
row.addClass('package1');
});
My PHP
function add_day($count)
{
$temp = "<div class='row".$count."'>
<select id='switch".$count."' class='switch'>
<option value='1'>Package 1</option>
<option value='2'>Package 2</option>
</select>
</div>";
$result = array(
'success' => true,
'content' => $temp,
);
$json = json_encode($result);
echo $json;
}
PS. The form is not as simple as this but to make the problem solving easier, I remove the details. But I can't seem to change the class on the fly. Do we have a solution or a good work around here?
Edit 1:
Sorry I didn't make myself clear before. I had no problem with getting the id or variable (it was okay, when I alert it the right value comes out - but after I add the class, no color changes is seen). I run it:
a. On button click, load Ajax content.
b. Ajax content (which results contains a ) loaded successfully.
c. FAIL: On change, add class "package1" to the div row. (So, I had no problem with getting the right id or class name. When I alert the variables it gives the right result, BUT the color doesn't change. I can't check whether class is successfully added or not.)
$("#content").on("change", "select.switch", function (e) {
e.preventDefault();
$('.row' + $(this).attr('id').replace('switch', '')).addClass('package1');
});
Assuming that everything else is ok
//Get which row is to be changed in background's color
id = this.id;
id = id.substr(6);
//Add class "package1" which change row's background color
row = "row"+id;
row.addClass('package1');
This is the problem. To get the attibute id you have to do
var id = $(this).attr('id').substr(6);
You have to use $(this) and not this by the way to use all of jQuery functionalities.
Same below
$(row).addClass('package1');
So, full code:
//Get which row is to be changed in background's color
var id = $(this).attr('id').substr(6);
//Add class "package1" which change row's background color
$('.row'+id).addClass('package1');
Changing the class to id solved the problem (using #row0 instead of .row0). Sorry and thank you for your time :)
I have been going crazy for the last 2 weeks trying to get this to work. I am calling a MySQL Db, and displaying the data in a table. Along the way I am creating href links that DELETE and EDIT the records. The delete pulls an alert and stays on the same page. The EDIT link will POST data then redirect to editDocument.php
Here is my PHP:
<?php
foreach ($query as $row){
$id = $row['document_id'];
echo ('<tr>');
echo ('<td>' . $row [clientName] . '</td>');
echo ('<td>' . $row [documentNum] . '</td>');
echo "<td><a href='**** I NEED CODE HERE ****'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='deleteDocument( {$id} );'>Delete</a></td>";
// this calls Javascript function deleteDocument(id) stays on same page
echo ('</tr>');
} //end foreach
?>
I tried (without success) the AJAX method:
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
I have been using <? print_r($_POST); ?> on editDocument.php to see if the id has POSTed.
I realize that jQuery/AJAX is what I need to use. I am not sure if I need to use onclick, .bind, .submit, etc.
Here are the parameters for the code I need:
POSTs the $id value: $_POST[id] = $id
Redirects to editDocument.php (where I will use $_POST[id]).
Does not affect other <a> OR any other tags on the page.
I want AJAX to "virtually" create any <form> if needed. I do not
want to put them in my PHP code.
I do not want to use a button.
I do not want to use $_GET.
I don't know what I am missing. I have been searching stackoverflow.com and other sites. I have been trying sample code. I think that I "can't see the forest through the trees." Maybe a different set of eyes. Please help.
Thank you in advance.
UPDATE:
According to Dany Caissy, I don't need to use AJAX. I just need to $_POST[id] = $id; and redirect to editDocument.php. I will then use a query on editDocument.php to create a sticky form.
AJAX is used when you need to communicate with the database without reloading the page because of a certain user action on your site.
In your case, you want to redirect your page, after you modify the database using AJAX, it makes little sense.
What you should do is put your data in a form, your form's action should lead to your EditDocument, and this page will handle your POST/GET parameters and do whatever database interaction that you need to get done.
In short : If ever you think you need to redirect the user after an AJAX call, you don't need AJAX.
You have a SyntaxError: Unexpected identifier in your $.ajax(); request here
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
it should be like this
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: {edit_id: edit_id},
success: function(response){
$('#result').html(response);
}
});
}
</script>
note the 'edit_id='edit_id, i changed, well for a start if you wanted it to be a string it would be like this 'edit_id = ' + edit_id but its common to use a object like this {edit_id: edit_id} or {'edit_id': edit_id}
and you could also use a form for the edit button like this
<form action="editDocument.php" method="POST">
<input type="hidden" name="edit_id" value="272727-example" />
<!-- for each data you need use a <input type="hidden" /> -->
<input type="submit" value="Edit" />
</form>
or in Javascript you could do this
document.location = 'editDocument.php?edit_id=' + edit_id;
That will automatically redirect the user
Given your comment, I think you might be looking for something like this:
Edit
$(document).ready(function() {
$('.editLink').click(function(e) {
e.preventDefault();
var $link = $(this);
$('<form/>', { action: 'editdocument.php', method: 'POST' })
.append('<input/>', {type:hidden, value: $link.data('id') })
.appendTo('body')
.submit();
});
});
Now, I don't necessarily agree with this approach. If your user has permission to edit the item with the given id, it shouldn't matter whether they access it directly (like via a bookmark) or by clicking the link on the list. Your desired approach also prevents the user from opening links in new tabs, which I personally find extremely annoying.
Edit - Another idea:
Maybe when the user clicks an edit link, it pops up an edit form with the details of the item to be edited (details retrieved as JSON via ajax if necessary). Not a new page, just something like a jQuery modal over the top of the list page. When the user hits submit, post all of the edited data via ajax, and update the sql database. I think that would be a little more user-friendly method that meets your requirements.
I was facing the same issue with you. I also wanted to redirect to a new page after ajax post.
So what is did was just changed the success: callback to this
success: function(resp) {
document.location.href = newURL; //redirect to the url you want
}
I'm aware that it defies the whole purpose of ajax. But i had to get the value from a couple of select boxes, and instead of a traditional submit button i had a custom anchore link with custom styling in it. So in a hurry i found this to be a viable solution.
I have a a script that on click do a ajax call connect to the database get imagename and set the image name inside an < -img - > with the right path also it adds a hidden checkbox after it and then echo it.
i then take the ajax message returned and put it as div's HTML. my question is will i be able to preform more action on the inserted content..
The main goal is to be able to click on the image as if it were a checkbox(this part is already sorted for me) however no matter what i try i cant have a .click function works..
Here is the code.
This is the PHP part that echos the images.
if($_POST['updateIgallery'] == 'ajax'){
global $wpdb;
$table_name= $wpdb->prefix . "table_T";
$imagecounter = 1;
$toecho = '';
$currentselected = $wpdb->get_row("query");
preg_match_all('/\/(.+?\..+?)\//',$currentselected ['image_gal'],$preresualts); // images are stored with /image/.
foreach ($preresualts[1] as $imagename){
$toecho .= '
<img rel="no" id="JustantestID" class="JustaTestClass" src="'.site_url().'/wp-content/plugins/wp-ecommerce-extender/images/uploads/'.$imagename.'">
<input name="DoorIMGtoDeleteIDcheck'.$imagecounter.'" style="display:none;" name="DoorIMGtoDelete['.$imagecounter.']" value="/'.$imagename.'/" type="checkbox">
';
$imagecounter++;
}
echo $toecho;
}
This is the ajax part that send and receive and insert the HTML to the div:
$.ajax({
type: "POST",
url: "/wp-content/plugins/wp-ecommerce-extender/DB_Functions.php",
data: { updateIgallery: "ajax", CurrentDoorIDnum: $('#dooridforgallery').val()}
}).success(function(insertID) {
$("#ImgGalleryID").html(insertID);
});
This so far works what i am having trouble with is the following:
$("#JustantestID").click(function() {
//DoorImageGallery($(this).attr('id')); // the function i will use if the alert actually works
alert("kahdaskjdj");
return true;
});
I hope the question and the code is understandable.
Thanks in advanced.
When you replace element's html, all the elements inside it are removed and gone. That means the event handlers attached to them are removed as well.
You could try attaching an event handler to a higher level element that is static and permanent on your page. Without more info I am going to use document:
$(document).on( "click", "#yaniv", function() {
alert("kahdaskjdj");
});
$('img.JustaTestClass').bind('click', function() {
var checkbox = $(this).siblings('input[type=checkbox]');
if (!checkbox.is(':checked')) checkbox.attr('checked', true);
else checkbox.attr('checked', false);
});
Since the elements are dynamically inserted into the DOM with ajax, you have to delegate events to a parent element that actually exists when binding the click handler, which in this case looks to be #ImgGalleryID
$('#ImgGalleryID').on('click', '#yaniv', function() {
DoorImageGallery(this.id);
alert("kahdaskjdj");
});
Hi everyone I have been working on this particular problem for ages by now,plz help.
I have looked at jQuery: Refresh div after another jquery action?
and it does exactly what I want but only once! I have a table generated from db and when I click on delete it deletes the row and refreshes the div but after which none of my jquery functions will work.
$('#docs td.delete').click(function() {
$("#docs tr.itemDetail").hide();
var i = $(this).parent().attr('id');
$.ajax({
url: "<?php echo site_url('kt_docs/deleteDoc'); ?>",
type: 'POST',
data: 'id=' + i,
success: function(data) {
$("#docs tr.itemDetail").hide();
$("#f1").html(data); // wont work twice
//$("#docs").load(location.href+" #docs>*"); //works once as well
}
});
});
in my body I have
<fieldset class='step' id='f1'>
<?php $this->load->view('profile/docs_table'); ?>
</fieldset>
profile/docs reads data from db. <table id='docs'>....</table>
and my controller:
function deleteDoc() {
$id = $_POST['id'];
$this->load->model('documents_model');
$del = $this->documents_model->deleteDocument($id);
return $this->load->view('docs_table');
}
Thanks in advance!
Are you removing any expressions matching $('#docs td.delete') anywhere? If so, consider using $.live(), which will attach your function to ALL matching elements regardless of current or in the future; e.g.
$('#docs td.delete').live('click', function() {
// Do stuff.
});
http://api.jquery.com/live/
Try using bind() instead of click(). The click() method won't work on dynamically added elements to the DOM, which is probably why it only works the first time and not after you re-populate it with your updated content.
You should just have to replace
$('#docs td.delete').click(function() {
with
$('#docs td.delete').bind('click', function() {
Are you replacing the html elements that have the events on them with the data your getting through ajax? If you end up replacing the td.delete elements, then the new ones won't automatically get the binding.
So all i need to do is refresh a variable displayed on a php page which is stored in a MySQL db. This value is an int which is subtracted by 1 everytime the submit button from a form is clicked. As i've opted to use AJAX to post the form the page isn't being refreshed, therefore the value isn't being updated along with the form submission.
$qry = mysql_query("SELECT codes_remaining FROM users WHERE email= '".$_SESSION['email']."'");
while($row = mysql_fetch_array($qry)) {
if ($row['codes_remaining'] ==1 )
{
echo "You have ".$row['codes_remaining'].' code remaining';
}
else {
echo "You have ".$row['codes_remaining'].' codes remaining';
}
}
So this code just displays how many "codes" a person has left. I need this value to be refreshed once the submit button has been clicked from the form on the same page.
I'm using the following JavaScript to not refresh the page.
$("#form-submit").click(function(e) {
e.preventDefault();
$.ajax({
cache: true,
type: 'POST',
url: 'process-register.php',
data: $("#form-register").serialize(),
success: function(response) {
$("#output-div").html(response);
}
});
});
Thanks,
LS
If you'd like to update the value, do it like this (jQuery is easiest):
$(".submit").click(function(event) {
event.preventDefault();
$(this).load('file.php',function(val){
$('#output').text(val);
});
});
And in file.php:
<?php
connect_to_db();
$returned = get_info_from_db();
echo $returned;
?>
The jQuery will grab the info on file.php and put it into #output.
Maybe It's just me, but why not use jQuery .load function?
$("#form-submit").click(function(e) {
e.preventDefault();
$(this).load('process-register.php');
});
Maybe not ethical nor the correct way of doing this but everytime you click on #form-submit, it loads that file and therefore processes it everytime. Also note that if you load a file that uses MySQL connection yes has no mysql_connect or mysql_select_db configured, it obviously won't work. I've had that for quite some times.
In your 'success', you could possibly just throw in
$("#WhereYouWantTheOutput").load("process-register.php");
That way whenever your submit succeeds, it'll also load the output for you. Just replace #WhereYouWantTheOutput with the name of where you want the output placed.