//returning File Response in Controller action Method
return File(MyMemoryStream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "lp.xlsx");
I want to download this file but I have used ajax for passing data from view to Controller so it's returning to Ajax success function .
<script>
$(".pfamlink").click(function()
{
$.ajax({
type: "GET",
url: "/Home/Excel",
data: { "data":$(this).html()},
success: function(response)
{}
});
});
</script>
what I need to give in this function(response) to download returning file from controller?
or any suggestions for passing table data from view to controller without Ajax ?
what I need to give in this function(response) to download returning
file from controller?
The FileContentResult is returned to the Ajax success function, the download was unsuccessful because we need to operate in success. Try to add an action to download, use window.location to redirect to the Download action in controller.
public async Task<IActionResult> DownloadAsync()
{
...
//returning File Response in Controller action Method
return File(MyMemoryStream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "lp.xlsx");
In your ajax success, change your code like below:
success: function (data) {
window.location = '/yourcontrollername/Download';
}
Related
I have a JavaScript/jQuery function used to execute AJAX requests as part of a ASP.NET Core Razor Pages (Visual C#) project. The AJAX request calls an "OnGet" handler method in the PageModel (.cshtml.cs) of whichever page it gets called on.
AJAX request JS/jQuery:
function conditionalDropDown(parameters) {
//code to get handler method inputs in correct format
var pathname = window.location.pathname;
var handler = "?handler=ConditionalDropDown";
var actionpath = pathname + handler;
$.ajax({
dataType: 'json',
url: actionpath,
type: 'GET',
data: {
parameterName: parameterValue
},
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (data) {
//dealing with the data returned by the request
},
error: function () {
alert("AJAX Request Failed, Contact Support");
}
});
}
Handler Method in PageModel:
public JsonResult OnGetConditionalDropDown(parameters)
{
//call a function to get the return string
return new JsonResult(dropdownHTML);
}
I want to change my AJAX request such that it uses an "OnPost" handler method instead. I have tried changing type: 'GET' to type: 'POST' in the AJAX request function, and the name of the handler method from OnGetConditionalDropDown to OnPostConditionalDropDown but the request always fails.
I have #Html.AntiForgeryToken() added to the page (.cshtml) from which the AJAX request is sent, but I'm not sure it's in the right place. Currently, I have it inside the <form> tags of the form from which the AJAX requests are called.
I think I'm missing something in the way the request is set up, but I have no idea what it is. Any help is greatly appreciated.
Answering my own question...
AJAX Request - removed beforeSend function in request, replaced with: headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() }, in request initialisation.
AJAX Request - changed type: 'GET' to type: 'POST'
Handler Method - OnGet --> OnPost
Page .cshtml - removed #Html.AntiForgeryToken(), added method="post" to form from which AJAX request is made
Works perfectly now!
I'm trying to import MySQL data(select query) using spring, mybatis.
In js, call the controller function via ajax, and get DB data from the controller.
ex.
ajax
url: /testmysql
controller
requestmapping: /testmysql
return mav (modelandview)
sysout(mav) is good for the controller.
But Ajax is not found(404) in js.
I was told that an ajax 404 error comes out when there is no return value.
But what should I do now?
You are making ajax call without root context url of your application.
$.ajax({
url: '/context/testmysql',
type:'GET',
success: function(data) {
console.log(data);
}
});
I need to send data from javascript to my action that return RedirectToAction and some data.
My Js:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "GetAssetFilterID",
data: JSON.stringify({ 'VidLink' : clipData.src, 'InitialTime': clipData.markIn, 'EndTime': clipData.markOut }),
dataType: "json",
/*async: false,*/
});
My Action:
[HttpPost]
public ActionResult GetAssetFilterID(string VidLink, string InitialTime, string EndTime)
{
//some code
return RedirectToAction("Share", new { vid = VidLink, fil = filterName });
}
Notes
I had, on js, the url controller/action and the link that it
generated was controller/controller/action.
I don' get any error on console, nothing happens.
I don't need to use Ajax, I just want to send data from my Js to my
ActionResult. Ajax was the sample that I found.
Thanks in advance
You cannot do that. All you can do is return a url in the ajax result and use JS to redirect. Return the url in json or similar and in the ajax success or complete callbacks do your redirect.
Because the browser never posted its not expecting a response that would allow/cause a redirect.
Also duplicate of asp.net mvc4 ajax login: RedirectToAction not working
I am using codeigniter for my project and I am stuck trying to figure this out.
I have some javascript that needs to perform an AJAX call to fetch some results based on a dropdown value that was selected.
function fetchLines(){
$.ajax({
url: baseURL + "resources/ajax.php?node=fetchLines",
type: 'GET',
cache: false,
data: {
lineType: 'business'
},
error: function(err) {
alert(err.statusText);
},
success: function(data) {
console.log(data);
}
});
}
In this AJAX file, I am trying to include my controller and then access the function within it.
<?php
define('BASEPATH', "AJAX");
require_once('../application/controllers/Project.php');
switch($_REQUEST['node']){
case 'fetchLines':
$objLines = new Project();
$objLines->fetchLines($_REQUEST['lineType']);
break;
}
?>
My CI Controller then has a private function in it which I am trying to call to get the data I need:
private function fetchLines($lineType){
$lines = $this->project_model->fetchLines($lineType);
return $lines;
}
My goal here is to have an AJAX file or controller (if needed) be used for all my AJAX calls. It needs to be able to access a controller and return data.
With the current code above, I am getting the error: Class 'CI_Controller' not found in <b>C:\xampp\htdocs\blueprint\application\controllers
\Project.php
Is there a better way to handle situations like this? I'm not an expert with OOP but some reading suggested something along these lines.
why you are not sending this request to the controller method instead ?
function fetchLines(){
$.ajax({
url: baseURL + "controller-name/method-name",
type: 'GET',
cache: false,
data: {lineType: 'business'},
error: function(err) {
alert(err.statusText);
},
success: function(data) {
console.log(data);
}
});
}
NOTE and in controller you can access these values as
function method-name(){
echo $this->input->get('lineType');
}
Lets say my ajax file is in the controllers folder
And I want to re-use my controllers, i would do it like this :
$this->load->library('../controllers/your_controller');
$this->your_controller->_some_method($data);
Load the controller as library and used it like a library.
Hope this helps.
You should put the code that listens to AJAX call in a controller function only. The way you are trying to do is not a good practice at all.
If you want a method to be executed only if the request was an XHR i.e.AJAX request then use
if($this->input->is_ajax_request()){
//your code
}else{
redirect(base_url())
}
Hi all is it possible to call a an ajax call without using success?
ie from:
$.ajax({
type: "POST",
url: "/project/test/auto",
data: data,
success: function(msg){
//window.location.replace(msg);
}
});
to something simply like:
$.ajax({
type: "POST",
url: "/project/test/auto",
data: data,
});
To give reasoning - I have written some php to insert items into a database and then redirect to another page, I don't want to have to re-write the same code again to insert into the DB and then redirect in JS.
jQuery.post() documentation
$.post( "/project/test/auto", data );
I don't think that you can redirect using PHP within ajax call.
It would be best to create a function out of DB insert and then with ajax call a page that executes that function and returns success:true in json for example. After that, redirect in success part of your ajax call. You can later call the same DB insert function from within your PHP code.