0

I have a site that uses ajax to load a post directly to the page when clicked.

But... I also have an ajax contact-form at the same page. But if I click a post first, then want to send a message later, it fails. But if I refresh the page and go straight to the contact-form and send a message it doesn't fail at sending. Is there any way that I can maybe "reload" ajax without refreshing the page so that you can do multiple things at my site with ajax?

$(document).ready(function() {

    function yournewfunction() {

        var requestCallback = new MyRequestsCompleted({
            numRequest: 3,
            singleCallback: function() {
                alert("I'm the callback");
            }
        });

        var width = 711;
        var animationSpeed = 800;
        var pause = 3000;
        var currentSlide = 1;


        var $slider = $("#slider");
        var $slideContainer = $(".slides");
        var $slides = $(".slide");
        var $toggleRight = $("#right");
        var $toggleLeft = $("#left");

        $toggleRight.click(function() {
            $slideContainer.animate({
                'margin-left': '-=' + width
            }, animationSpeed, function() {
                currentSlide++;
                if (currentSlide === $slides.length) {
                    currentSlide = 1;
                    $slideContainer.css('margin-left', 0);
                }
            });
        });

        $toggleLeft.click(function() {
            if (currentSlide === 1) {
                currentSlide = $slides.length;
                $slideContainer.css({
                    'margin-left': '-' + width * ($slides.length - 1) + 'px'
                });
                $slideContainer.animate({
                    'margin-left': '+=' + width
                }, animationSpeed, function() {
                    currentSlide--;
                });
            } else {
                $slideContainer.animate({
                    'margin-left': '+=' + width
                }, animationSpeed, function() {
                    currentSlide--;
                });
            }
        });




        if ($(".slide img").css('width') == '400px' && $(".slide img").css('height') == '400px') {
            $(".options").css("width", "400px");
            $(".slide").css("width", "400px");
            $("#slider").css("width", "400px");
            $(".video-frame").css("width", "400px");
            var width = 400;

        };



        if ($("#slider img").length < 2) {
            $("#right, #left").css("display", "none");

        };



        if ($("iframe").length > 0 && $("iframe").length < 2) {
            $(".options").css("width", "711px");
            $(".slide").css("width", "711px");
            $("#slider").css("width", "711px");
            $(".video-frame").css("width", "711px");
            $('.slide').hide();
            var width = 711;


        };

        if ($(".slide img").css('width') > '400px' && $(".slide img").css('width') < '711px') {
            $(".options").css("width", "600px");
            $(".slide").css("width", "600px");
            $("#slider").css("width", "600px");
            $(".video-frame").css("width", "600px");
            var width = 600;

        };

    }

    $.ajaxSetup({
        cache: false
    });
    $(".post-link").click(function(e) {
        e.preventDefault()
        var post_link = $(this).attr("href");
        $("#single-post-container").html('<img id="loads" src="http://martinfjeld.com/wp-content/uploads/2015/09/Unknown.gif">');
        $("#single-post-container").load(post_link, function(response, status, xhr) {
            if (status == "error") {
                var msg = "Sorry but there was an error: ";
                $("#error").html(msg + xhr.status + " " + xhr.statusText);
            } else {
                $("#main-content").fadeIn(500);
                $("body").addClass("opens");
                yournewfunction();


            }
        });

        requestCallback.requestComplete(true);
        return false;
    });




});


$(function() {

    var form = $('#ajax-contact');

    var formMessages = $('#form-messages');


    $(form).submit(function(event) {
        event.preventDefault();

        var formData = $(form).serialize();

        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        }).done(function(response) {
            // Make sure that the formMessages div has the 'success' class.
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');

            // Set the message text.
            $(formMessages).text(response);

            // Clear the form.
            $('#name').val('');
            $('#email').val('');
            $('#message').val('');
        }).fail(function(data) {
            // Make sure that the formMessages div has the 'error' class.
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');

            // Set the message text.
            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Oops! An error occured and your message could not be sent.');
            }
        });
    });


});
joyBlanks
  • 6,419
  • 1
  • 22
  • 47
  • This sounds to me like the elements are being replaced on the page and therefore the binding that you made against a particular event, such as, `$('#contact-form').on('submit', function(e){....});` is lost. Are you replacing HTML for the contact form on the page when clicking on a POST? – Ohgodwhy Sep 21 '15 at 17:16
  • 1
    Welcome to Stack Overflow! This question is a little short on information. Can you share what your relevant code and markup? Multiple AJAX calls from one page is not hard to do, it is likely your code and markup are holding you back. – Jay Blanchard Sep 21 '15 at 17:16
  • please add some code so that we can help you... – Niranjan N Raju Sep 21 '15 at 17:18
  • Questions about code MUST include the relevant code IN the question. On this site, we look at your actual code and help you correct it. We don't try to guess what code you have. – jfriend00 Sep 21 '15 at 17:24
  • Please indent your code property to make it readable. You paste your code into http://jsbeautifier.org/ to fix the code indentation, then paste it back into your question. – jfriend00 Sep 21 '15 at 17:26
  • I'm sorry people, I added the (really messy) code right now. Sorry for being mis-informative! –  Sep 21 '15 at 17:26
  • @jfriend00 I did now :) –  Sep 21 '15 at 17:45
  • @Ohgodwhy Every time I try to send an message from my page now, it gets this error in the debugger: Failed to load resource: the server responded with a status of 500 (Internal Server Error) –  Sep 22 '15 at 07:36
  • @JqueryKing thank you ^^ –  Dec 12 '15 at 13:07

1 Answers1

0

Though it's hard to follow exactly what is going on without being able to see the context of your HTML and without you giving us a more concrete description of exactly which line of code fails to execute, this is likely because one Ajax call is replacing a bunch of HTML which clobbers all your event handlers. So, when you then try to do the second Ajax operation, it's click handler is no longer in force so nothing happens.

Replacing a DOM element loses all event handlers that were attached to the original DOM element. Using .html() or assigning to .innerHTML replaces all the DOM elements within that element, thus losing all their event handlers.

The typical solution to this is to either reinstall the event handlers after replacing the content that you want event handlers on or use delegated event handling from a parent element that is not replaced.

Here are some references on delegated event handling:

JQuery Event Handlers - What's the "Best" method

jQuery .live() vs .on() method for adding a click event after loading dynamic html

Does jQuery.on() work for elements that are added after the event handler is created?

Should all jquery events be bound to $(document)?

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Suddenly I get error every time I try to send a message from my site now: Failed to load resource: the server responded with a status of 500 (Internal Server Error) –  Sep 22 '15 at 07:21
  • Is it possible for us to chat somewhere maybe? @jfriend00 –  Sep 22 '15 at 07:25