Question

I am trying to send the data object with an AJAX request when opening up a Magnific Popup. However, it seems like $(this) is not being translated correctly within the plugin.

Consider this code:

<div class="my-div">
  <a href="/path/to/file.php" data-name="John" data-location="Boston">Click here</a>
</div>

$('.my-div a').magnificPopup({
  type: 'ajax',
  ajax: {
    settings: {
      data: $(this).data()
    }
  }
});

The data object is not properly returned. However, if I replace the data line with this:

data: { name: "John", location: "Boston" }

Then I'm able to reference those objects in the $_GET.


EDIT: To further the fact that $(this) is not functioning properly within magnificPopup, I changed the data line to:

data: { href: $(this).attr('href') }

Which still returns nothing.


Everything I've done seems to point at $(this) not being respected within the plugin. How can I get the data objects from the original anchor tag and pass them on to the AJAX request?

Was it helpful?

Solution

$('.my-div a').magnificPopup({
      type: 'ajax',
      elementParse: function(item) {
           this.st.ajax.settings = item.el.data();
      }
});

OTHER TIPS

I've found that the best way to call an ajax response with data attributes in the request is simply to call an ajax request on click instead of directly calling magnificpopup. Then simply insert the response into a standard inline mfp.

$('a.popup').magnificPopup({
    type: 'ajax',
    ajax: {
        settings: {
            type: "POST",
            url: '/ajax.php',
            data: {
                action : 'ajax_action',
                postid : this.currItem.el.data('id')
                // this doesn't actually work because 'this.currItem'
                // is only accessible in a callback
            }
        }
    }
});

Do this instead:

$('a.popup').click(function(){
    $.ajax({
        type: "POST",
        url: '/ajax.php',
        data: {
            action : 'ajax_action',
            postid : $(this).data('id'),
            //$(this).data() works because it's a standard AJAX call
        },
        success: function(data){
            $.magnificPopup.open({
                type: 'inline',
                items: {
                    src: data
                }
            })
        }
    });
});

You can try this

data: { name:$(this).data('name'), location:$(this).data('location')  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top