Here i am trying to open the file in new tab by calling ViewFile action of Doctor controller using Ajax Success which is in functionabc(this) on click of anchor tag.
Now the problem is that everything is as required but the url doesnot open in new tab.
Below is my Ajax
<script>
function abc(thisEvent) {
debugger;
var getDoCredId = $(thisEvent).attr('docCredId');
var parameter = { id: getDoCredId };
$.ajax({
url: "/Doctor/ViewFile1",
type: "get",
dataType: "html",
data: parameter,
success: function (data) {
debugger;
if (data = true) {
debugger;
var getdoctorId = $(thisEvent).attr('docCredId');
var url = "/Doctor/ViewFile/" + getdoctorId;
window.open(url, "_blank");
}
else {
debugger;
showNotification("Error", "warning");
}
}
});
}
Below is my anchor tag HTML
<a title="View Attachment" docCredId = "' + getDocCredId + '" onclick="abc(this)"><i class="btn btn-web-tbl btn-warning fa fa-eye "></i></a>
Below is code behind
public bool ViewFile1(int id)
{
var document = _doctorService.GetDoctorCredentialDetails(id);
string AttachPath = ConfigPath.DoctorCredentialsAttachmentPath;
string strFileFullPath = Path.Combine(AttachPath, document.AttachedFile);
string contentType = MimeTypes.GetMimeType(strFileFullPath);
bool checkFileInFolder = System.IO.File.Exists(strFileFullPath);
if (checkFileInFolder == true)
{
return true;
}
else
{
return false;
}
}
public ActionResult ViewFile(int id)
{
var document = _doctorService.GetDoctorCredentialDetails(id);
string AttachPath = ConfigPath.DoctorCredentialsAttachmentPath;
string strFileFullPath = Path.Combine(AttachPath, document.AttachedFile);
string contentType = MimeTypes.GetMimeType(strFileFullPath);
bool checkFileInFolder = System.IO.File.Exists(strFileFullPath);
bool filedata = System.IO.File.ReadAllBytes(strFileFullPath).Any();
byte[] filedata1 = System.IO.File.ReadAllBytes(strFileFullPath);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = document.FileName,
Inline = true
};
Request.HttpContext.Response.Headers.Add("Content-Disposition", cd.ToString());
return File(filedata1, contentType);
}
Since this is too long for a regular comment, I am posting this as an answer, although it isn't directly going solve the problem because I am not able to reproduce it, but might give some insights and let you check the differences with what happens in your code as compared with this simplified example.
Calling window.open() from jQuery ajax success callback works just fine: https://codepen.io/nomaed/pen/dgezRa
I used the same pattern as you did, without your server code but using jsonplaceholder.typicode.com sample API instead.
There are some issues with the code sample that you might want to consider, even though you didn't ask for comments about it and it's not directly related to your issue (probably):
if (data = true) means data will always be true. You probably mean to do a if (data === true) if you know it's a boolean value, or if (data) if you want to accept any truthy value (true, {}, "something", 42, etc). Judging by the Java code and how you define the response format in the jQuery ajax call, it looks like you're expecting the "data" variable result be an HTML and not a boolean. You might want to try and remove the dataType: "html" row and let jQuery set the data format according to what is coming back from the server, and/or send a JSON formatted response, as in a POJO of { result: true } for a successful response. Then make sure that data.result === true to be sure that you got what you expect.
You should probably add arbitrary data to tags DOM elements the data-* attributes and if you're using jQuery, access them using the .data() selector. White adding just random attributs with string values may work, it's considered an abuse of the HTML and DOM, and the data-* attributes are there specifically for adding any data.
In the abc() function you grab the value of the attribute in the beginning (var getDoCredId = $(thisEvent).attr('docCredId');) but in the callback you're trying to get the value once more. You really don't need it since the success() callback is a closure in the scope of the abc() function and it has access to the value already, so doing var getdoctorId = $(thisEvent).attr('docCredId'); in the callback is really not needed.
I'd also suggest naming getDoCredId variable just as docCredId. Having a "get" prefix usually means that it's a getter function or a reference to some getter. Likewise, the "thisEvent" argument of the main function should probably be called "callerElement" or something like that since it's not an event, it's an actual element that you're passing directly from the DOM when calling abc(this) in the onClick event handler of the <a> anchor. This is just to make the code clearer to understand for anyone who's reading it, and for yourself when you're coming back to it several months in the future and trying to figure out what's going on :)
Try adding async: false to your Ajax request
function abc(thisEvent) {
debugger;
var getDoCredId = $(thisEvent).attr('docCredId');
var parameter = { id: getDoCredId };
$.ajax({
async: false, // <<<----------- add this
url: "/Doctor/ViewFile1",
type: "get",
dataType: "html",
data: parameter,
success: function (data) {
debugger;
if (data = true) {
debugger;
var getdoctorId = $(thisEvent).attr('docCredId');
var url = "/Doctor/ViewFile/" + getdoctorId;
window.open(url, "_blank");
}
else {
debugger;
showNotification("Error", "warning");
}
}
});
}
Related
I have a function in my view, that requires calling a list, in order to execute the ajax call within it. The API that I'm using has a parameter List<> among its arguments. That's why I need it.
Is it possible to pass a parameter of type List<> to a Javascript function? If yes, what's the appropriate syntax to use? I googled and didn't find an answer yet.
EDIT : Here's my code
Javascript function:
function DeleteRoom(RoomId, FloorId, userDevicesID) {
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader('verifySession', verifySession());
xhr.setRequestHeader('Authorization', '#HttpContext.Current.Session["BaseAuth"]');
},
url: "/api/Room/RemoveRoom?RoomId=" + RoomId + "&userDevicesId="+ userDevicesID,
type: "DELETE",
dataType: 'json',
success: function (data) {
// removing items from the view
}
});
}
Calling the popup that uses this function:
arr.push(existingdevices[i].attrs.id); //array of IDs, can be empty
PopUpDeleteRoom(id, FloorId, arr);
The API:
[HttpDelete]
public void RemoveRoom(int roomId, [FromUri]List<int> userDevicesId)
{
int currentUserId = SessionData.CurrentUser.UserID;
List<Equipment> equipmentsAssociated = equipmentRepository.FindMany(e => e.RoomID == roomId).ToList();
foreach (Equipment equipment in equipmentsAssociated)
{
equipment.RoomID = null;
equipmentRepository.Update(equipment);
equipmentDeviceRepository.DeleteAllEquipmentDeviceOfZwave(equipment.EquipmentID);
}
foreach (int userDeviceId in userDevicesId)
{
userDeviceRepository.Delete(userDeviceId);
//this generates a NullReferenceException that I will fix later
}
equipmentRepository.Save();
userDeviceRepository.Save();
roomRepository.Delete(roomId);
roomRepository.Save();
}
Please is there a solution or a workaround for this issue?
I assume that in your javascript the List<> is an Array.
If that is the case, you can do all sorts of things with it: http://www.w3schools.com/js/js_arrays.asp
Example (calling this function will display an alert for each element in the array):
var alertAllElements = function (theArray) {
for(var x=0; x<theArray.length; x++)
alert(theArray[x]);
};
i've never used AJAX or JQuery before, but here's my attempt at dynamic loading(pulled from various examples here at stackoverflow)
this is the script i have in my view:(edited to comply with mayabelle's code.) doesn't throw either alert, and the breakpoint on DRequest never trips, but drequest produces results if called directly.
<script type="text/javascript">
$(document).ready(function () {
alert("testing123");
$response = DRequest;
alert("good at response");
$.ajax({
url: "request/drequest"
type: "GET",
dataType: "json",
success: function ($response) {
alert("I am an alert box2!");
// Do something with your response
var $tr = $('<tr>').append(
$('<td>').text($response.NeededByDate),
$('<td>').text($response.RequestedBy),
$('<td>').text($response.Username),
$('<td>').text($response.RequestedPCID),
$('<td>').text($response.RequestType_ID),
$('<td>').text($response.Division_ID),
$('<td>').text($response.ReqTypeIcon)
).appendTo('#requestTable');
console.log($tr.wrap('<p>').html());
}
});
setInterval(function () {
var url = '#';
$('body').load(url);
}, 300000);
});
</script>
is supposed to dynamically append one row at a time (until there are no more rows to add) from the DRequest JsonResult (this is producing results when called directly by way of the addressbar). this should reload the whole page every 5 minutes(300000 seconds).
the JsonResult looks like this
Public Function DRequest() As JsonResult
Dim Reqs = _db.dRequestGetAll
Return Json(Reqs, JsonRequestBehavior.AllowGet)
End Function
where "_db.dRequestGetAll" returns a collection of dRequest rows like so:
Public Function dRequestGetAll() As IEnumerable(Of DRequest)
Return From r In _PITcontext.Requests Where r.CompletedDate Is Nothing Select r
End Function
so. what did i miss?
EDIT: i replaced the javascript from the original post with the most current version since comments can't handle more than 600 characters.
Try like this:
$(document).ready(function () {
$.ajax({
url: url to your controller action,
type: "GET",
dataType: "json",
success: function (response) {
// Do something with your response
}
});
}
Also, in your code above you are calling your variable $response but then in your each loop you are trying to access response (no $ prefix).
I think you should be using $.map() instead of $.each(). It returns an array of your elements. Differences are discussed here.
I have this working code:
jQuery.ajax({
type: 'post',
url: 'http://www.someurl.com/callback.php',
dataType: 'json',
data: jQuery(':input[name^="option"][type=\'checkbox\']:checked, :input[name^="option"][type=\'text\']'),
complete: function (mydata) {
//do something with it
}
});
That successfully posts back any checked checkboxes and all textboxes. But now I want to add some arbitrary data as well to this. But not sure how to format it. Basically i want to simply add my own name=value pair "test=1" so that on the callback I see it like the others. But no matter what I try, I can't see to get the syntax correct in the format it expects. not sure if I should be adding it inside the jQuery() wrap or outside.. I've tried serializing, encodeURIComponent, basic string "&test=1"
Any ideas?
Your best bet is to build the parameters outside of the AJAX call, like so:
var params = jQuery(':input[name^="option"][type=\'checkbox\']:checked, :input[name^="option"][type=\'text\']');
params.test = 1;
params.test2 = 2;
Then in your AJAX call, simply use:
jQuery.ajax({
type: 'post',
url: 'http://www.someurl.com/callback.php',
dataType: 'json',
data: params,
complete: function (mydata) {
//do something with it
}
});
EDIT: Typically when using jQuery to collect input, I tend to use the .each function, like so:
var params = new Object();
$.each('input[name^=option]', function() {
if ((this.type === 'checkbox' && $(this).is(':checked')) || this.type === 'text' && this.value !== '') {
params[this.name] = this.value;
}
});
Then if you wish to add parameters, you'd do so either after this, or right after creating your new object.
I forgot I asked this previously. It was answered correctly so I'm sharing the link:
How can I pass form data AND my own variables via jQuery Ajax call?
Inside my MVC view I have javascript that is executed by a button click. I'm trying to set a string to a random set of characters which I can get to work fine but when I try and set that string to 'randomchars' string inside the javascript I get a NullReferenceException when I try and run the view.
Below is the code snippet, the CreateRString is where the model parameter (RString) is set to the random string.
<script type="text/javascript">
function showAndroidToast(toast) {
var url = '#Url.Action("CreateRString", "Functions")';
$.ajax({ url: url, success: function (response) { window.location.href = response.Url; }, type: 'POST', dataType: 'json' });
var randomchars = '#(Model.RString)';
}
</script>
Is the syntax correct? I'm not too sure why it's getting the NULL.
The javascript is executed after the page been delivered to the client (i.e. web browser). Your razor code here is executed on the server before the page is sent to the client. Therefore, the ajax method will execute after you try to access Model.RString
To fix this you can either call CreateRString on the server, or you can set randomchars by using the response in the success callback.
To explain option 2 a bit further. You could do something like this:
//Action Method that returns data which includes your random chars
public JsonResult CreateRString()
{
var myRandomChars = "ABCDEF";
return new JsonResult() { Data = new { RandomChars = myRandomChars } };
}
//The ajax request will receive json created in the CreateRString method which
//contains the RandomChars
$.ajax({ url: url, success: function (response) {
var randomchars = response.Data.RandomChars;
window.location.href = response.Url;
}, type: 'POST', dataType: 'json' });
More specifically, the razor calls #Url.Action("CreateRString", "Functions") and #(Model.RString) execute first on the server.
Then showAndroidToast executes in the client's browser when you call it.
I have an issue with a method ive created for an object ive created. one of the methods requires a callback to another method. the problem is i cant add the data to the object that called the method. it keeps coming back as undefined. otherwise when i send the data to the console it is correct. how can i get the data back to the method?
var blogObject = new Object();
var following = [...];
//get posts from those blogs
blogObject.getPosts = function () {
var followersBlogArray = new Array();
for (var i = 0; i < this.following.length;i++){
var followersBlog = new Object();
// get construct blog url
var complete_blog_url = ...;
i call the getAvatar function here sending the current user on the following array with it.
followersBlog.avatar = blogObject.getAvatar(this.following[i]);
that part goes smoothly
followersBlogArray.push(followersBlog);
}
this.followersBlogArray = followersBlogArray;
}
here is the function that gets called with the current user in following array
this function calls an ajax function
blogObject.getAvatar = function (data) {
console.log("get avatar");
var url = "..."
this ajax function does its work and has a callback function of showAvatar
$(function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: url,
data: {
jsonp:"blogObject.showAvatar"
}
});
});
}
this function gets called no problem when getAvatar is called. i cant however get it to add the data to the followersBlog object.
blogObject.showAvatar = function (avatar) {
return avatar
}
everything in here works fine but i cant get the showAvatar function to add to my followersBlog object. ive tried
blogObject.showAvatar = function (avatar) {
this.followersBlog.avatar = avatar;
return avatar
}
that didnt work of course. it shows up as undefined. can anyone help?
so somethings like...
$(function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: url,
complete: function () {
this.avatar = data;
}
data: {
jsonp:"blogObject.showAvatar"
}
});
});
}
Welcome to the world of asynchronous programming.
You need to account for the fact that $.ajax() will not return a value immediately, and Javascript engines will not wait for it to complete before moving on to the next line of code.
To fix this, you'll need to refactor your code and provide a callback for your AJAX call, which will call the code that you want to execute upon receiving a response from $.ajax(). This callback should be passed in as the complete argument for $.ajax().
The correct option for setting the JSONP callback is jsonpCallback. The recommendation from the API for .ajax(...) is to set it as a function.
{
// ...
jsonpCallback: function (returnedData) {
blogObject.showAvatar(returnedData);
},
// ...
}