Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggers doesn't work on content loaded via ajax

I have following problem. I was forced to rewrite all below functions to create this:

$(document).on("change","#type_of",function(){

instead of this:

$('#type_of').on('change', function () {

I did that because I am manipulating DOM and after load content via ajax all functions ceased to operate. Now they work half because triggers doesn't do they job. All below code is added to page index.php. In this page I have div #content and I am reloading its contents via ajax. All of the following functions pertain to only that div. My question is how to create proper triggers for this functions?

One more question: is that proper syntax in my case $(document).ready(function() { ?

$(document).ready(function() {  

    // ALSO SOME CODE HERE (variables and etc.)

    $(document).on("change","#type_of",function(){
        // FUNCTION CODE
    })


    $(document).on("change","#order_form",function(){
        // FUNCTION CODE
    })
    $( '#type_of, #orer_form' ).trigger( 'change' );
})


$(document).on("change","input[name=window-type]",function(){
    // FUNCTION CODE
}


$(document).on("change","#shutter_type",function(){
    // FUNCTION CODE
})
$( '#shutter_type, #input[name=window-type]' ).trigger( 'change' );

Here is also one of my ajax calls that I use to reload content of div #content

function displayPhoto(photoid){
    $.ajax({
        url: "includes/displayphoto.php?photo_id="+photoid
    }).done(function(data) {    
        if (data == false)
        {
            alert ("ERROR");
        }
        else
        {
            $('#content').html(data);
        }
    });
}

$(document).on("click",".photo-id",function(){
    var photoid = $(this).data("photoid");
    displayPhoto(photoid);
});
like image 381
Walter White Avatar asked Nov 01 '22 09:11

Walter White


2 Answers

You're trying to .trigger() events on Elements, which don't have any direct event handler. Since you are using event delegation, you have to .trigger() the event on the Element itself, in this case, the element with the id of #type_of, #order_form and all other Elements which events you're handling on your Document Node.

$( '#type_of, #orer_form' ).trigger( 'change' );
like image 162
jAndy Avatar answered Nov 10 '22 04:11

jAndy


Try this idea, I hope this will help you.

$(document).on("change","#select1",function(){
   //ajax request here that can pass to the params
    $("#test").trigger('click',[$(this).val()]);
});

$(document).on("click","#test",function( event, param1 ) {
   //ajax request here
  $("#result").html(param1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#" id="test" style="display:none;">trigger</a>

<select id="select1">
<option>1</option>
<option>2</option>  
</select>


<div id="result">
  
</div>
like image 38
frogcoder Avatar answered Nov 10 '22 03:11

frogcoder