Ajax call only passing id of the first element - javascript

I am outputting multiple dynamic links which use the same < a >. My AJAX call loads the content fine of all the links fine. But the new div which displays the ajax content only outputs id of the first link when other links are clicked. I am using this to see the id in the console console.log($('[data-taskid]').first().attr('data-id')); how can i pass the id of the link clicked to my ajax view? Thanks guys!
<div id="content"></div>
PHP
$string .= '<a class="hrefid" data-id="'.$name["id"].'" href="#link">'.$name["name"].'</a>'.
Jquery
$('.hrefid').on('click', function (e) {
var load = $(e.target).attr("href");
if(load == "#link") {
$.ajax({
type: 'post',
url: "/page/test/"+$(this).parents("[data-id]").attr("data-id"),
complete: function (event) {
$("#content").contents().remove();
$("#content").append(event.responseText);
}
});
}
});

Please review that I didn't use $(this) as reference , $(this) reference get chnaged once you use $(this) in ajax , it refers to ajax not main selector.
$('.hrefid').on('click', function (e) {
var $this = $(this);
var load = $this.attr("href");
if(load == "#link") {
$.ajax({
type: 'post',
url: "/page/test/"+ $this.attr("data-id"),
complete: function (event) {
$("#content").contents().remove();
$("#content").append(event.responseText);
}
});
}
});

Related

ajax is not working i have to refresh to make it work

Ajax is not working I have to reload the page to make it work. Because of ajax was not reloading i used location.reload but I don't want this so please anyone can help me out how to make ajax function work. Its removing data but I need to refresh the page to see
$(document).ready(function() {
$('.headertrash').click(function(e){
e.preventDefault();
var trashcartid = this.id;
var splittrash = trashcartid.split('-');
var cartdelid = splittrash[1];
//Ajax Request
$.ajax({
url: 'delusing.php',
type: 'POST',
data: { id:cartdelid },
success: function(response){
// Remove row from HTML Table
$(this).closest('li').fadeOut(300,function(){
$(this).closest('li').remove();
});
//I uses location.reload as alternative
// location.reload();
}});
e.preventDefault();
});
I am going to assume that your request is working and returns success.
From your code and question I am deducing that the actual issue is not with ajax not working but with the li not fading and disappearing.
The issue you are experiencing is due to the this you are using, the way you are using this it means the ajax request, but your intent is to get the element associated with $('.headertrash') to fix your issue:
$(document).ready(function() {
$('.headertrash').click(function(e){
e.preventDefault();
var trashcartid = this.id;
var splittrash = trashcartid.split('-');
var cartdelid = splittrash[1];
var clickedElement = $(this);
//Ajax Request
$.ajax({
url: 'delusing.php',
type: 'POST',
data: { id:cartdelid },
success: function(response) {
// Remove row from HTML Table
clickedElement.closest('li').fadeOut(300,function() {
clickedElement.closest('li').remove();
});
}
});
});
});
See: Ajax (this) not working for more details

jQuery .on not working after ajax delete and div refresh

On a page with a tab control, each tab contains a table, each tr contains a td with a button which has a value assigned to it.
<td>
<button type="button" class="btn" name="deleteEventBtn" value="1">Delete</button>
</td>
This code below works for the first delete. After the AJAX call & the refresh of the div, no further delete buttons can be clicked. The .on is attached to the document. The same happens if I attach it to the body or anything closer to the buttons.
function deleteRecord(url, id, container) {
$.ajax({
type: "POST",
url: url,
data: { id: id },
success: function (data) {
$('#delete-popup').hide();
$(container).trigger('refresh');
}
});
}
$(document).ready(function () {
$(document).on('click', '[name^="delete"]', function (e) {
e.preventDefault();
var id = $(this).val();
$('#current-record-id').val(id);
$('#delete-popup').modal('show');
});
$('#delete-btn-yes').on('click', function (e) {
e.preventDefault();
var recordId = $('#current-record-id').val();
var recordType = location.hash;
switch (recordType) {
case "#personList":
deleteRecord(url, recordId, recordType);
break;
}
});
});
Any ideas? Could it be related to the wildcard for starts with [name^="delete"]? There are no other elements where the name starts with 'delete'.
EDIT
When replacing
$(container).trigger('refresh');
with
location.reload();
it "works", however that refreshes the whole page, loses the users position and defeats the point of using AJAX.
As the button click is firing at first attempt, there is no issue in that code. All you have to do is, put the button click event in a method and call it after the refresh. This way, the events will be attached to the element again. See the code below,
function deleteRecord(url, id, container) {
$.ajax({
type: "POST",
url: url,
data: { id: id },
success: function (data) {
$('#delete-popup').hide();
$(container).trigger('refresh');
BindEvents();
}
});
}
$(document).ready(function () {
BindEvents();
});
function BindEvents()
{
$(document).on('click', '[name^="delete"]', function (e) {
e.preventDefault();
var id = $(this).val();
$('#current-record-id').val(id);
$('#delete-popup').modal('show');
});
$('#delete-btn-yes').on('click', function (e) {
e.preventDefault();
var recordId = $('#current-record-id').val();
var recordType = location.hash;
switch (recordType) {
case "#personList":
deleteRecord(url, recordId, recordType);
break;
});
}
Apologies to all and thanks for your answers. The problem was due to the way the popup was being shown & hidden.
$('#delete-popup').modal('show');
and
$('#delete-popup').hide();
When I changed this line to:
$('#delete-popup').modal('hide');
it worked. Thanks to LShetty, the alert (in the right place) did help!
If you are using Bootstrap Modal
After Ajax Request before Refreshing page add
$('.modal').modal('hide');
This Line will Close your Modal and reload your page. Before that it will complete all Ajax Request things.
But for google chrome there is no issues :) hope this help someone.

jQuery Ajax Page Loading Fails

I want when I click a link with attribute "linkdata" = "page" to change the body's code to a loading image and after it's done to change the whole document's HTML to the result. Here is the current code I have:
$('a[linkdata="page"]').each(function() {
$(this).click(function () {
var attribute = $(this).attr("href");
$("body").html('<center><img src="/ajax-loader.gif" /></center>');
$.ajax({ type: "GET", url: attribute }).done(function (data) {
$(document).html(data);
});
return false;
});
});
The result:
It changes the body's HTML code to the image and always fails with the request (which is http://somelink.com/home - using CodeIgniter, tried with .fail(function() { window.location="/error/404" });)
$('a[linkdata="page"]').on('click',function(k,v){
var attribute = $(this).attr("href");
$("body").html('<center><img src="/ajax-loader.gif" /></center>');
$(document).load({ type: "GET", url: attribute });
})
$('a[linkdata="page"]').click(function(e){
e.preventDefault();
$("body").html('<center><img src="/ajax-loader.gif" /></center>');
$.ajax({url:$(this).attr("href") })
.success(function(data){$(document.body).html(data);})
.error(function(x,s,e){alert('Warning! '+s+': '+e)});
});

jquery $.ajax force POST

I have an ajax function that creates a link that triggers another ajax function. For some reason the second ajax function refuses to go through POST event if I've set type: "POST"
The two functionas are below:
function HandleActivateLink(source) {
var url = source.attr('href');
window.alert(url)
$.ajax({
type: "POST",
url: url,
success: function (server_response) {
window.alert("well done")
}
});
return false;
}
function HandleDeleteLink() {
$('a.delete-link').click(function () {
var url = $(this).attr('href');
var the_link = $(this)
$.ajax({
type: "POST", // GET or POST
url: url, // the file to call
success: function (server_response) {
if (server_response.object_deleted) {
FlashMessage('#form-success', 'Link Deleted <a class="activate-link" href="' + url.replace('delete', 'activate') + '">Undo</a>');
$('a.activate-link').click(function(){
HandleActivateLink($(this));
});
the_link.parent().hide();
} else {
var form_errors = server_response.errors;
alert(form_errors)
}
}
});
return false;
});
}
You'll notice HandleDeleteLink creates a new link on success, and generates a new click event for the created link. It all works butHandleActivateLink sends the request to the server as GET. I've tried using $.post instead with no luck.
Any pointers, much appreciated.
In the second event you do not inform the client to prevent the default behaviour.
One way to do this would be to change:
$('a.activate-link').click(function(){
HandleActivateLink($(this));
});
to:
$('a.activate-link').click(function(){
return HandleActivateLink($(this));
});
(This works because HandleActiveLink already returns false.)
A nicer way to do this is to pass in the event argument to the click function and tell it to preventDefault
$('a.activate-link').click(function(e){
e.preventDefault();
HandleActivateLink($(this));
});
what is your url?
btw You can't send a cross-domain post via javascript.

changing jquery live to on pagination

I have a pagination page based on dropdown list and on change loaded as
$("select#opt-category").change(function () {
$(".showgrid").load('portal.php?category='+category);
});
in portal.php(which is also post as ajax to pagination.php
if(isset($_GET['category'])) $catgory=$_GET['category'];
<script type="text/javascript">
function loading_show(){
$('#loading').html("<img src='assets/img/ajax-loader.gif'/>").fadeIn('slow');
}
function loading_hide(){
$('#loading').fadeOut('slow');
}
function loadData(page,category){
loading_show();
$.ajax
({
type: "POST",
url: "pagination_data.php",
data: {'page':page,'category':category},
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1,<?php echo $catgory?> )
// For first time page load default results
$('#container .pagination li.active').live('click',function(){
event.stopPropagation();
var page = $(this).attr('p');
var category= $(this).attr('q');
loadData(page,category);
//break;
});
$('#go_btn').live('click',function(){
var page = parseInt($('.goto').val());
var category = parseInt($('.total').attr('b'));
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page,category);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
//$('.goto').val("").focus();
return false;
}
});
</script>
It shows all the pagination correctly but clicking on pages fire multiple Ajax call to pagination_data.php and how do i change to .on()
thanx
Use the element closest to the button, which is not loaded dynamically (document in extreme cases). Then attach the handler on it, and use the button's selector (the id in your case) as the selector for the delegated event.
Assuming your #container is that static element:
$('#container').on('click', '.pagination li.active', function(){…});
$('#container').on('click', '#go_btn', function(){…});

Categories

Resources