6

im still a beginner with JS.

I use ajax for filtering content in wordpress. So I need to send 2 variables to PHP. But the problem is once i've navigated further one of the variables needs to change. In html the Data gets changed, but jquery which runs on (document).ready uses the initial variable. How can i make the variable refresh on ajax complete?

here is my code

jQuery(document).ready(function($) {
$('.tax-filter').click( function(event) {

    if (event.preventDefault) {
        event.preventDefault();
    } else {
        event.returnValue = false;
    }

    var selecetd_taxonomy = $(this).attr('id');
    var personData = $('#content').data('id');


    data = {
        action: 'filter_posts',
        afp_nonce: afp_vars.afp_nonce,
        taxonomy: selecetd_taxonomy,
        person: personData,
    };


    $.ajax({
        type: 'post',
        dataType: 'json',
        url: afp_vars.afp_ajax_url,
        data: data,
        success: function( data, textStatus, XMLHttpRequest ) {
            $('.showContent').html( data.response );
        },

        error: function( MLHttpRequest, textStatus, errorThrown ) {
            $('.projects').html( 'Error 404' );
        }
    })
});
});

From another function the .data('id') in html gets a new value, but I need the jQuery to get the new value aswell

EDIT:

I need the personData to be updated in my click function. The data-id value of #content gets updated on ajaxComplete. It is done by another click function which gets the value from PHP.

9
  • 2
    if (event.preventDefault) { why are you doing that check in jQuery? Commented Apr 22, 2015 at 12:51
  • possible duplicate of update javascript variable with ajax in real-time Commented Apr 22, 2015 at 12:52
  • "From another function the .data('id') in html gets a new value, but I need the jQuery to get the new value as well" Get the value where? Where is it setting the new id? Commented Apr 22, 2015 at 12:52
  • 1
    you did not mention what variable you want to change Commented Apr 22, 2015 at 12:53
  • The $('#content').data('id'); gets a new value on ajaxComplete. I need the var personData to be updated in the function I posted above. Commented Apr 22, 2015 at 12:56

1 Answer 1

2

Update the data-id using $('#content').data('id', 'newValueHere') instead of $('#content').attr('data-id', 'newValue')

See fiddle and note that changing the attribute with .attr() doesn't work, but .data() does.

Sign up to request clarification or add additional context in comments.

1 Comment

this and correcting a few typos fixed my problem! Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.