akaBase
akaBase

Reputation: 2250

set attribute value dynamically from from event

I need to set the value of an attribute to show 'x' amount of stars but need to run an event to my database to get the average and use that number?

here is this HTML with the 'data-rateit-value' attribute id like to modify dynamically.

<div id="randomtest" data-productid="randomtest" class="rateit" data-rateit-value=""></div>

i tried this just to modify it without an event to query the database and it didnt set it? so need some advise before i go on to including the event.

$('#randomtest').attr( 'data-rateit-value','4');

but once im able to i will be able to set it dynamically like i have made a basic demo of below? if not some further guidance would be much appreciated.

$.ajax({
    url: 'currentvalue.php',
    data: { id: productID, value: value },
    type: 'POST',

    success: setCurrentValue
});

function setCurrentValue(data) {
    $('#randomtest').attr( 'data-rateit-value'.append(data));
}

thanks for any help

EDIT i changed the query and results to this and it alerts with the integer but still doesn't append to the attribute

$.ajax({
    url: 'currentstars.php', //your server side script
    data: { id: productID, value: value }, //our data
    type: 'POST',

    success: function(results) { 
    alert(results);
    $('.rateit').attr( 'data-rateit-value'.append(results))
    }
});

i don't know if this helps with anyone trying to work out why it's not working?

Upvotes: 0

Views: 295

Answers (3)

akaBase
akaBase

Reputation: 2250

I got it working!!

$.ajax({
    url: 'currentstars.php',
    data: { id: productID, value: value },
    type: 'POST',

    success: function(results) { 
    $('.rateit').rateit('value', (results));
    }
});

with that query and function i'm able to update to the average rating when both the page is loaded and when a rating is selected!!!

what a nightmare that was lol :)

Upvotes: 0

Sai Prasad Sabeson
Sai Prasad Sabeson

Reputation: 103

You are trying to use .append on attributes,which i don't think is the right way. Try this-

$.ajax({
    url: 'currentvalue.php',
    data: { id: productID, value: value },
    type: 'POST',
    success: function(){setCurrentValue(data);}
 });

function setCurrentValue(data) {
    $('#randomtest').attr( 'data-rateit-value',data);
    //Or $('#randomtest').data( 'rateit-value',data);
}

Upvotes: 0

dehrg
dehrg

Reputation: 1741

First I would say you should check that you are getting back what you expect from the server:

function setCurrentValue(data) {
    console.log(data);
    ...
}

What is the structure of data?

I'm not sure what you want to happen with the setCurrentValue function, you have some syntax errors in the line $('#randomtest').attr( 'data-rateit-value'.append(data));. attr can be called like attr(attribute, value) so maybe $('#randomtest').attr( 'data-rateit-value', data); is closer to what you need

Upvotes: 1

Related Questions