JQuery function POST on the same page works only twice - javascript

The function below allows me to use an href link to POST request to the same page. It works for the first 2 times I click on the link, but this function doesn't seem to be recognized after a third POST request.
$(function() {
$('.sort-link').on('click', function(e) {
e.preventDefault();
$.post(this.href, function(data) {
$('.container').html(data);
});
});
});
I need to modify the function to have it work even after a POST request has been submitted.

As per #Elvin85's advice, I revised my function as follows:
$(function() {
$(document).on("click", '.sort-link', function(e) {
e.preventDefault();
$.post(this.href, function(data) {
$('.container').html(data);
});
});
});
It was a DOM-related issue.

Related

making javascript work after ajax response

I have ajax displaying posts (infinite scroll).
And I have a script which works prior to the ajax response but not after.
So when the new posts are loaded, the javascript is not executed in the ajax loaded posts.
document.addEventListener('DOMContentLoaded', function() {
jQuery(function($) {
$('.post-link-home').find('.elementor-post').each(function() {
let link = $(this).find('a').attr('href');
$(this).wrapAll(document.createElement('a'));
$(this).closest('a').attr('href', link);
});
});
});
Any ideas how to make this work after the ajax loaded posts?
This is what worked for me:
document.addEventListener('DOMContentLoaded', function PostLinkHome() {
jQuery(function($) {
$('.post-link-home').find('.elementor-post').each(function() {
let link = $(this).find('a').attr('href');
$(this).wrapAll(document.createElement('a'));
$(this).closest('a').attr('href', link);
});
});
jQuery(document).ajaxComplete(function() {
PostLinkHome();
});
});
Explanation
I gave the first function executed without Ajax a name: PostLinkHome()
I then called for that same function to be executed when Ajax is loaded:
jQuery(document).ajaxComplete(function() { PostLinkHome(); });
Source

when scroll down, data is loaded by ajax but click trigger is not working jquery

i face a problem of jquery click function when i scroll down in list.
in list, data is loaded by ajax request and when i scroll down then click function (trigger) is not working.
when i not scroll down, ajax data is not loaded then click function is working.
i'm confuse why this happened. i used following triggers below but not success.
on()
click()
bind()
load()
delegate()
i'm sending you code. this is code below. Please help me to sort out.
$(window).ready(function(){
$(".like").on("click", function(){
var id = $(this).attr('data');
// alert(id);
$.ajax({
url: "/stores/addLike",
type: 'GET',
data: {
id: id
},
error: function (data) {
console.log(data);
},
success: function (data) {
console.log(data);
if(data == "liked"){
alert('Sorry, you have already liked this beat.');
}else if(data == "notlogin"){
alert('Please login first to like a beat.');
window.location = "https://demo.amplifihub.com/login";
}else{
$(".likes"+id).text(data);
}
}
});
});
});
instead of $(".like").on("click", function(){ }); use $(document).on("click", ".like", function(){}); or use any static parent dom element to preserve the DOM event. I believe you are generating .like class element on scroll ajax call.

jQuery onclick event not working upon making multiple ajax requests

I am making few ajax requests in my jQuery file. On success of these jQuery requests, I wrote few on click events which are not working.
This is my code
$(document).ready(function (){
$.ajax ({
type: "POST",
url: 'myServlet',
async: false,
success: function (response) {
id = parseInt(response);
setOutputEvents();
}
});
function setOutputEvents() {
for (var queryNumber = 0; queryNumber <= id; queryNumber++) {
$.ajax({
type: "POST",
url: 'myOtherServlet',
data: {queryNumber: queryNumber},
success: success,
async: false
});
var success = function (response) {
//some code here
generateTable();
}
}
}
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
});
I understand making multiple ajax requests is a bad programming practice but what could be the reason for on click events not getting triggered?
These are the onclick events which are not working.
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
I am using Google Chrome Version 39.0.2171.95 on Windows 7.
Please do let me know if any further information is necessary.
Since you use ajax to load even the initial content it seems, .class / #me html elements likely do not exist on initial page load of the DOM. As you didn't post html, i'm guessing this is the case.
Thus, you need to use a delegated event click handler to respond to it
so, you would change
$("#me").on("click", function(){
to
$(document).on("click", "#me", function(){
and so forth to link it to the parent element that does exist, the document itself.
This would work:
$(".class").on("click", function(){
alert("me is triggered");
});
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").trigger("click");
}
Some notes:
Event handler must be registered before triggering click.
Triggered click selector must match the class which has the click event registered.
Functions must be defined before the usage.

How to make $.get call during form submission?

I don't want to submit my form with AJAX, but I want to make a progress bar by making a couple of GET requests to the server during form submission, since the submission might take a while with multiple file uploads. I've found that in webkit browsers, I can't make GET requests while the form is submitting and I was seeing that submitting the form to an iframe would allow me to do it.
The markup looks like this:
<form action="/my-action" target="target-iframe">
...
</form>
<iframe name="target-iframe"></iframe>
And the JavaScript:
$(document).ready(function() {
$("form").on("submit", function() {
$.get("/other-action", function(data) {
// Use data returned here
});
});
});
I'm still not getting data back on the GET request--how can I get this to work?
$(document).ready(function() {
$("form").on("submit", function(e) { //add a parameter e - the event object
e.preventDefault(); //stop the form from submitting
$.get("/other-action", function(data) {
// Use data returned here
});
});
});
EDIT
Set a flag that won't allow the form to submit until you've received your response form your get request. Once you've received your response, set your flag to allow your form to submit and then resubmit it programmatically.
$(document).ready(function() {
var canISubmit = false;
$("form").on("submit", function(e) { //add a parameter e - the event object
var el = $(this);
if(!canISubmit) {
e.preventDefault();
$.get("/other-action", function(data) {
canISubmit = true;
el.submit();
});
}
});
});
The only way to be certain that your $.get request was completed is to make sure that the form doesn't submit and redirect the page until your $.get request completes.
EDIT #2
$(document).ready(function() {
$("form").on("submit", function(e) { //add a parameter e - the event object
e.preventDefault();
$.post("url",$(this).serialize())
.done(function(response,status,jqXHR) {
$.get("/other-action")
.done(function(response,status,jqXHR) {
//other stuff done
//refresh the page or do whatever....
})
.fail(function() {
//$.get failed
});
})
.fail(function() {
//$.post failed
});
});
});

Question about Javascript (Jquery) and GET

After getting a new page with $.get none of the javascript will run on the new page.
Is there a way to make javascript use the new page too?
Many thanks
Dorjan
Edit: Example:
$(function() {
$('.viewPage').click(function() {
$('#mainarticle').fadeOut('slow')
$.get($(this).attr('href'), { js: "1" }, function(data) {
$('#mainarticle').html(data).fadeIn('slow');
});
return false;
});
});
Now this works fine however, the new page's anchor tags won't trigger (lets say it has a .viewPage).
I hope that clarify's the issue.
You need to bind events to your anchors using live:
$('a.something').live("click",function() {
alert('this will still work after a.something has been replaced via ajax');
});
Another way using $.get's callback:
$.get( "page.html", function(data) {
$('#someDiv').html(data);
$('a.something').click(function() {
alert('this will still work after a.something has been replaced via ajax');
});
});
Now that I've seen your code:
$(function() {
$('.viewPage').live("click",(function() {
$('#mainarticle').fadeOut('slow')
$.get($(this).attr('href'), { js: "1" }, function(data) {
$('#mainarticle').html(data).fadeIn('slow');
});
return false;
});
});
Yep; there is another jquery ajax method that will take the returned script from your page and execute it. Check the jquery docs.

Categories