I am developing ASP.NET MVC 4 application. I am trying to change src attribute after controller sent data to a view, however all my attempts have no result. A script at a View:
<script type="text/javascript">
$(document).ready(function () {
$('#fileupload').fileupload({
dataType: 'json',
url: '/Home/UploadFiles',
autoUpload: true,
done: function (e, data) {
$('.file_name').html(data.result.name);
$('.file_type').html(data.result.type);
$('.file_size').html(data.result.size);
$('.file_source').attr('src', 'D:/somePhoto.jpg'); //this row does not set 'src' of <img/>
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('.progress .progress-bar').css('width', progress + '%');
});
});
</script>
<img class="file_source" src="" /> <!--src attribute is just empty--->
Could you tell please where I’ve made an error?
this row is not working:
$('.file_source').attr('src', 'D:/somePhoto.jpg'); //this row does not set 'src' of <img/>
The attribute 'src' of tag is not altered to src="D:/somePhoto.jpg".
Any help would be greatly appreciated.
Have you tried assigning a valid image location from the web inside the image source? I am pretty sure, D:\somePhoto.jpg is the location at server side. If that is the case, then javscript does not know how to get it, because js runs on client side, and after you have already sent the data from controller, there is nothing it could do.
First test with an image available from web to test, such as this - http://sci8.com/wp-content/uploads/2014/10/test-all-the-things.jpg
So change your code to -
$('.file_source').attr('src', 'http://sci8.com/wp-content/uploads/2014/10/test-all-the-things.jpg');
If that works ( and I am pretty sure, it will), then you know the reason why. Just keep the somePhoto.jpg somewhere inside the Content folder of your project and use that url.
for example
$('.file_source').attr('src', 'http://<hostaddress>/content/image/somePhoto.jpg');
If you are still facing problems, please let me know.
Related
I have a 3D model being rendered on my site through an image rotator .xml config file. This feature works but I am attempting to render a completely different .xml in place of the previous file through a JS on change event.
I have done a fair bit of reading in order to solve this issue, although I have not found an answer. I have already tried to make the JQuery script into a function as seen below:
function updateModel(xml_file_path) {
console.log('updating room model...');
console.log('xml_file_path: ' + xml_file_path);
// clear past model
$("#wr360PlayerId").empty();
jQuery('#wr360PlayerId').rotator({
licenseFileURL: 'license.lic',
configFileURL: '/static/360_assets/' + xml_file_path,
graphicsPath: '/static/img/basic',
zIndexLayersOn: false,
responsiveBaseWidth: 600,
responsiveMinHeight: 0,
googleEventTracking: false,
});
console.log('rendering: ' + xml_file_path);
}
// clears the old model then updates the configFileURL to the new model
This was successful in clearing the previous model although when I inspect the new model the images used by the image rotator are not being loaded and nothing is displayed.
wr360 documentation
I've also read through the documentation for wr360 above and found a few different ways of loading the image rotator on my site. I've gone through each and attempted to make it update using similar methods as JQuery but each had their own oddities that were difficult to overcome.
There's not much to code to this as for most of it is created dynamically on page load, but I'll try to provide all code necessary below:
js
function updateModel(xml_file_path) {
console.log('updating room model...');
console.log('xml_file_path: ' + xml_file_path);
// clear past model
$("#wr360PlayerId").empty();
jQuery('#wr360PlayerId').rotator({
licenseFileURL: 'license.lic',
configFileURL: '/static/360_assets/' + xml_file_path,
graphicsPath: '/static/img/basic',
zIndexLayersOn: false,
responsiveBaseWidth: 600,
responsiveMinHeight: 0,
googleEventTracking: false,
});
console.log('rendering: ' + xml_file_path);
}
$(document).ready(function(){
$('#rooms').on('change', function() {
updateModel(room.xml_path);
console.log('model updated');
});
});
// truncated for simplicity
html
<div id="wr360PlayerId" class="wr360_player" style="background-color:#FFFFFF;">
</div>
The xml file path is getting passed correctly (checked by the console.log('xml_file_path: ' + xml_file_path);) it just doesn't render the second rotator.
$('#rooms') is a select field, and room.xml_path is the selected rooms .xml file path. With this being said, ideally, the on change event would show the selected model and if the selection changes again it should render the new model (instead of nothing like it currently does).
Either I am missing something or it is impossible to update a model without refreshing the page, either way, any help is appreciated!
You can actually use,
apiObj.reload(xml_path);
to simply reload the image rotator with a new xml file path.
I need to be able to change the filebrowserUploadUrl of CKEditor when I change some details on the page, as the querystring I pass through is used by the custom upload process I've put in place.
I'm using the JQuery plugin. Here's my code:
$('#Content').ckeditor({
extraPlugins: 'autogrow',
autoGrow_maxHeight: 400,
removePlugins: 'resize'
});
$("#Content").ckeditorGet().on("instanceReady", function () {
this.on("focus", function () {
// Define browser Url from selected fields
this.config.filebrowserUploadUrl = filebrowserUploadUrl: '/my-path-to-upload-script/?ID1=' + $("ID1").val() + '&ID2=' + $("#ID2").val();
});
});
This works fine the first time, but if I come out of the dialogue and change the value of #ID1 and #ID2, it keeps the previous values. When I debug, the filebrowserUploadUrl is set correctly, but it doesn't affect the submission values. It seems the config values are cached.
Is there any way to change a config value on the fly?
Currently I don't see any possibility to change this URL on the fly without hacking.
Take a look at http://dev.ckeditor.com/browser/CKEditor/trunk/_source/plugins/filebrowser/plugin.js#L306
This element.filebrowser.url property is set once and as you can see few lines above it will be reused again. You can try to somehow find this element and reset this property, but not having deeper understanding of the code of this plugin I don't know how.
Second option would be to change this line #L284 to:
url = undefined;
However, I haven't check if this is the correct solution :) Good luck!
BTW. Feel free to fill an issue on http://dev.ckeditor.com.
I solved this by reloading the editor whenever a change occurred; I actually went through the source code for the browser plugin etc, but couldn't get any changes to work (and of course, I really didn't want to change anything for future upgrades).
function setFileBrowserUrl() {
// Remove editor instance
$("#Content").ckeditorGet().destroy();
// Recreate editor instance (needed to reset the file browser url)
createEditor();
}
function createEditor() {
$('#Content').ckeditor({
filebrowserUploadUrl: '/my-path-to-upload-script/?ID1=' + $("ID1").val() + '&ID2=' + $("#ID2").val(),
extraPlugins: 'autogrow',
autoGrow_maxHeight: 400,
removePlugins: 'resize'
});
}
Then I call setFileBrowserUrl every time the relevant elements on the page change. Not ideal, but it works for my purposes :)
This post discusses how to inform the user via a progress bar by calculating the percentage of the file being downloaded by a www::mechanize Perl script.
I need to inform my user of a www::mechanize script's progress but not necessarily in percentage remaining. The script is migrating through a user's account and picking up data, which can vary significantly in size so the percentage factor is unknown.
If I can show "progress" via some js DOM div writing (in the dialog that shows a "loader" image while the perl script is running) then that would suffice.
Can I inject js script like:
<script>
$('#formboxtext').html('Logging into account ...');
</script>
into the Perl script to show progression to my user? Or does the Perl script have to return before the DOM will get updated? (The answer appears to be "no".)
Are JavaScript::SpiderMonkey and WWW::Scripter modules I need to make this happen, or is the solution more simple?
EDIT:
I am expanding a PHP-based CMS. I have written a screen-scraping script using Perl and the module www::Mechanize which traverses several pages of a user's account on another site for retrieval into mySQL databases. I will display the collected content in a php form for the user to save once the Perl script is completed. The collection process will range from 10 seconds to a minute. I would like to display progression as the script navigates the user's account pages collecting information.
To begin, I supply the user a jQuery modal dialog (calling a php file to fill it's contents with a form of username and password inputs) used to login to their personal account. I show a loader image in this dialog and a sentence asking for patience, but I would like to use jQuery to rewrite this sentence (div) as the Perl script navigates through pages, sending back progress to display; such as, "I'm here now. Now I'm over here." If an error occurs (i.e. bad login) then I can rewrite the modal dialog and offer solutions per usual. If success, then I would close the dialog and display the collected information in form inputs ready for saving into my database - on the php page that spawned the modal dialog.
If all of this entails multiple DOMs, forking processes and returning control from one script execution to another... then I am definitely over my head. BUT, I would like to learn it. :) I would appreciate an overview on what to read and learn. If it's actually much simpler than I realize then I would appreciate that answer too.
Thanks to daxim and reinierpost for their patience and advice. Thanks for any help.
The Answer:
Recap: For me, I decided to fake the progress bar showing progression by estimating the time it would take. That has worked nicely. This post shows how you can dup output from a perl script back to the calling php script, but then feeding that information back to the original DOM was becoming too complex for it's worth. It was made more complex by various parameters passed to the perl script which changed the progression and output. "Faking it" proved a nice solution. Hey, now I see why my girlfriend does it! :)
PS. I gave the green checkmark to daxim because he has answered other questions of mine and been a big help to me, even though he was sort of shooting in the dark on this one.
Instead of printing progress to STDOUT as in https://stackoverflow.com/a/1938448, expose the number as a Web service. This should suffice:
sub {
return [200, [Content_Type => 'text/plain'], [$PROGRESS]]
}
On the client side, use jQuery get to poll the Web service every half second or so and jQuery Progressbar to display it.
Edit: code example
use 5.010;
use strictures;
use DBI qw();
use Plack::Request qw();
use POSIX qw(floor);
use Forks::Super qw(fork);
use WWW::Mechanize qw();
sub db_connect {
return DBI->connect('dbi:SQLite:dbname=/var/tmp/progress.db');
}
sub {
my ($env) = #_;
my $req = Plack::Request->new($env);
if ('/progress' eq $req->path_info) {
return [200,
[Content_Type => 'text/html'],
[db_connect->selectrow_array('select progress from progress')]
]
} else {
fork(sub => sub {
state $total = 0;
my $dbh = db_connect;
$dbh->do('delete from progress');
$dbh->do('insert into progress (progress) values (0)');
WWW::Mechanize->new->get(
'http://localhost:5000/VBoxGuestAdditions_4.0.4.iso', # large-ish file
':read_size_hint' => 1024**2,
':content_cb' => sub {
my ($data, $response, $proto) = #_;
$total += length($data);
my $size = $response->header('Content-Length');
$dbh->do(
'update progress set progress = ?', {}, floor(($total/$size)*100)
);
sleep 1;
},
);
}) unless defined db_connect->selectrow_array('select progress from progress');
return [200,
[Content_Type => 'text/html'],
[q~<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" />
<style>
#progress { width: 80em; height: 5em; border: 1px solid black; }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script>
jQuery(document).ready(function() {
// TODO: stop the timer if progress == 100 or no response
var timer = setInterval(function() {
jQuery.ajax({ async: false, cache: false, dataType: 'html', url: 'http://localhost:5001/progress' }).done(function(progress) {
jQuery('#progress').progressbar({ value: parseInt(progress) });
});
}, 500);
});
</script>
</head>
<body>
<h1>downloading your stuff</h1>
<div id="progress"><div>
</body>
</html>~]
]
}
};
I'm using blueimp JQuery file upload script to fancy the uploading of files. You can download it here: https://github.com/blueimp/jQuery-File-Upload/zipball/master (ZIP).
Here is a snippet of the JavaScript code:
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
// Dirs
url: 'accesspoint/upload.php',
uploadDir: 'accesspoint/files/',
thumbnailsDir: '',
// Options
autoUpload: 1,
maxNumberOfFiles: 1,
limitConcurrentUploads: 1,
maxFileSize: 1000000,
});
// Load existing files:
$.getJSON($('#fileupload form').prop('action'), function (files) {
var fu = $('#fileupload').data('fileupload');
fu._adjustMaxNumberOfFiles(-files.length);
fu._renderDownload(files)
.appendTo($('#fileupload .files'))
.fadeIn(function () {
// Fix for IE7 and lower:
$(this).show();
});
});
// Open download dialogs via iframes,
// to prevent aborting current uploads:
$('#fileupload .files a:not([target^=_blank])').live('click', function (e) {
e.preventDefault();
$('<iframe style="display:none;"></iframe>')
.prop('src', this.href)
.appendTo('body');
});
});
Now take a look at http://www.mcemperor.nl/test/appstest/blueimpjqueryfileupload/example/. We can upload a file, and it works.
Now if I upload a file which is larger than the maximum file size defined in the JavaScript snippet above, then you'll see something like this.
Perfect, works as expected. (Note that I have set the maximum upload size to 1000000 bytes, so if you upload a file of 1 MB, it states the file is too big.)
But... Now when I paste the same script (with some small modifications) as a module into a framework of some kind, the script won't work properly; I get this:
As you can see, The 'delete entry' icon is smaller (it's supposed to be square) and nothing happens when I click on it.
I do not have any clue what can be the problem. Does anyone have ideas?
Can using this script inside another <form> be the problem?
Can multiple elements with the same id be the problem?
Can collisions between javascripts (e.g. redefining functions or objects) be the problem?
I am not sure how to fix the scripts, but maybe a workaround would be to locate the element using FireBug and patch it with a css entry or a jquery function. Also, you might take a look at jquery.fileupload-ui.css which is the css file responsible for overriding jqueryUI elements for the control. I do know that the buttons are styleable independently. Again, I am not for certain, but there may be a class added via script to change the icon on the delete button.
is it possible using fancybox to post a var to the iframe when opens?
I currently have:
function fancyBoxLoad(element) {
var elementToEdit = $("#" + $(element).attr("class"));
var content = encodeURIComponent($(elementToEdit).outerHTML());
$.fancybox(
{ 'href': 'loadEditor.php' },
{
frameWidth: 750,
frameHeight: 430,
overlayShow: true,
ajax: {
type: "POST",
data: 'content=' + content
},
type: 'iframe'
}
);
}
It does seem that if I take away type: 'iframe' it will post data but it doesn't appear to be in the iframe and if I take away ajax: { type: "POST", data: 'content=' + content } instead it will open in an iframe but not post the data (the example above does the same)
So my question being can it be done?
If you're simply trying to put content in a iframe, why don't you use fancybox to create the iframe, and once you know it's been created, then access it via the reference that fancybox returns to you and set your content that way. I'm not sure you want to send the content to the server and back. Just wait for the iframe to load, then on ready, query an element within it and set the content.
Looking at the source for Fancybox v1.3.1 they are in fact mutually exclusive. If you don't feel comfortable diving into the source code and editing the plugin, you might try using GET variables in your HREF as a work around. It should effectively work like a post as it is an AJAX call, just make sure the backend can receive the GET variables.