How to set slider element position with javascript?

rbuelund

Member
I have 5 sliders on a form which all needs to be set to the latest entry in the database. The php works fine and returns the values on my ajax call - but how do I actually set the sliders ?
I have this javascriptcode that is triggered by another element:

var thisElement = Fabrik.getBlock('form_1').elements.get('bqwez_fabrik_mains___subject1');
var mySubject = thisElement.get('value');

getScores(mySubject);

function getScores(mySubject)
{
var url = "index.php?option=com_fabrik&format=raw&task=plugin.userAjax&method=getScores&subject=" + mySubject;
var slider1 = Fabrik.getBlock('form_1').elements.get('bqwez_fabrik_mains___slider1');
var slider2 = Fabrik.getBlock('form_1').elements.get('bqwez_fabrik_mains___slider2');
var slider3 = Fabrik.getBlock('form_1').elements.get('bqwez_fabrik_mains___slider3');
var slider4 = Fabrik.getBlock('form_1').elements.get('bqwez_fabrik_mains___slider4');
var slider5 = Fabrik.getBlock('form_1').elements.get('bqwez_fabrik_mains___slider5');

new Request({url:url,onComplete: function(response)
{
if (response !== '')
{
scoresArray = response.split(",");
alert(slider1.value);
slider1.value = scoresArray[0];
slider2.value = scoresArray[1];
slider3.value = scoresArray[2];
slider4.value = scoresArray[3];
slider5.value = scoresArray[4];
alert(response);

}
else
{
alert("Kunne ikke s?tte tidligere scoring! Dette er formentlig ikke et problem, s? forts?t bare.");
}
}
}).send();
}



I believe these lines are wrong : slider1.value = scoresArray[0]; ??
 
The simplest way to do that is to return JSON from your PHP. So if your PHP has an array of scores...

Code:
echo json_encode($scores);

... or if you have a comma seperated string of scores ...

Code:
echo json_encode(explode(',', $scores));

... then in the first line of your JS AJAX response handling ...

Code:
var scoresArray = JSON.decode(response);

JSON stands for JavaScript Object Notation, and shipping data structures in and out of JS from other sources is what it was designed for. Which is why using it here is the way to go.

-- hugh
 
This worked just fine for me:

slider1.mySlide.set(parseInt(scoresArray[0]));
slider2.mySlide.set(parseInt(scoresArray[1]));
slider3.mySlide.set(parseInt(scoresArray[2]));
slider4.mySlide.set(parseInt(scoresArray[3]));
slider5.mySlide.set(parseInt(scoresArray[4]));
 
Yup, that's what you need for setting the values once you have the data in the array, but you should still get in the habit of using JSON to encode your response at the server end, and decode it in the JS. All kinds of issues can arise if you don't do that, and rely on comma separating and splitting strings.

-- hugh
 
Back
Top