I have an Send.aspx page that has an uploadify control on it. Upload.ashx handles the file upload.
I am adding a file record to a sql database in the Upload.ashx file and I need to get the ID of that record back from Upload.aspx when it is done.
Can't get it working with Sessions. =( Something to do with an Adobe bug?
What would the best way to handle this be?
Here is the uploadify control:
<script type="text/javascript">
// <![CDATA[
var contestID = $('[id$=HiddenFieldContestID]').val();
var maxEntries = $('[id$=HiddenFieldMaxEntries]').val();
var userID = $('[id$=HiddenFieldUserID]').val();
$(document).ready(function() {
$('#fileInput').uploadify({
'uploader': '../uploadify/uploadify.swf',
'script': '../uploadify/Upload.ashx',
'scriptData': { 'contestID': contestID, 'maxEntries': maxEntries, 'userID': userID },
'cancelImg': '../uploadify/cancel.png',
'auto': true,
'multi': false,
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.png;*.jpeg',
'queueSizeLimit': 1,
'sizeLimit': 4000000,
'buttonText': 'Choose Image',
'folder': '/uploads',
'onAllComplete': function(event, queueID, fileObj, response, data) {
document.getElementById('<%= ButtonCleanup.ClientID %>').click();
}
});
});
// ]]></script>
This took a while for me to figure out. But in retrospect it is extremely simple. For this reason, I mad a video tutorial to help newcomers get started quickly and understand how this awesome control works.
Video Tutorial from start to finish:
http://casonclagg.com/articles/6/video-tutorial-uploadify-asp-net-c-sharp.aspx
I noticed in my own script that I'm using an onComplete event instead of onAllComplete. Unless a config option escapes me, onComplete will trigger after each Upload.aspx call (the files are uploaded individually - again maybe this is configurable). According to the documentation, onAllComplete doesn't actually pass back request data (which makes sense because it's done outside of the scope of the individual uploads).
Anything that Upload.aspx outputs should appear in the response parameter. You can simply have it output the id of the element the script created and the response should contain the appropriate string.
As promised, I made a video tutorial on how to use an Uploadify control in an ASP.Net application.
http://casonclagg.com/articles/6/video-tutorial-uploadify-asp-net-c-sharp.aspx
Hope this helps.
The short answer to my questions is this:
When you return context.Response.Write("foo"); out of your Upload.ashx handler...
And put this in your uploadify control:
'onComplete': function(event, queueID, fileObj, response, data) {
alert(response);
}
An alert box with the word foo will pop up.
You can make this something more complicated like
context.Response.Write("id=55&title=This is the title");
and parse the values out yourself in your OnComplete or OnAllComplete in JQuery.
Related
I'm using Rotativa to generate a PDF file from a view, which works well, but now on the browser I get the raw file thrown at the console, no download dialog box, no warning, nothing. Here's my code:
Controller
public ActionResult DescargarPDF (int itemId) {
var presupuesto = ReglasNegocio.Fachada.Consultas.ObtenerPresupuesto(itemId);
return new Rotativa.PartialViewAsPdf("_PresupuestoFinal", presupuesto) {
FileName = "Presupuesto_" + itemId + ".pdf",
PageSize = Rotativa.Options.Size.A4
};
}
JQuery script:
$(".convertirPDF").on("click", function (id) {
var itemId = $(this).data('itemid');
Pdf(itemId);
});
function Pdf(itemid) {
var id = itemid;
$.ajax({
method: "POST",
url: 'DescargarPDF',
data: { itemId: id },
cache: false,
async: true,
});
};
Button on the HTML
<button class="convertirPDF btn btn-secondary btn-info" data-itemid="#item.Id">PDF</button>
I've tried several codes on the controller (with same result) since the script and view seems to work fine. However, I'm suspecting, maybe the html or the script need some tuning to inform the browser it has to download the file?
Thanks everyone in advance.
I found a solution. It's not elegant, but it works.
So I didn't need to use ajax necessarily to make the request, neither to give function to the button. I'm kind of sure that the issue has something to do with JS and/or jQuery. Nevertheless, there's a simpler way to do this.
I changed my html button to:
PDF
so it looks like a button but it's really a link to my controller¡s method. I also removed the script for that button and now it downloads the file. Not with the name intended, but still.
Thanks to everyone. Happy coding.
UPDATE
I've been working on the same project, and I think I found out why my PDF file was being thrown into console.
The thing is, jQuery makes the request, so jQuery manages the response. Is that simple. If you check official docs for .post(), you'll see the following:
The success callback function is passed the returned data, which will be an XML root element or a text string depending on the MIME type of the response. It is also passed the text status of the response.
As of jQuery 1.5, the success callback function is also passed a "jqXHR" object (in jQuery 1.4, it was passed the XMLHttpRequest object).
Most implementations will specify a success handler.
And I wasn't, so, by default, it just drop it to console. I hope this throws some light into the issue and helps. Happy coding.
I have a program(c#) but the programs needs to work for every timezone, so i created a js script to know the client timezone and this is what i get (and it works) but only if only click action(example button), but i need this to work (run) on my page load is that possible?
This is my script
<script type="text/javascript">
function pageLoad() {
myFunction();
}
function myFunction() {
var localTime = new Date();
var year = localTime.getYear();
var month = localTime.getMonth() + 1;
var date = localTime.getDate();
var hours = localTime.getHours();
var minutes = localTime.getMinutes();
var seconds = localTime.getSeconds();
var calculated_date = hours + ":" + minutes + ":" + seconds;
var div = document.getElementById("demo");
div.innerText = calculated_date;
var client_date = document.getElementById("client_date");
client_date.setAttribute("value", calculated_date);
}
</script>
And this is what i tryed so far
Page.ClientScript.RegisterStartupScript(this.GetType(), "myFunction", "myFunction()", true);
Session["Data"] = client_date.Text;
Response.Redirect("Welcome.aspx");
Thanks anyway for reading my post, hope someone can help on this issue
Yes, it is possible. All you need is to use onload() event.
This would do it
<body onload="myFunction()">
<!-- body elements here -->
</body>
You can execute any function that you want to execute on a page load. I used myFunction because that had to be executed when the page loads.
with javascript
if (document.readyState === "complete") { myFunction(); }
with jquery
$(document).ready(function(){ myFunction(); });
The problem isn't what you think. In all likelihood, this JavaScript *is*set to run when the page loads. And it's probably going to do exactly what you told it to do. The problem is what else you're doing. Note these three lines:
Page.ClientScript.RegisterStartupScript(this.GetType(), "myFunction", "myFunction()", true);
Session["Data"] = client_date.Text;
Response.Redirect("Welcome.aspx");
What you're doing here is:
Set the JavaScript to run when the page loads.
Capture the value of a TextBox from before the page loaded.
Abandon the page entirely and redirect to another page.
So even if the JavaScript code would run, you're not capturing the value it sets. And even if you were capturing that value, you abandon the entire page before it even loads and redirect the user to a different page.
You need to better understand the difference between server-side code, which runs on the server in its entirety before delivering a page to the client... and client-side code, which runs after a page has loaded on the client.
If you need this information from the client, you'll need to get it from client-side code. This code will need to run in a loaded page and then send the value back to the server in some way. Either the page has to execute and then perform the redirect from client-side code, or (probably better) the page can run as normal, make an AJAX post to the server to notify you of this information (time zone), and then the server can respond to the AJAX request with any data the client-side code needs to adjust the page accordingly.
It's not really clear what you're customizing based on the time zone or when you need to know the time zone. But it is clear that you need the client-side code to execute before you can retrieve that value from the client.
Use System.Web.ScriptManager Like this :
Page.ClientScript.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "myFunction();", true);
Session["Data"] = client_date.Text;
Response.Redirect("Welcome.aspx");
Well you can't store the value within a hidden field and then read result, but what you can do is store the timezone offset as a cookie and then read that on the server after the page reloads.
This article explains it perfectly
http://prideparrot.com/blog/archive/2011/9/how_to_display_dates_and_times_in_clients_timezone
i am in my way to apply my website users to add comment using face book in my account in my website . i have created my app using this link
and then tried the below code
<div id="fb-root" ></div>
<script>
window.fbAsyncInit = function () {
FB.init({
appId: 'my API ID',
status: true,
xfbml: true
});
};
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) { return; }
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
but there is no result and nothing appears to he screen???
any help
You're missing fairly considerable amount of code still... The code you posted will just bring in the Facebook SDK.
Have a look at my comment in this thread which will illustrate how to properly import the SDK.
Once you have it imported, you have to define the HTML in your page to actually place the comment box on the page as well as some other stuff for how it behaves. You're going to want to check out (and sign up for) the Facebook developers page, which offers some useful, yet seriously lacking, information on how to load comment blocks, like buttons and how to use OpenGraph stuff. I'd give you the link there, but corporate policy prevents me from accessing Facebook.
I have a jQuery Countdown Timer that I am using, and I need to be able to access my Database and perform some calculations and then return the result:
$('#expireMessage').countdown({until: shortly,
expiryText: '<div class="over">It\'s all over</div>'});
$('#expireMessageStart').click(function() {
shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5.5);
$('#expireMessage').countdown('change', {until: shortly});
});
Now, the above code just displays a countdown timer, and counts down. And when it hits
00:00:00
it displays a message "It's all over".
But what I need it to do is display a different message depending on the result of the DB calculations.
The DB work I can do, but I'm not sure how to go about retrieving that info from the database when using jQuery. I'd really appreciate your help.
Thank you
You need to set up something on the server side to talk to the database for you, then return the result in JSON format. What that something is depends on what your server-side code is written in. Are you using PHP? Java? ASP.NET?
I work primarily in ASP.NET, so one way I might tackle this is adding a WebMethod to my page that executes a database query, builds the message, serializes it to JSON, and returns it to the client.
In your JavaScript, you'll want to execute either an XMLHttpRequest (if you're using regular JavaScript) or a jQuery AJAX request.
Here's a very simple example of what a jQuery AJAX call might look like:
$.ajax({
url: 'http://mysite.com/getmymessage',
success: function( data ) {
// Here's where you'd update your countdown display, but I'm just writing to the console
console.log( 'The server says: ' + data.myDbResult );
}
});
I need to refresh sections of my page to update when there is new data! what do i do? use jquery?
examples:
Yes, jQuery's great for this. Look into these methods:
http://api.jquery.com/category/ajax/
jQuery is usually not needed for basic AJAX. A simple example could be as follows:
liveSection = document.getElementById('latest-news');
request = new XMLHttpRequest;
request.open('GET', '/news-ajax', true);
request.send(null);
request.addEventListener('readystatechange', function() {
if (request.readyState == 4 && request.status == 200)
liveSection.innerHTML = request.responseText;
}, false);
If you're using Asp.NET, why not use an UpdatePanel? It's simple and reliable.
Edit
I just re-read your question and it looks (based on how you worded it) that you want to update a user's web page when the data changes on the server. I just want to make sure you understand that in a web app, the server can't trigger the browser to do anything. The server can only respond to browser requests, so you'll need to have the browser poll the server periodically.
I've created a simple example (using jQuery) to help you understand the breakdown of the things that will need to happen, which are:
1 - Periodically polling the server (via ajax) using Javascript's setTimeout to check that what is loaded into the browser is the latest content. We can achieve this by fetching the latest item ID or whatever and comparing it to a variable, which was initialised when the page first loaded.
2 - If the item ID does not match (a bit of an oversimplification) then we can assume that there has been an update, so we replace the content of some element with some content from some page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function getLatestStuff() {
// fetch the output from a context which gives us the latest id
$.get("isthereanupdate.aspx", function(response) {
// we have the response, now compare to the stored value
if(resp != lastItemId) {
// it's different, so update the variable and grab the latest content
lastItemId = response;
$("#latestStuffDiv").load("updates.aspx");
}
});
}
$(document).ready(function() {
// the value which initializes this comes from the server
var lastItemId = 7;
setTimeout(getLatestStuff, 10000);
});
</script>
If you want to update when there is new data, you should look into comet or pubsubhubbub. jQuery can help you display the data in a pretty way, but you'll need to write stuff on the serverside to send the data.