I want to perform an action write to file in controllers/static_pages_controller.rb:
def fileopen
my_file = File.new("public/CHNAME1.txt","w")
my_file.write "\tfasf"
my_file.close
end
(it work well when i define it in helper and call it in view.)
in myview.html.erb, i want some thing like How can I do that? I tried in application.js
function readfile() {
alert('readfile work')
$.ajax({
alert('ajax work')
url: "/fileopen",
type: "POST",
##don't know what to to to call fileopen
}
});
}
routes.rb
match '/fileopen', to:'static_pages#fileopen', via: 'get'
and it's seem nothing happen. Only the first alert work
You have syntax error, try this:
function readfile() {
alert('readfile work');
$.ajax({
url: "/fileopen",
type: "POST",
success: function(){
alert('ajax work');
}
});
}
I don't know ruby but route is on "GET" request and you are making "POST" request:
match '/fileopen', to:'static_pages#fileopen', via: 'get' // should be via: 'post'?
You can not use alert within ajax, If you want to use it then use in success and error methods
Related
I know there are already lots of posts out there covering this, but I'm not that good at Javascript at baseline, and most of the ones that should probably make sense use an older syntax that is confusing me.
Here is my function that I want to work:
function getUpdateForm() {
$.ajax({
url: 'test_response.html',
type: 'GET',
dataType: 'json',
success: function(data) {
$("#Form_div").html(data);
},
});
};
This is my response file:
<html>
<head>
<title>Test Response</title>
</head>
<body>
<h1>Test Page</h1>
</body>
</html>
And this is my QUnit test:
QUnit.test('getUpdateForm ajax request', function(assert) {
$.ajax = function(request) {
assert.equal(
request.url,
'test_response.html',
'request url is correct'
);
assert.equal(request.type, 'GET',
'request type is correct'
);
assert.equal(request.dataType, 'json',
'request dataType is correct'
);
};
getUpdateForm();
setTimeout(function() {
assert.equal($("#Form_div").html(), '',// not exactly sure what to put
'Received correct html in response'
);
assert.async();
}, 1000);
});
Currently it doesn't even attempt to run the assert.equal in the setTimeout function.
Please give as many details details as possible, and I will probably have many questions. First one being, how does test even get the correct function from $.ajax = function(request)?
I see what you're trying to do... but there is a tool to mock out Ajax requests for just this purpose! (Which I am the maintainer of, but still...)
Basically, in your test (or a beforeEach hook) you create a mock based on your real Ajax call, then do your code test.
First, I would start by adding a callback in your source code function so we know when the ajax call is done in the test:
function getUpdateForm(doneFunction) {
$.ajax({
url: 'test_response.html',
type: 'GET',
dataType: 'json',
success: function(data) {
$("#Form_div").html(data);
},
complete: doneFunction // <-- this is new!
});
};
Now set up your test with a mock, and execute assertions...
QUnit.test('getUpdateForm ajax request', function(assert) {
let done = assert.async(); // set up an async test
$.mockjax({
url: "test_response.html",
responseText: "<h1>Test Page</h1>"
});
getUpdateForm(function() { // this is our callback function
// now do your assertions on the content in the form div...
assert.equal($("#Form_div h1").text(), 'Test Page', 'Received correct title in html response');
done(); // then tell QUnit you are done testing.
});
});
Don't forget to include the Mockjax JS file in addition to the QUnit JS file!
When an POST is made to the controller, the controller responds with exactly what I want the browser to render. But the browser does not render the response. I've verified the response is good in Fiddler.
The code below shows what I think is relavent code. The controller action method that returns the response, part of the template that has the mvc helper code, javascript/jquery code that fires the ajax call with the form inputs.
I want to use the FormCollection. Why doesn't the browser render the response and what can I do to fix it?
BoMController
public ActionResult GetBillOfMaterialsView(FormCollection frmColl){
// snipped out model interaction
return PartialView("~/Views/Project/Index.cshtml", project);
}
Index.cshtml
#using (Html.BeginForm("GetBillOfMaterialsView", "BoM", FormMethod.Post, new {id = "frmGetBom"})) {
// selProj input select code removed for brevity
}
function submitGetBoM() {
var frmGetBom = $('#frmGetBom');
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize()
});
}
$(document).ready(function() {
$('#selProj').selectmenu( {
select: function(){submitGetBoM()}
}).addClass("overflow");
});
Invoking $.ajax alone doesn't append the response from the server to the document, you have to use the success callback to manually fetch the response and append it.
For example:
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize(),
success: function(response) {
$('#someContainerId').html(response);
}
});
Alternatively, use load() that is a shorthand to the above:
$('#someContainerId').load(frmGetBom.attr('action'), frmGetBom.serializeArray());
See Documentation
Your client code doesn't do anything with the returned values from the server:
function submitGetBoM() {
var frmGetBom = $('#frmGetBom');
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize(),
success: function() { alert('ok'); }
});
}
This would popup an alert on success.
below is an ajax but it wont work, what seems be the problem? assume that I have requestparser.php and inside it i have "echo "yes ajax work!";".
$(document).ready(function(){
// start ajax form submission
$.ajax({
url: "requestparser.php",
type:"POST",
data: ({ "pulldata" : "oy" }),
success:function(e){
if(($.trim(e)=="success")){
alert("yes");
}else{
alert("no");
}
},error:function(){
alert("error");
}
});
});
as above ajax function ,the process should be, on load it will send first a post request to requestparser.php with a post name of "pulldata" and post content of "oy" and when the requestparser receive that post request from the ajax so then respond with "yes ajax work!" and since the respond from requestparser.php is not equal to success then it should display "no".
any help would be greatly appreciated
I tried to debug your code and it worked fine for me. So can you try this code and say what error it shows ?
$(document).ready(function () {
$.ajax({
url: "test.php",
type: "POST",
data: ({
"pulldata": "oy"
}),
success: function (e) {
console.log(e);
},
error: function (e) {
console.error(e);
}
});
});
test.php
<?php
var_dump($_POST);
One more thing, just for confirmation, you have included jQuery in your page before using ajax right ?
I'm getting error 404 while making ajax calls to my MVC controller
Here is the scenario:
I have 2 controllers:(PartnerControler,GettingSartedController)
While on the getting started page:http://mysite/GettingStarted/ I make the following ajax call:
$scope.SubmitRegistration = function() {
return $http({
url: '/partner/register',
method: 'POST',
data: $scope.UserAccount,
headers: {
'Content-Type': 'application/json'
I get a 404 on the call to the controller.
when I add the exact register method to the gettingstarted controller and change the ajax URL to the following it works:
url: '/gettingstarted/register',
When on web a page that uses a specific controller can you make calls to another controller?
How can this be achieved modifying the above script?
If you have separate js files, you can use workaround like below
<input type="hidden" id="registerurl" data-register-url="#Url.Action("register", "partner")"/>
and use this element's attribute as url to be used in your http call
var urlRegisterPartner = $('#registerurl').data('register-url');
I found another very good answer here in
https://stackoverflow.com/a/57274117/14181068 for
Ajax call to a different controller
This is the summary i got from the answer.
url on ajax
result
your/path
http://example.com/Home/your/path
~/your/path
http://example.com/Home/~/your/path or http://example.com/your/path
.../your/path
http://example.com/Home/.../your/path
../your/path
go up one directory level, resulting in http://example.com/your/path.
/your/path
http://example.com/your/path
sample
$.ajax({
type: 'Get',
url: "YourUrlHere",
data: { id: $('#inputId').val() },
})
.done(function (response) {
if (response.length > 0) {
}
})
.fail(function (error) {
alert(error.StatusText);
});
I am aware this question has been answered before but I am somehow unable to hit an action within my controller.
Here is the Action
public JsonResult GetUpdate()
{
//get a list of valid elements
var result = getContent();
return Json(result, JsonRequestBehavior.AllowGet);
}
In my script:
$.ajax({
type: 'GET',
url: '#Url.Action("GetUpdate")',
dataType: 'json',
success: function (constraints) {
alert("Application updated");
},
error: function (ex) {
alert('Failed to retrieve update.' + ex);
}
});
Using fiddler I can hit GetUpdate but from the browser the Ajax call fails. Am I correctly accessing the URL?
Update:
The following is the error message:
"NetworkError: 404 Not Found - protocol://localhost:port/Controller/#Url.Action(%22GetUpdate%22)"
The following works through Fiddle:
protocol://localhost:port/Controller/GetUpdate
Razor code (C# and all other server-side script) is only executed from .cshtml files, therefore C# and Razor can't be used in .js files.
'#Url.Action("GetUpdate")' doesn't generate a URL, it's just a string, therefore you are trying to request protocol://domain:port/Controller#Url.Action("GetUpdate") which doesn't exist.
Here's what you can do:
In the .cshtml file you can store the generated URL in a JavaScript variable and pass it to the external JS file.
You can move your external JavaScript to the .cshtml file so you can use Razor.
use a relative string path like /Controller/GetUpdate
I would recommend the first one.
You can try this out,where _ApplicationPath is protocol://localhost:port/
$.ajax({
type: 'GET',
url: _ApplicationPath + "/ControllerName/GetUpdate",
dataType: 'json',
success: function (constraints) {
alert("Application updated");
},
error: function (ex) {
alert('Failed to retrieve update.' + ex);
}
});