I'm developing a Qt program that contains an OpenStreetMap application as a HTML page and this page is able to access a database -via submitting an ajax form that contains the start and end dates of queries- in order to retrieve and visualize queries on the map. I would like to move this querying process to Qt from the HTML/Javascript part. So far I managed to interact with the browser via Qt but I still have a problem that is below:
1) The fetch queries button of Qt is clicked and an alert box is supposed to pop up saying that Ajax POST is failed -the database is not on my current laptop and I should be getting the error when I click either the HTML Browser window's fetch queries button or the Qt's fetch button-
2) But also, whenever I click the Fetch queries button of the HTML Browser, it displays the POST warning but also displays extra POST warning alert boxes depending on how many times I have clicked the Qt's Fetch queries button. -for example if I have clicked the Qt's fetch queries button 5 times in a row and then clicked the HTML window's fetch button once, I get 6 POST failed messages in a row-
The HTML code is like the following:
<form id="ajaxForm" action="index.php" method="post">
Start <input type="text" name = "date1" id = "datepicker" value = "2011-07-13" style = "width:70px">
<input type="text" name = "time1" id = "timepicker1" value = "00:00" style = "width:40px">
End <input type="text" name = "date2" id = "datepicker2" value = "2011-07-13" style = "width:70px">
<input type="text" name = "time2" id = "timepicker2" value = "00:01" style = "width:40px">
The post method of AJAX form is this:
<script type="text/javascript">
$(document).ready(function(){
// ajaxForm submit
$('#ajaxForm').submit(function() {
$.ajax({
type: 'POST',
url: 'heatQuery.php',
data: $(this).serialize(),
dataType: 'json',
success: function(response)
{
// update the points for heatmap layer
updateHeatMap(response);
},
error: function(errorMsg)
{
alert('Error in Ajax POST');
}
});
return false;
});
});
</script>
And finally, the Qt code that calls the function is this:
void MainWindow::onButtonClicked() // clicking the button in order to POST
{
//the QString a is the same ajax post function as declared above
QString a = "$(document).ready(function(){$('#ajaxForm').submit(function() {$.ajax({type: 'POST',url: 'heatQuery.php',data: $(this).serialize(),dataType: 'json',success: function(response){updateHeatMap(response);},error: function(errorMsg){alert('Error in Ajax POST');}});return false;});});";
this->view->page()->mainFrame()->evaluateJavaScript(a);
}
Any ideas on what is wrong here? Thanks.
I think I have got the problem. XMLHttpRequest loads your local file successfully, but it returns 0 in request.status, thats why error() gets fired from your jQuery code.
I ran following example code in QWebView..
var request = new XMLHttpRequest();
request.open('POST', 'file:///C:/hello.txt', true);
request.onreadystatechange = function(e) {
if(request.readyState == 4)
{
// 'responseText' will not be empty if file present..
alert("response text: " + request.responseText);
alert("status: " + request.status);
}
}
request.send();
Hope this helps..
Related
I am loading a report in an iframe using ReportViewerForMvc. Currently, I have a spinner so that the user will know the report is loading. However, the spinner stops spinning when the iframe is placed on the page...not when the content of the report is finished rendering. I have found people using isLoading with $find but I am pretty sure that is just for asp and I need my to be in .Net
What is the simplest way to have spinner continue to spin until the report is loaded in the iframe?
Currently, I have a shared view for all reports that I am hoping to add some javascript to:
#using ReportViewerForMvc;
<div id="reportViewer">#Html.ReportViewer(Model.ReportViewer as Microsoft.Reporting.WebForms.ReportViewer)</div>
iframe onload does not work to stop spinner here.You would need cookies and client side script to accomplish that.
The server code will set the value in the cookie .Once the report is rendered the value will be read on the client side(cshtml) and spinner can be stopped.
Read this article.Here you can replace the blocker with the spinner.
http://gruffcode.com/2010/10/28/detecting-the-file-download-dialog-in-the-browser/
//This should be called on the event when you are loading the report
//In your case you will route the url to controller or invoke the link
//for the report
$(document).ready(function () {
$('#create_pdf_form').submit(function () {
blockUIForDownload();
});
});
//This is where you will place the spinner
function blockUIForDownload() {
var token = new Date().getTime();
//use the current timestamp as the token value
$('#download_token_value_id').val(token);
$.blockUI();
fileDownloadCheckTimer = window.setInterval(function () {
var cookieValue = $.cookie('fileDownloadToken');
if (cookieValue == token)
finishDownload();
}, 1000);
}
//This will read the token generated from the server side controller or
//aspx.cs or ashx handler
function finishDownload() {
window.clearInterval(fileDownloadCheckTimer);
// $.removeCookie('fileDownloadToken'); //clears this cookie value
//$.cookie('fileDownloadToken', null);
//$.removeCookie("fileDownloadToken");
setCookie("fileDownloadToken", '2')
$.unblockUI();
}
//On the server side set the token , it could be controller or ashx handler
var response = HttpContext.Current.Response;
response.Clear();
response.AppendCookie(new HttpCookie("fileDownloadToken",
downloadTokenValue); //downloadTokenValue will have been provided in the
form submit via the hidden input field
response.Flush();
//Lastly don't forget to add these source js files.
<script src="~/Scripts/jquery-1.5.1.js"></script>
<script src="~/Scripts/jquery.blockUI.js"></script>
<script src="~/Scripts/jquery.cookie.js"></script>
My project is an online mock toefl test. In speaking section I want to upload a recorded file (audio) to server. for recording im not using flash and its only js.
I searched and find something useful but the server is php. and i cant turn the codes to asp.net (web form). please help me out.
In php i used this code in js :
function uploadAudio(mp3Data){
var reader = new FileReader();
reader.onload = function(event){
var fd = new FormData();
var mp3Name = encodeURIComponent('audio_recording_' + new Date().getTime() + '.mp3');
console.log("mp3name = " + mp3Name);
fd.append('fname', mp3Name);
fd.append('data', event.target.result);
$.ajax({
type: 'POST',
url: 'upload.php',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
//console.log(data);
log.innerHTML += "\n" + data;
});
};
reader.readAsDataURL(mp3Data);
}
and this code in upload.php:
<?php
if(!is_dir("recordings")){
$res = mkdir("recordings",0777);
}
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
//echo ($decodedData);
$filename = urldecode($_POST['fname']);
// write the data out to the file
$fp = fopen('recordings/'.$filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>
How can i do this in asp.net, tanks.
You can use jQuery File Uploader on an aspx page. Your client can simply communicate withe an ashx handler at the server side.
https://evolpin.wordpress.com/2011/09/11/asp-net-ajax-file-upload-using-jquery-file-upload-plugin/
One method, and perhaps the most simple solution, is to just use the <asp:FileUpload> control, and hide it from view. Then again, although this works well if you want the user to choose the files they're uploading, it might not be the best solution if you want to implement some kind of HTML5 drag'n'drop solution, etc.
Coincidentally, I spent pretty much all of last week studying how to upload files via javascript to ASP.NET web forms. I developed a drag and drop interface that uses HTML5, and also developed a fail-over method with which the user could choose and upload their files via the <asp:FileUpload> control.
Due to the feature being low-priority, we only fully developed the <asp:FileUpload> control, but I'm happy to share that feature with you here:
HTML
We're going to create an ASP file upload control, and hide certain parts of it. The rest of it, we can add styles to (or do whatever in javascript and CSS) to make it look fancy and customized. The CONTINUE BUTTON
<!-- Allow user to upload the file via the fallbackuploader -->
<div id="fallbackUploader" class="uploader-item-fallbackuploader uploader-item fallbackuploader step-container">
<div class="fallbackuploader-item-uploadcontrols fallbackuploader-item uploadcontrols">
<!-- Uploader Label (note: this serves as the visible "choose files" button too) -->
<label id="uploader_choose_files_button" class="uploadcontrols-item uploadcontrols-item-label button animated" for="mainContent_subContent_fbu_fileuploader">
Choose Files
</label>
<!-- Choose Files button (**NOTE: you'll want to make this control invisible. Try not to set the display to none, as that may cause ASP to omit rendering it -->
<asp:FileUpload ID="fbu_fileuploader" CssClass="uploadcontrols-item-aspfileloader uploadcontrols-item aspfileloader" runat="server" />
<!-- Continue button (NOTE: this button triggers the event that on the server side that will actually handle the file upload -->
<asp:Button ID="fbu_fileuploaderButton" runat="server" Text="Continue" ClientIDMode="Static"
CssClass="uploadcontrols-item-button-upload uploadcontrols-item-button uploadcontrols-item button-upload button continue-button hidden disabled animated" />
<!-- Cancel button -->
<div id="chooseFilesCancelButton" class="uploadcontrols-item-uploadcontrols-item-button
uploadcontrols-item cancel-button hidden disabled button animated">
Go Back
</div>
</div>
</div>
Javascript
// Organizational container for the file uploader controls.
var aspUploadControlsContainer = $('.fallbackuploader-item-uploadcontrols');
// ASP control that chooses and loads the file.
var aspFileLoader_ele = aspUploadControlsContainer.children('.uploadcontrols-item-aspfileloader'),
// element that represents the "choose files" button.
aspUploaderChooseFilesLabel = aspUploadControlsContainer.find('.uploadcontrols-item-label'),
// ASP button that loads the file
aspFileLoaderButton_ele = aspUploadControlsContainer.children('.uploadcontrols-item-button'),
// the element created by the actual ASP "<asp:FileUpload>" control tag.
aspFileUploadControl_ele = aspUploadControlsContainer.find('input.uploadcontrols-item-aspfileloader'),
// the message/alert container
messagebox_ele = $('.uploader-item-messagebox');
// ------------------------------------------------------------
// Bind the 'click' and 'change' events to the file uploader
// ------------------------------------------------------------
function bindAspUploadControlEvents() {
aspFileLoader_ele.on('change', function () { // add the on-change event for the file uploader.
console.log('File changed ...');
if (!aspUploaderChooseFilesLabel.hasClass('upload-disabled')) {
console.log('Choose-files label not disabled ...');
fileSelected(); // perform the file-selected actions.
}
});
};
// ------------------------------------------------------------
// Validate the selected file name and adjust the uploader.
// ------------------------------------------------------------
function fileSelected() {
console.log('File selected...');
var f = aspFileLoader_ele.val() || '';
f = f.replace('C:\\fakepath\\', '') || ''; // get the file name <-- ASP.NET masks the path as C:\\fakepath\\ for security purposes...we'll just take that part out.
var xlRegex = /.(xlsx|xls)$/i; // set the regex to test for accepted file extensions.
if (f.length && !(f.match(xlRegex))) {
// --------------------------- FAILED - show a message -----------------------------------------------------------------
console.log('File-name invalid. Displaying error message ...');
convertCFlabelToButton(); // <-- converting the label to a button and visa versa is probably a round-about way of doing what we wanted, but we were doing some other stuff with it that kind of made it a necessary evil :)
deactivateChooseFilesCancelButton(); // if nothing selected, disable and hide cancel button <-- these functions just do some fluffy stuff that you probably won't need.
deactivateUploaderContinueButton(function () { // if nothing selected, disable and hide continue button <-- these functions just do some fluffy stuff that you probably won't need.
messagebox_ele.text("You've selected a file with an invalid file name. Please make sure the file extension ends with \".xlsx\".").show(); // show the error message.
});
} else if (f.length && f.match(xlRegex)) {
// --------------------------- PASSED -----------------------------------------------------------------
console.log('File-name validated. Hiding messages...');
messagebox_ele.text('').hide(); // reset and hide any messages
console.log('Messages hidden.');
convertCFbuttonToLabel(f, function () { // this converts the button to a label with the given file name as its text
activateUploaderContinueButton(function () { // show and enable the choose-files continue-button
activateChooseFilesCancelButton() // show and enable the choose-files cancel-button
});
});
} else {
// --------------------------- FAILED - hide message -----------------------------------------------------------------
console.log('No file detected. Returning to default state ...');
messagebox_ele.text('').hide(); // hide any messages
// reset the label to defaults
convertCFlabelToButton();
// ------------------------------------------------------------------------------------------------------------------------------
};
}
CODE-BEHIND
Now we just need to add the VB.NET (or C#) to handle the click-event for the continue button.
Protected Sub fbu_fileuploaderButton_Click(sender As Object, e As EventArgs) Handles fbu_fileuploaderButton.Click
If fbu_fileuploader.HasFile Then
Dim FileName As String = Path.GetFileName(Path.GetRandomFileName())
Dim Extension As String = Path.GetExtension(fbu_fileuploader.PostedFile.FileName)
Dim FolderPath As String = ResolveUrl("~/" & ConfigurationManager.AppSettings("FolderPath"))
Dim FilePath As String = Server.MapPath(FolderPath + FileName)
fbu_fileuploader.SaveAs(FilePath)
GetExcelSheets(FilePath, fbu_fileuploader.PostedFile.FileName, FileName, Extension, "Yes")
End If
End Sub
Other Caveats
We did a couple things in the above code that I did not explain, such as the "FolderPath" application setting (we used this in CODE-BEHIND section to determine where the file should be saved). If you've never used application settings in the web.config, it's very simple. For the sake of the above example, we would add the following snippet between our <configuration> tags:
<appSettings>
<add key="FolderPath" value="uploads/"/>
</appSettings>
I can then access the value of this appSetting using
ResolveUrl("~/" & ConfigurationManager.AppSettings("FolderPath"))
or
ResolveUrl(String.Format("~/{0}", ConfigurationManager.AppSettings("FolderPath")))
Also, I stopped with the function to "getExcelSheets" because that's more specific to my application, and probably beyond the scope of this tutorial.
Additional Resources
I have a good habit of methodically saving useful bookmarks. Here is what I have from my "File Uploader" section...
CodeProject.com - File Upload with ASP.NET
Reading files in Javascript using File APIs
Stack Overflow - jQuery Ajax File Upload to ASP.NET web service with
JSON response
Drag and Drop Asynchronous File Upload <-- DEFINITELY THE MOST
USEFUL
I solved my problem. thank you guys. I used web services. in svc file i wrote these codes:
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{
[OperationContract]
public void upload(string data)
{
byte[] base64EncodedBytes = System.Convert.FromBase64String(data);
string strFileDestination = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "somefile.mp3";
File.WriteAllBytes(strFileDestination, base64EncodedBytes);
}
}
in js file i wrote this:
function uploadAudio(mp3Data) {
var reader = new FileReader();
reader.onload = function (event) {
Service.upload(event.target.result, helloWorldCallback, onFail);
function helloWorldCallback(result) {
alert(result);
}
function onFail(e) {
alert(e.get_message);
}
};
reader.readAsDataURL(mp3Data);
}
I want to know is it possible to find out the value of html.textbox inside a view.
if i have #Html.TextBox("textdata") can I read data from that textbox like in my paragraph
my value is: **
So i need this becouse i want that user write a number inside a textbox which i will take as an param to my function like:
#Html.ActionLink("click me", "actionname", "controller", new { param = textbox value}, "")
You need to use javascript for this. Instead of using an action link a better way to achieve this would be to use a form:
#using (Html.BeginForm("actionname", "controller", FormMethod.Get))
{
#Html.TextBox("textdata")
<input type="submit" value="click me" />
}
This way the value entered by the user in the textbox will be automatically sent to the server when he submits the form.
If you still want to do this using javascript (not recommended) here's how you could proceed with jQuery. Subscribe for the click event of the link and fetch the value from the text field and append it to the url:
$(function() {
$('#id_of_your_link').click(function() {
var value = $('#textdata').val();
$(this).attr('href', function() {
return this.href += '?param=' + encodeURIComponent(value);
});
});
});
I have this code for Form Submit..
<input type="submit" runat="server" id="buttonSubmit" value="Add" style="width:100px;" />
My BeginForm is like this..
<% using (Html.BeginForm("Insert", "StudentController", FormMethod.Post, new { #id = "exc-" }))
{%>
I have one textbox in my view I need to check my textbox is empty or not if it is Empty display alert box saying please Enter some value in textbox
other wise go to controler..
Please any body help me out?
thanks
You can do this many ways, but possibly the cleanest is to use Data Annotations on your ViewModel. For example -
public class MyViewModel
{
[Required]
public string MyProperty { get; set; }
}
Now in your View use
<% Html.EnableClientValidation(); %>
just before you start the form. This will cause a JavaScript object to be emitted in the markup sent to the client. The script looks like this example
<script type="text/javascript">
//<![CDATA[
if (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; }
window.mvcClientValidationMetadata.push({"Fields":[{"FieldName":"FirstName","ReplaceValidationMessageContents":true,"ValidationMessageId":"FirstName_validationMessage","ValidationRules":[{"ErrorMessage":"The First Name field is required.","ValidationParameters":{},"ValidationType":"required"}]},{"FieldName":"LastName","ReplaceValidationMessageContents":false,"ValidationMessageId":"LastName_validationMessage","ValidationRules":[{"ErrorMessage":"The Last Name field is required.","ValidationParameters":{},"ValidationType":"required"}]},{"FieldName":"EmailAddress","ReplaceValidationMessageContents":false,"ValidationMessageId":"EmailAddress_validationMessage","ValidationRules":[{"ErrorMessage":"The Email Address field is required.","ValidationParameters":{},"ValidationType":"required"}]},{"FieldName":"ZipCode","ReplaceValidationMessageContents":false,"ValidationMessageId":"ZipCode_validationMessage","ValidationRules":[{"ErrorMessage":"Zip Code must be 5 character long.","ValidationParameters":{"minimumLength":0,"maximumLength":5},"ValidationType":"stringLength"},{"ErrorMessage":"Zip Code must be five digits.","ValidationParameters":{"pattern":"\\d{5}"},"ValidationType":"regularExpression"},{"ErrorMessage":"The Zip Code field is required.","ValidationParameters":{},"ValidationType":"required"}]}],"FormId":"form0","ReplaceValidationSummary":false,"ValidationSummaryId":"valSumId"});
//]]>
</script>
This object contains validation metadata that can be used by a client side validation plugin to hook up validation on the client side. The plugin that comes with ASP.NET MVC 2 is the Microsoft AJAX validator and you will need to include these scripts in the page to use the validation (MicrosoftAjax.js, MicrosoftMVCAjax.js and MicrosoftMvcValidation.js in that order).
Alternatively, if you're more comfortable with jQuery, you can get a script in the MvcFutures source that hooks the validation into the jQuery validate plugin (this isn't a fully fledged script and is missing a few pieces, such as getting client side validation summaries). The script is MicrosoftMvcJQueryValidation.js and you can get it here
The advantage of using Data Annotations is that you get the server side validation too and your client and server side validation will validate for the expected values. Also, the Data Annotations allow you to set Error Messages and names for the field labels from the attributes (error messages and display names* can also come from resource files)
*Because MVC2 was compiled against .NET 3.5 version of Data Annotations, display name cannot be set from resource files. There is a workaround to this - DisplayName attribute from Resources?.
NOW THE EASY WAY
Just set up a submit event handler on the form
var form = document.getElementById('exc-');
var oldSubmit = form.onsubmit || function() {};
form.onsubmit = function() {
var input = document.getElementById('myinput');
if (input.value === '') {
alert('please Enter some value in textbox');
return false;
}
oldSubmit();
}
or with jQuery
$('#exc-').submit(function() {
if ($('#myinput').val() === '') {
alert('please Enter some value in textbox');
return false;
}
});
I have an asp.net aspx page and on that page I have a hidden input field with and id of paneIndex. However, when I load the page, the alert shows index 1 which is correct on the first load, but if I open up pane 3 for example, the alert shows 1 still. Am I doing something wrong?
In a Custom.js file, I have the following code:
$(document).ready(function() {
$("#accordion").accordion({
active: 1,
collapsible: true,
autoHeight: false,
change: function(event, ui) {
var activeIndex = $("#accordion").accordion('option', 'active');
$("#paneIndex").val(activeIndex);
//alert(activeIndex);
}
});
});
In my server side button click, I have the following code:
string activeIndex = Request.Form["paneIndex"];
string script = string.Format(#"<script type=""text/javascript"">var paneIndex =
{0};</script>", activeIndex);
if(!ClientScript.IsStartupScriptRegistered("JSScript"))
ClientScript.RegisterStartupScript(this.GetType(),"JSScript", script);
I have just tested the jquery script locally here and it works fine for me without form submission / postback.
Therefore I assume your issue is related to the form submission / activeIndex variable not being set correctly.
If you use asp.net, do you need to submit the form instead of using postbacks?
I always try to do a postback to the server if possible instead of form submission.
If you use Visual Studio you could also try to set a breakpoint on the server-side code and investigate the Request.Forms collection contains the correct variables after submission.