I started learning Rails 3 months ago.And now I'm trying to add Ajax in my Rails app.
So it have some problems.
In my Index.html.erb file:
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET","demo.txt", true);
xhttp.send();
}
</script>
<button type="button" onclick="loadDoc()">click</button>
<p id="demo"></p>
And I created a file that demo.txt.I try to show content in demo.txt when I click the button.But it shows nothing.
So have any tut for me.
Thanks !
The second parameter of the xhttp.open(...) call should be a URL, not simple a file name. If you are running the Rails application with "rails s" then your url might look something like "http://localhost:3000/demo.txt" if the file demo.txt is in your public folder. Without a URL in that second parameter, I suspect that the request is never finding your rails application.
You might also want to dig into jquery (since you tagged it) to understand how to use that library to issue the request. The interface is much simpler than the low-level js.
Related
I want to be able to receive open/save dialog for a pdf file being returned from controller without using 'Html.Beginform' in ASP.NET MVC. I´m using 'Ajax.Beginform' since I can register events to fire OnBegin and OnComplete (which I think I can´t do when using Html.Beginform, or is it?).
I want to state that the problem is not creating and receiving the file from the server when using 'Html.Beginform' because that works fine, but without the events I want to use. I´m using 'Ajax.Beginform' and the file is being returned from the controller but nothing happens after that client side.
My cshtml
#using (Ajax.BeginForm("CreatePdf", "Print", null, new AjaxOptions() { LoadingElementId = "printLoading", OnSuccess = "printPageComplete"}, new { id = "exportForm" }))
{
//Stuff abbreviated
<input type="button" onclick="onPrint()" />
}
My jQuery
function onPrint()
{
//Stuff abbreviated
$("#exportForm").submit();
}
function printPageComplete(result)
{
//this 'result' variable is obviously holding the file from the controller
//stuff abbreviated
//TODO: I need to open file dialog here
}
My Controller
[HttpPost]
public ActionResult CreatePdf(FormCollection collection)
{
//Stuff abbreviated
return File(thePdf, _mimeTypes[ExportFormat.Pdf], "thePdf.pdf")
}
As you can see I´ve managed to get this far as in the printPageComplete function but I´m not sure where to go from here. Should I continue using the ajax form or should I stick with the html form and try to find other way to fire the events I so sorely need to use?
Perhaps I´m going about this all wrong and your help would be very well appreciated.
You can post a form without using Ajax.BeginForm. It is more work, but gives you more flexibility:
$('#exportForm').submit(function (e){
e.preventDefault();
//Do any validation or anything custom
$.ajax({
//set ajax settings
success: function(){
// Handle the success event
}
});
});
What is the simplest way of getting the nth User in a database (User.find(n) in rails) using a field (where n is the input) and a button, and displaying it on the page using Ajax?
<input id="search_input" type="text">
<button id="search_button">Search</button>
<div id="output> Output displayed here </div>
I read the Ajax tutorial on W3Schools where an XMLHttpRequest object is created, but this seems way too long winded for doing something so simple. Is there an easier way in rails?
This is the Javascript function I would have to call when the button is pressed
function find_nth_user() {
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
}
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("output").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.rb",true);
xmlhttp.send();
}
and then in file ajax_info.rb (which has to be routed correctly) have the rails code.
I tried searching for Ajax on Rails but all I find is stuff to do with forms_for which I don't think are applicable here. I need to function to execute on a button press.
You shouldn't be dealing with the barebones objects like this. jQuery/Prototype/Zepto exist so you don't have to do this stuff.
Watch this railscast on searching with AJAX: http://railscasts.com/episodes/240-search-sort-paginate-with-ajax
So I am trying to implement Uploadifive 1.0 with Asp.NET MVC. Using the debugger mode, I know that the upload action is successfully passed to the Controller and the Server variables are passed as well. However, the HttpPostedFileBase variable fileData is always null. I've looked everywhere on google and couldn't find an answer. I found out that the variable has to be called fileData. That doesn't help though.
Here's part of the view:
<form action="<%: Url.Action("SaveFiles", "File") %>" enctype="multipart/form-data">
<input type="file" name="file_upload" id="file_upload" />
</form>
<script type="text/javascript">
(function ($) {
$(document).ready(function () {
$('#file_upload').uploadifive({
'method': 'post',
'uploadScript': 'SaveFiles',
'formData': {'path' : 'documents'}
});
});
})(jQuery);
</script>
Here's the controller action:
[HttpPost]
public ActionResult SaveFiles(HttpPostedFileBase fileData)
{
string uploadFolder = Request.ServerVariables.Get("HTTP_X_PATH");
if(string.IsNullOrWhiteSpace(uploadFolder))
return Json(JsonMessageManager.GetFailureMessage("No upload folder was selected"));
if (fileData != null && fileData.ContentLength > 0)
{
var fileName = Path.GetFileName(fileData.FileName);
var path = Path.Combine(Server.MapPath("~/Content/" + uploadFolder), fileName);
fileData.SaveAs(path);
return Json(true);
}
return Json(false);
}
Any pointers or help would be greatly appreciated. I feel lost.
I had the exact same problem with Uploadifive so I posted on the Uploadify forums on an existing thread (probably yours). The author has since posted an update to the Uploadifive plugin which I downloaded and now this works fine for me. In fact, it works exactly like Uploadify used to including additional form data being available in "Request.Forms" and it no longer prepends the "X_" to the additional form data. I would recommend you try the new version and see how you go.
See the discussion here: http://www.uploadify.com/forum/#/discussion/8223/no-files-attached-to-request
The key is not naming your variable 'fileData,' but rather making sure that your controller and UploadiFive both think it has the same name. For example:
Javascript:
$(document).ready(function () {
$('#fileUploadDiv').uploadifive({
'uploadScript': '/File/Upload',
'fileObjName' : 'file'
});
});
C# Controller:
[HttpPost]
public PartialViewResult Upload(HttpPostedFileBase file)
{
var name = file.FileName;
var stream = file.InputStream;
// etc...
}
As long as fileObjName has the same name as the parameter in your C# controller, you should be fine. I tested it with various names, and the parameter came in null if the names didn't match, and it worked like a charm when they did match.
If the parameter still doesn't work, you should be able to access the data using this.Request.Files inside of your controller. It looks like that data comes through regardless of parameter names.
I've a bit of an odd issue with FCKEditor in my MVC project.
I've essentially got a View which renders a Partial View containing my FCKEditor (javascript, html and any other bits to make my control reusable throught my app)
I'm calling FCKEditor by doing the following:
<script src="<%= Url.Content("~/Scripts/fckeditor/fckeditor.js") %>" type="text/javascript" ></script>
<script type="text/javascript">
window.onload = function () {
var sBasePath = '<%= Url.Content("~/Scripts/fckeditor/") %>';
var oFCKeditor = new FCKeditor('FckEditor1');
oFCKeditor.BasePath = sBasePath;
oFCKeditor.ReplaceTextarea();
}
</script>
To validate my form, I'm using jQuery.Validate with the following code:
//FORM VALIDATION
$("#NewPageForm").validate({
errorContainer: "#errorblock-div1, #errorblock-div2",
errorLabelContainer: "#errorblock-div2 ul",
wrapper: "li",
rules: {
titleTxt: "required",
FckEditor1: "required"
},
messages: {
titleTxt: "You must enter a page title.",
FckEditor1: "You must enter at least some content."
},
submitHandler: function (form) {
form.submit();
}
});
Locally, when debugging my project, this works absolutely fine and throws up an error to the user when they leave the editor blank.
However, when I publish the application and run it from the server, whenever the editor has content in, the form won't validate, telling me that my FCKEditor control is empty, when it clearly isn't.
If I take away the validation, and submit the form with all the relevant boxes filled, the collection of collection("FckEditor1") is also empty, but again, running this locally works first time, every time.
I've had a search around and what seems to be happening is that my text area <%= Html.TextArea("FckEditor1", New With {.name = "FckEditor1", .class = "required"})%> isn't being populated with the content entered into the FCKEditor, even though this is the box that FCK is linked to.
The issue exists in all the browsers I've tried (IE8 and FF).
Not sure if it's also worth noting that FCK still renders fine too?
I'm not entirely convinced it's an issue with my code as it runs perfect locally. Is there anything I need to configure server-side or in web.config that could be causing it?
Has anyone else come across this or have any ideas as to how to solve the issue?
EDIT
I think I could be partway there with a fix.
I've added the following so far:
$('#publishBtn').button().click(function () {
if (typeof (FCKeditorAPI) == "object") {
FCKeditorAPI.GetInstance("FckEditor1").UpdateLinkedField();
} else {
alert('this is not an object!');
}
if ($("#FckEditor1").val() == "") {
alert("FCKEditor is empty");
} else {
$("#NewPageForm").submit();
}
});
Though, I now get sent to a blank page when the form is submitted, though nothing in my controller seems to be the issue - at least I don't think so as if there was an issue there, it'd do the same on my local machine.
One thing that may be causing your issue if you are validating on the server is that once it's on IIS you cannot post HTML content without the request validation preventing the FCKContent from being passed. Cassini wont check this so it works on your local machine.
try adding this to your the action which is called when you post to validate:
[ValidateInput(false)]
public ActionResult UpdateAction()
{
}
If possible, use CKEditor instead; it integrates with MVC much better.
http://ckeditor.com/
http://ckeditor.com/what-is-ckeditor
I found the source of my problem, and it's to do with the way I'm handling multiple submit buttons in my controller.
I've tweaked it and it's now fixed.
I am looking to standardize the processing of ajax #anchors at the server side, using MVC.
Before a controller action is invoked I want to convert every request with ajax anchors into a request without ajax anchors, so that the controller code does not know there were anchors in the request:
For example:
1) /user/profile#user/photos should be treated as /user/photos
2) /main/index#user/profile/33 should be treated as /user/profile/33
What is the best technique in MVC to accomplish that?
This should necessarily be done on the client side, probably using jquery as everything that follows the # sign is never sent to the server.
I too struggle with same issue and I solved this problem after looking at Visual Studio 11 Developer Preview template code. I added following code in my _layout.cshtml, please note we must load jquery.mobile*.js file after following script tag:
<script type="text/javascript">
$(document).bind("mobileinit", function () {
// As of Beta 2, jQuery Mobile's Ajax navigation does not work in all cases (e.g.,
// when navigating from a mobile to a non-mobile page, or when clicking "back"
// after a form post), hence disabling it. http://jquerymobile.com/demos/1.0a3/#docs/api/globalconfig.html
#{
if (ViewBag.JqueryMobileAjaxEnabled != null && ViewBag.JqueryMobileAjaxEnabled == true)
{
#: $.mobile.ajaxEnabled = true;
}
else
{
#: $.mobile.ajaxEnabled = false;
}
}
});
</script>
**<script src="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.js"></script>**