Sam Skirrow Sam Skirrow - 5 months ago 15
Javascript Question

POST data attributes on click using ajax

I have the following html:

<div class="actor_container span-3 column" data-url="http://www.spotlight.com/5094-1276-6177" data-age-min="31" data-age-max="40" data-height="180" data-weight="72" data-gender="male" data-eye="green">
....
</div>


Is it possible to POST each data attribute when the user clicks the image, and then in another file I can use $_GET to retrieve them?

So for example, something like this:

$('.actor_container').on("click", function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: $(this).data("url"),
...rest of code goes here...
});
}); //on


Then in my PHP file, use something like:

echo htmlspecialchars($_GET['url']);


UPDATE
From answer below, here is my JS code (I've posted the full on click function so you can see):

$('.actor_container').on("click", function (e) {
$('.loading_overlay').show();
$('#actor_data').hide();
$('#actor_data_container').css('top','0');
e.preventDefault();
$.ajax({
url: "http://79.170.44.105/samskirrow.com/nial/wp-content/plugins/nial-customizations/front-end/actor-profile.php?url=" + $(this).data("url"),
type: 'GET',
success: function(res) {
var data = $.parseHTML(res);
// append all data
$('#actor_data').html(data);
$('#actor_data').show();
$('.loading_overlay').hide();
}
});


$.ajax({
type: 'POST',
data: ({
"age-min" : $(this).data("age-min"),
"age-max" : $(this).data("age-max")
}),
});

});


and then in my PHP file I have:

var_dump($_POST);


which returns

array(0) { }

Answer

There is a way to serialize your data :

$('.actor_container').on("click", function (e) {
    e.preventDefault();
    var length_data = Object.keys($(this).data()).length;
    var data = [];
    for (i = 0; i < length_data; i++) {
      var str = Object.keys($(this).data())[i]
      data.push({ name : str, value : $(this).attr('data-'+str) })
    }
    $.post("your_page.php", data);
})

And on your php site, you can access to data with :

    $_POST['url']
    $_POST['age-min']
    $_POST['weight']
    ...

For try the serialization, here the JSFiddle

UPDATE

Mix your 2 ajax call :

$('.actor_container').on("click", function (e) {
    e.preventDefault();
    $('.loading_overlay').show();
    $('#actor_data').hide();
    $('#actor_data_container').css('top','0'); 
    var length_data = Object.keys($(this).data()).length;
    var data = [];
    for (i = 0; i < length_data; i++) {
      var str = Object.keys($(this).data())[i]
      data.push({ name : str, value : $(this).attr('data-'+str) })
    }
    $.ajax({
      url: "http://79.170.44.105/samskirrow.com/nial/wp-content/plugins/nial-customizations/front-end/actor-profile.php",
      data : data,
      type: 'GET',
      success: function(res) {
        var data = $.parseHTML(res); 
        // append all data
        $('#actor_data').html(data);
        $('#actor_data').show();
        $('.loading_overlay').hide();

    });
Comments