Reputation: 1322
I'm new in yii and I have this script in one of my views:
$('#div_exams').on('click', 'a[id^="download"]', function(e) {
e.preventDefault();
var fileName = e.target.id;
$.ajax({
type: "POST",
url: "<?php echo Yii::app()->createUrl("exams/downloadExam",array('fileName'=>'HERE I NEED TO PASS FILENAME')); ?>",
success: function(jsonResponse) {
},
error: function() {
}
});
});
So my question is, how can I pass the var fileName in javascript to create the url in yii?
Thank you very much :)
Upvotes: 1
Views: 6700
Reputation: 8607
You could also pass the filename as POST
data if you use the data
option in jQuery.ajax()
:
$('#div_exams').on('click', 'a[id^="download"]', function(e) {
e.preventDefault();
var fileName = e.target.id;
$.ajax({
type: "POST",
url: "<?php echo Yii::app()->createUrl("exams/downloadExam"); ?>",
data: {fileName: fileName},
success: function(jsonResponse) {
},
error: function() {
}
});
});
Upvotes: 1
Reputation:
Option 1: Build a URL template in Yii and interpolate each needed filename into it:
var baseUrl = <?php echo json_encode(Yii::app()->createUrl("exams/downloadExam",array('fileName'=>'__PLACEHOLDER__'))); ?>;
$('#div_exams').on('click', 'a[id^="download"]', function(e) {
...
var url = baseUrl.replace('__PLACEHOLDER__', encodeURIComponent(filename));
...
}
Option 2, probably cleaner: Build each URL in Yii, attach it to the link as a data- attribute, read it using JS:
// when building each download link:
<?php echo CHtml::link('Download link, 'some url', array(
'id' => 'download_1234',
'data-download' => Yii::app()->createUrl("exams/downloadExam",array('fileName'=>'the file')),
));
// in the script
$('#div_exams').on('click', 'a[id^="download"]', function(e) {
...
var url = $(this).data('download');
...
}
Note that neither solution abuses the id
attribute like you're doing now.
Upvotes: 4
Reputation: 5981
If I understand your problem correctly, you need to create an URL for downloading something with Javascript?
That is not possible. JS does not work server side so you can not create an URL using PHP code inside the JS function once its loaded in the client (browser).
You can however, have an action in Yii that you pass a value and it echoes a URL, you get that URL with Jquery (responseText I think) and use it whenever you want.
Upvotes: 1