I have an MVC web project. In a cshtml page of the project, I have an Ajax code as below:-
$.ajax({
type: 'POST',
dataType: 'json',
cache: false,
contentType: false,
processData: false,
url: '#Url.Action("Report", "Report")',
data: data,
success: function (result) {
if (result) {
alert(result.AccessToken); // ----> result.AccessToken is accessible here
$("#load-report").html(#Html.PowerBIReportFor(m => m.Report, new { id = "pbi-report", style = "height:68vh", powerbi_access_token = result.AccessToken })); // ----> result.AccessToken is not accessible here
}
else {
alert("server Error: Not able to load report, please try again");
}
},
error: function () {
alert("Error in uploading the data");
}
});
The response to Ajax call is a JSON serialised object which has two data memebers - Report and AccessToken. In the success function of Ajax, the alert is able to access the result.AccessToken and prints it correctly. However, when I try to access result.AccessToken inside Html.PowerBIReportFor() function, the page shows an error saying "The name result does not exist in the current context".
Can anyone help me with this?
#Html.PowerBIReportFor(m => m.Report, new { id = "pbi-report", style = "height:68vh", powerbi_access_token = Model.AccessToken });
The PowerBIReportFor method takes Model object coming from controller. The Model object should contain Report (Microsoft.PowerBI.Api.V1.Models.Report) and AccessToken (string) so that the method dynamically builds a div element using the info. to generate attributes.
This works peacefully if a view is loaded from a controller. However in my case I just want to load the report into current view. If I load partial view entire Layout is loading again.
I finally solved this problem by building the div element by myself from the content of Result object in ajax success event.
Related
On button click I am trying to send a product name value that the user enters into a textbox to the server to be modified and then back to the page using AJAX. I am getting into the ChangeName method in the controller but not getting into my success function to alert the new name.
The JS:
$("#changeNameButton").click(function () {
var productName = $("#Name").val();
$.ajax({
url: '/Products/ChangeName/',
type: 'POST',
dataType: 'JSON',
data: {name: productName},
success: successFunc
});
});
function successFunc(data) {
alert(data);
}
The controller:
public string ChangeName(string name)
{
string changedName = ChangeNameHelper(name);
return changedName;
}
If anyone can give recommendations on the proper way to make asynchronous calls to a controller in MVC5/6 this would be great.
My main problem is that I am never getting into the successFunc() on response.
Regarding your comment, if you return just a string MVC will convert that to json.
Now, in your updated code you still call a method inside itself. Please call string changedName = ChangeNameForResult(name); or any function with another name.
Install Newtonsoft.Json via nuget package manager and in your controller do this
Public ActionResult ChangeName(string name)
{
// get your object you want to serialize let's say res
return JsonConvert.SerializeObject(res);
}
I needed to set dataType: 'text' rather than JSON since I am returning a simple string.
dataType is the type of data being returned and contentType is the type of data being sent.
In my HTML page , I have the following div:
<div id="notification"></div>
An ajax call add some attribute to that div after receiving successful response.This is what the ajax success does:
$("form").on("submit", function (e) {
e.preventDefault();
$.ajax({
dataType: 'json',
type: "POST",
url: "/dummy/url",
data: {Redacted},
success: function (data) {
$('#notification').attr({'data-status': data['status'], 'data-message': data['message']});
$('#notification').click();
$('#notification').removeAttr("data-status data-message");
}
});
});
The problem is the attributes of #notification does not go away after using removeAttr. I mean it removes the attributes from the page, but remains as cached. Thats why I am getting same data-message on every click though the server returns different data-message.
For example:
In my first ajax call, server returned:
{"status":"success","message":"Invitation sent"}
In this case the #notification triggers and shows me data-message="Invitation Sent". But in my second call server returned:
{"status":"danger","message":"Invitation sending failed"}
But #notification shows data-message="Invitation Sent" again.
Any suggestion for me on this? How can I remove the cached data? Or is there any alternative of what I am doing up there?
Instead of using attribute, use data(). If you had already used data() to read the attribute it is going to be cached as a property of the element.
success: function (data) {
var elementData = {
status: data['status'],
message: data['message']
}
$('#notification').data(elementData);
$('#notification').click();
// not sure why it needs to be removed here
// if it does use `removeData()
}
For the LIFE of me I cannot figure this out.
Setup:
page 1: add.php
page 2: upload.php
page 3: return.php
On page one, the user uploads a spreadhseet from Excel:
<div id="return"></div>
~~~~~
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
jsonResponse = data;
$("#return").load("return.php")
}
});
}));
});
The Excel sheet is sent over to upload.php and a JSON response is returned with the data from the cells.
echo json_encode($out);
This is exactly how it looks in console.log
jsonResponse = [
{"dateReceived":"2015-01-01","designCustomer":"MULTITEST 1","designCustomerLocation":"SUNNYVALE, CA"},
{"dateReceived":"2016-04-05","designCustomer":"MULTITEST 2","designCustomerLocation":"SUNNYVALE, CA"},
{"dateReceived":"1982-04-18","designCustomer":"MULTITEST 3","designCustomerLocation":"SUNNYVALE, CA"}
]
On success, return.php is loaded into the #return div that exists on this first page and it attempts to build a dataTable with the JSON output... :
var table = $('#ltc-table').DataTable( {
"data" : jsonResponse,
"columns" : [
{ data : 'designCustomer' },
{ data : 'designCustomerLocation' },
{ data : 'dateReceived' }
]
});
However, I get the error: Uncaught Error: DataTables warning: table id=ltc-table - Requested unknown parameter 'designCustomer' for row 0.
What I don't understand:
jsonResponse is a variable that contains JSON, and when I use console.log(jsonResponse); on return.php, I get the exact string that I pasted above (so I assume jsonResponse is a variable I can on this page if console.log is reporting it), however, datatables says it can't find the variable, as it's issuing me this error.
If, on return.php, I create new code that flat out defines jsonResponse there instead:
jsonResponse = [
{"dateReceived":"2015-01-01","designCustomer":"MULTITEST 1","designCustomerLocation":"SUNNYVALE, CA"},
{"dateReceived":"2016-04-05","designCustomer":"MULTITEST 2","designCustomerLocation":"SUNNYVALE, CA"},
{"dateReceived":"1982-04-18","designCustomer":"MULTITEST 3","designCustomerLocation":"SUNNYVALE, CA"}
];
it works.
What am I doing wrong? Is this a problem of me passing the data from one page to another page loaded into a div on that first page? This is driving me crazy.....
Your ajax reply will be returning text won't it? I don't see any "json" type specified in the ajax.
Does the data property support JSON. Or does it need javascript objects?
Looking at the docs under "ajax sourced", it implies to use the "ajax" property of the datatable function:
e.g
Ajax Sourced Datatable
I'm struggling to achieve the following, I have a page where a user Logs a Call, the user needs to input various fields and selects from several dropdowns, I then need to post that data (either via JQuery or the controller) to another page, where the user can view the entered data and decide to commit it or not.
I've been going back and fourth for ages now, trying to figure out how to post data from my cshtml to my controller and then redirect to another page with that data persisting.
I've tried to redirect via JQuery and/or the controller and just can't seem to get one or the other working.
Code extracts below:
cshtml:
$.ajax({
url: dir + '/Submit/',
async: true,
type: 'POST',
data: JSON.stringify(callData),
contentType: 'application/json; charset=utf-8',
complete: function () { },
success: function (data) {
}
})
Controller:
[HttpPost]
public ActionResult Submit(SupportCallModel callData)
{
SupportCallModel newData = new SupportCallModel();
newData.SupportCallID = 1;
newData.CallTypeID = callData.CallTypeID;
newData.TroubleShooting = callData.TroubleShooting;
newData.EmailRequest = callData.EmailRequest;
newData.MailDate = callData.MailDate;
newData.FSEOnSite = callData.FSEOnSite;
newData.FSEEmployeeID = callData.FSEEmployeeID;
newData.CallCategory = callData.CallCategory;
newData.CallType = callData.CallType;
newData.CallItem = callData.CallItem;
newData.Summary = callData.Summary;
newData.Description = callData.Description;
newData.ExternalReference = callData.ExternalReference;
newData.CallStatusID = callData.CallStatusID;
newData.CallPriorityID = callData.CallPriorityID;
newData.CallCoEmployeeID = callData.CallCoEmployeeID;
return RedirectToAction("Verify", newData);
}
public ActionResult Verify(SupportCallModel postData)
{
return View(postData);
}
Using ajax is pointless since ajax calls stay on the same page (return RedirectToAction("Verify", newData); is ignored). You can just do a normal submit. Assuming your rendering all the required inputs for SupportCallModel in view, then it will post back. I would recommend you include
[HttpPost]
public ActionResult Submit(SupportCallModel callData)
{
if (!ModelState.IsValid)
{
return View(callData);
}
...
at the top of the method in case the model contains validation errors.
You then create a new instance of SupportCallModel based on the properties of callData which also seems pointless (why not just pass callData instead of newData?)
If SupportCallModel contains only properties which are Value types then you can use return RedirectToAction("Verify", newData); or return RedirectToAction("Verify", callData);. Internally a RouteValueDictionary is created based on the name and value of each property and postData will be correctly bound in the Verify() method. If however any of the properties are complex types or collections then binding will fail for those properties. In that case you need to persist the model so it can be retrieved in the Verify method. My recommendation would be to persist to the database (either a separate table or the existing table that includes a field indicating a pending status), but you could use Session or TempData (in conjuction with .Peek so its not lost if the user hits the refresh button).
I'm not sure exactly what the Verify GET method is rendering, but if it does not include controls for all properties then the Verify submit button will need to post back some ID value that allows you the retrieve the model again from the database or session and finally save it to the database.
It's not working because you're redirecting on the server side when you're making the call via AJAX.
Your redirects should be made on the client side since you're calling the ActionResult on a non-traditional sense (AJAX).
You can remove the return RedirectToAction("Verify", newData); from your action result since it will not do anything. You can probably just return something that specifies whether the call was valid or not.
For your data to persist on another page, you will have to save the data into a temp table in DB so you can show it when you do a redirect.
$.ajax({
url: dir + '/Submit/',
async: true,
type: 'POST',
data: JSON.stringify(callData),
contentType: 'application/json; charset=utf-8',
complete: function () {
},
success: function (data) {
if (data && data.isValid) {
// Grab the tempId that was saved temporarily for verification.
var tempId = data.tempId;
// Perform redirect
window.location = dir + '/Verify/' + tempId;
}
}
});
In your url post...
$.ajax({
url: '#Url.Action("Submit","{ControllerName}")',
async: true,
type: 'POST',
data: JSON.stringify(callData),
contentType: 'application/json; charset=utf-8',
complete: function () { },
success: function (data) {
window.location.href = '#Url.Action("Verify","{ControllerName}", Model);'
}
})
You could model this all without Ajax using standard form posts to MVC controllers reasonably simply.
Assuming your flow looks something like this:
Make the Submit POST return a view containing the data sent in the model. If that data can be verified make the view allow the data on that form to be posted to a Confirm controller action.
In this design the data is entirely transient, the data sent in the HTTP form payload on the initial post is then returned as a form within the returned HTML. This data is then in turn sent to the Verify action.
To do this in your case I think it might be as simple as calling the Submit with the Post verb as a none Ajax call and amending it so the return line looks like return View("Verify", newData);
You will also obviously need to do something else with Verify to do something in that action method.
I'm trying to save the .ajax response, which queries a xml from a REST interface, but I am not successful. Until now the code works, and I get the response, but optimally I would like to parse some of the items into javascript variables or at least save the whole response into one variable. My code looks is the following:
// the actual request
function request(url) {
$.ajax({
type : "GET",
url : "localhost:8080/package/rest/pubs/getpubswithinbbox?south=41.886288445510516&west=12.483901977539062&north=41.893700240146295&east=12.500102519989014",
dataType : "xml",
success : function (data) {
console.log("Successfully queried API!");
console.log(data);
},
error : function (data) {
console.log("An error occurred while processing XML file.");
}
});
};
//Code Ends
Using console.log(data) I also can view the file as a document, but as already mentioned, I would like to save some XML-Elements into variables (or the whole XML document for a later processing).
The XML looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><osm generator="Overpass API" version="0.6">
<note>The data included in this document is from www.openstreetmap.org. The data is made available under ODbL.</note>
<meta osm_base="2014-06-05T12:35:02Z"/>
<node id="1701218666" lat="41.8885564" lon="12.4950752">
<tag k="amenity" v="pub"/>
<tag k="name" v="Camden Town"/>
</node>
</osm>
Do you have any tips of how to proceed with my code snippets? I want to set the request to sync by using async: false
Thanks!
Create div tag in html body like and in jquery ajax part just use $(#result).append(data); inside sucess function
The response object you define within your success/error callbacks can be used as any other JS object. So if you have an existing variable you want to assign it to, do so (though try to avoid cluttering the global namespace) or even attach it to the page using jQuery's .data() function. Example:
// the actual request
function request(url) {
$.ajax({
type : "GET",
url : "localhost:8080/package/rest/pubs/getpubswithinbbox?south=41.886288445510516&west=12.483901977539062&north=41.893700240146295&east=12.500102519989014",
dataType : "xml",
success : function (data) {
console.log("Successfully queried API!");
console.log(data);
$('body').data('APIResult',data);
},
error : function (data) {
console.log("An error occurred while processing XML file.");
}
});
};
Then, elsewhere in your script, whenever you want to reference or use the API response, simply call it or assign it to a local var as such:
var APIData = $('body').data('APIResult');
foo = data
Note that foo will remain undefined until the asynchronous function has been resolved.
You should probably declare foo in the scope you want it in (using var foo outside the call to ajax).