I am sending a json in my server using vanilla JS and it returns a bad request, it seems the server only wants a key value pair like 'page=pageData&action=act', when i do this it works, but i would want to send data that way. Is there a way to make it possible?
When i try to make it in jquery it works fine.
$('.more-headlines').on('click', function() {
var pageData = $(this).data('page');
var pageURL = $(this).data('url');
var act = 'load_more';
var jsondata = {
page : pageData,
action : act
}
var xhr = new XMLHttpRequest();
xhr.open('POST', pageURL, true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onload = function() {
if (xhr.status >=200 && xhr.status < 400) {
var data = JSON.parse(xhr.responseText);
console.log(data);
} else {
console.log('sad');
}
};
xhr.send(JSON.stringify(jsondata));
});
This is my code in jquery
$('.more-headlines').on('click', function () {
var that = $(this);
pageData = $(this).data('page');
newPage = pageData+1;
pageURL = $(this).data('url');
act = 'load_more';
that.addClass('icon-spin');
that.find('span').html('loading headline');
jsondata = {
page : pageData,
action : act
}
$.ajax ({
type: 'POST',
url: pageURL,
data: jsondata,
success: function(response) {
setTimeout( function () {
that.data('page', newPage);
$('#featureOnDemand ul').append(response);
that.removeClass('icon-spin');
that.find('span').html('See more headlines');
}, 500);
}
});
});
I looked at the network tab in chrome and i saw that the send request becomes a key value pair like 'page=pageData&action=act'.
I am stuck in this part because i want to make a vanilla js ajax request in my project. Any idea would be much appreaciated. Many thanks!
You want to serialize your object data. Here's a helper function you can pass your object into:
var serializeObject = function (obj) {
var serialized = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
serialized.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
}
return serialized.join('&');
};
So, I have a button that triggers a javascript function, that calls an AJAX request, that calls an actionresult that should update my database.
Javascript Call
function changeDepartment() {
// Initiate and value variables,
var id = $('#requestId').val();
var user = $('#contactUser').val();
// Bind variables to data object
var data = { id: id }
// Ajax call with data.
$.ajax({
url: '#Url.Action("changeDepartmentActionResult", "ManageRequestResearch")',
type: "POST",
dataType: 'json',
data: data,
success: function (data, textStatus, XmlHttpRequest) {
var name = data.name;
window.location.href = '#Url.Action("Index", "ManageRequestResearch")';
$('#btn-input').val('');
},
error: function (jqXHR, textStatus, errorThrown) {
alert("responseText: " + jqXHR.responseText);
}
});
alert(data);
And then, I have the action result:
[HttpPost]
public ActionResult changeDepartmentActionResult(string id)
{
var moadEntities = new MOADEntities();
moadEntities.Configuration.AutoDetectChangesEnabled = false;
var researchBusiness = new ResearchRequestBusiness(moadEntities);
var request = researchBusiness.FetchRequestById(Convert.ToInt32(id));
var directoryObject = GetActiveDirectoryObject(request.Requestor);
var requstorDisplayName = directoryObject != null ? directoryObject.DisplayName : request.RequestorFullName;
var researchRequestFileBusiness = new ResearchRequestFilesBusiness(moadEntities);
var requestFiles = researchRequestFileBusiness.FetchFilesByRequestId(Convert.ToInt32(id));
var viewModel = new ManageSelectedRequestResearchViewModel()
{
RequestDetails = request,
RequestActivity = request.tbl_ResearchRequestActivity.Select(d => d).ToList(),
Files = requestFiles
};
moadEntities.Configuration.AutoDetectChangesEnabled = false;
if (request.GovernmentEnrollment == true)
{
request.GovernmentEnrollment = false;
request.ManagedCare = true;
moadEntities.SaveChanges();
}
else
{
request.ManagedCare = false;
request.GovernmentEnrollment = true;
moadEntities.SaveChanges();
}
return Json("Status changed successfully", JsonRequestBehavior.AllowGet);
}
From what I have observed, it returns the right record, it makes the changes properly, and it hits the Context.SaveChanges();
when debugging -- i can see before the save changes is made that the values have indeed changed, however--inside the database, no changes are saved.
In addition, i have checked to see that the connection strings are valid.
Any idea what may be causing this?
Thanks ahead of time!
It seems that you are modifying an entity while auto detecting changes are disabled.
If it is intentional then you should inform the context that the entity has been changed.
I assume that MOADEntities is derived from DbContext. So instead of this:
if (request.GovernmentEnrollment == true)
{
request.GovernmentEnrollment = false;
request.ManagedCare = true;
moadEntities.SaveChanges();
}
else
{
request.ManagedCare = false;
request.GovernmentEnrollment = true;
moadEntities.SaveChanges();
}
I would try this:
// Simplify the if..else block
request.ManagedCare = request.GovernmentEnrollment;
request.GovernmentEnrollment = !request.GovernmentEnrollment;
// Notifying the context that the 'request' entity has been modified.
// EntityState enum is under System.Data.Entity namespace
moadEntities.Entry(request).State = EntityState.Modified;
// Now we can save the changes.
moadEntities.SaveChanges();
I have the following Jquery code, I'm trying to display information in $('.cbs-List').HTML(divHTML); based on the region value. But in the success function, I can't read the value for the region, it states that
'data is undefined'
What is the correct form of passing parameters or values to the success function in this case?
$(document).ready(function() {
getSearchResultsREST('LA');
});
function getSearchResultsREST(region) {
var querySA = 'ClientSiteType:ClientPortal* contentclass:STS_Site Region=LA';
var queryDR = 'ClientSiteType:ClientPortal* contentclass:STS_Site Region=EM';
if(region == 'LA') {
var searchURL = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?queryText='" + querySA + "'";
} else {
var searchURL = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?queryText='" + queryDR + "'";
}
$.ajax({
url: searchURL,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
contentType: "application/json; odata=verbose",
success: SearchResultsOnSuccess(data, region),
error: function(error) {
$('#related-content-results').html(JSON.stringify(error));
}
});
}
function SearchResultsOnSuccess(data, region) {
var results;
var divHTML = '';
if (data.d) {
results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
if(results.length == 0) {
$('#related-content-results').html('There is No data for the requested query on ' + _spPageContextInfo.webAbsoluteUrl);
} else {
for (i=0; i<results.length; i++) {
var item = results[i];
var itemCell = item.Cells;
var itemResults = itemCell.results;
// Get values for item result
var _title = getValueByKey("Title", itemResults);
var _path = getValueByKey("Path", itemResults);
divHTML += '<li><a href=' + _path + '>' + _title + '</li>';
}
// Display information based on region.
$('.cbs-List').html(divHTML);
}
}
}
You have 2 problems, and they're both easy to fix.
There's no need to pass region into SearchResultsOnSuccess at all. you can already use it in there because it's defined at a higher scope.
In the object you're passing to $.ajax, you're not setting SearchResultsOnSuccess as a callback, you're calling it.
Change the lines:
success: SearchResultsOnSuccess(data, region) => success: SearchResultsOnSuccess
function SearchResultsOnSuccess(data, region) { => function SearchResultsOnSuccess(data) {
and it should work fine.
Edit:
Here's a basic example of how you need to set this up
function search(region) {
$.ajax({
url: 'example.com',
method: 'GET',
success: successCallback,
});
function successCallback(data) {
console.log(data, region);
}
}
search('LA');
You have to urlencode the value if it contains = or & or whitespace, or non-ASCII characters.
var querySA = encodeURIComponent('ClientSiteType:ClientPortal* contentclass:STS_Site Region=LA');
var queryDR = encodeURIComponent('ClientSiteType:ClientPortal* contentclass:STS_Site Region=EM');
if(region == 'LA') {
var searchURL = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?queryText=" + querySA;
} else {
var searchURL = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?queryText=" + queryDR;
}
And normally you don't have to put your values between apostrophes.
I updated the answer, I hope you will understand me better.
Your problem is NOT the parameter passing IMHO but your server response.
You should either:
turn on the developer tools and check the XHR requests on the network tab, look for the /_api/search/query... requests and examine the response
double check the server side logs/study your search service API documentation how to assemble a proper call
use your favourite REST client and play around your service: send there queries and check the responses and check that it matches with your expectation
last but not least, you can replace your ajax caller with this quick-and-great one:
$.ajax({
url: searchURL,
success: function (response) {
$('#post').html(response.responseText);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$('#post').html(msg);
},
});
(of course you should have a <div id="post"><div> somewhere in your page)
Your success function IMHO would get your region if gets called, but it does not, and I hope using one or more of these techniques will help you to see clear.
If you are really sure that you get what you want, you can go furher with passing your second argument, as described here
enter image description hereI am trying to implement Google sign in into my web forms page because we use G suite for business. basically I am using javascript to get the token then using ajax to post to the google api then I am looking at the HD claim to make sure they are apart of our domain and thne posting to the code behind the email and doing a lookup to get a user ID then setting the form cookie and trying to redirect to our defalut page. So we have a mvc app that I done this exact thing with and it works perfectly I just routed them to the controller. For some reason it just seems like I am not getting anything from my code behind code.
here is my javascript.
<script>
function onSignIn(googleUser) {
debugger;
const profile = googleUser.getBasicProfile();
let boolRedirectUrl = false;
const id_token = googleUser.getAuthResponse().id_token;
const pathname = window.location.pathname;
const url = window.location.href;
let redirectPath = "";
if (window.location.href.indexOf("ReturnUrl") > -1) {
boolRedirectUrl = true;
redirectPath = readQueryString("ReturnUrl");
}
const googleUrl = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" + id_token;
$.ajax({
url: googleUrl,
dataType: 'json',
data: '{}',
contentType: 'application/json',
success: (data, status, xhr) => {
const domain = data.hd;
const email = data.email;
if (domain === "kimbelmechanical.com") {
$.ajax({
url: "Login.aspx/GoogleLogin",
type: "POST",
data: { 'email': email },
success: (data, status, xhr) => {
//window.location.href = "Default.aspx"
},
error: (xhr, status, error) => {
console.log("I stopeed on the call to controller " + status);
}
});
}
},
error: (xhr, status, error) => {
console.log(status);
}
});
};
function readQueryString(key) {
key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&");
var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}
</script>
this is my c# code behind.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GoogleLogin(string email)
{
string userID = "";
using (var context = new KPDataContext(KP.Common.KPConnectionString))
{
var user = context.Employees.Where(p => p.Email == email);
foreach (var e in user)
{
userID = e.Username;
}
}
if (userID != "")
{
FormsAuthentication.SetAuthCookie(userID, false);
Response.Redirect("~/Default.aspx", true);
}
}
if I redirect from the success to my default page it loads it default.aspx found but for some reason it does login.aspx?ReturnUrl=?default.aspx but stays on the login page so I am in a endless loop of loading the login page over and over.
Is it MVC? If so you can use RouteData along with creating a new instance of a controller. That controller can then execute a new web request with the new path like so:
var routeData = new RouteData();
routeData.Values.Add("message", errorModel.message);
routeData.Values.Add("action", "Index");
routeData.Values.Add("controller", "ErrorPage");
IController ctrl = new ErrorController();
ctrl.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
Response.End();
I have a download function where the idea is that when the user clicks a button, it does an ajax call to a function that will create a csv file containing all of the information the user was viewing, and will return the file as a download. I have the server function creating a csv file, but I'm not sure how to make it download. This is my server-side code:
public ActionResult Download(Guid customerOrderId)
{
var order = this.UnitOfWork.GetRepository<CustomerOrder>().Get(customerOrderId);
var csv = new StringBuilder();
csv.Append("Customer,Bill To Name,Ship To Name,Patient,Order#,Order Date," +
"Line,Item#,Item Description,Qty,UOM,Price,Ext Price,Carrier," +
"Notes,Purchase Order");
var customer = order.CustomerNumber;
var billToName = order.BTDisplayName;
var shipToName = order.ShipTo.CustomerName;
var orderNum = order.OrderNumber;
var orderDate = order.OrderDate;
var carrier = order.ShippingDisplay;
var notes = order.Notes;
var subtotal = order.OrderSubTotalDisplay;
var total = order.OrderGrandTotalDisplay;
var shipping = order.ShippingAndHandling;
var tax = order.TotalSalesTaxDisplay;
var patient = "";
var purchaseOrder = order.CustomerPO;
foreach (var cartLine in order.OrderLines)
{
var line = cartLine.Line;
var itemNum = cartLine.Product.ProductCode;
var itemDesc = cartLine.Description;
var qty = cartLine.QtyOrdered;
var uom = cartLine.UnitOfMeasure;
var price = cartLine.ActualPriceDisplay;
var ext = cartLine.ExtendedActualPriceDisplay;
//Customer,Bill To Name,Ship To Name,Patient,Order#,Order Date," +
//"Line,Item#,Item Description,Qty,UOM,Price,Ext Price,Carrier," +
//"Notes,Purchase Order
var newLine = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}",
customer, billToName, shipToName, patient, orderNum, orderDate, line, itemNum, itemDesc,
qty, uom, price, ext, carrier, notes, purchaseOrder);
csv.AppendLine(newLine);
}
csv.AppendLine();
csv.AppendLine("Subtotal,Shipping & Handling,Tax,Total");
csv.AppendLine(string.Format("{0},{1},{2},{3}", subtotal, shipping, tax, total));
var filename = "MSD-Order-" + orderNum + ".csv";
var bytes = Encoding.UTF8.GetBytes(csv.ToString());
return this.File(bytes, "text/csv");
}
And here is the ajax method:
function download(customerOrderId) {
$.ajax({
url: insite.core.actionPrefix + '/Checkout/Download/?customerOrderId=' + customerOrderId,
type: 'Post',
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
success: function (data) {
alert("downloaded");
},
error: function (ex) {
console.log(ex);
}
});
}
In the success of the ajax call, I checked the value of "data" and it has the information, but I'm not sure how to make it download. What do I do once I receive the data?
Can't you just download it via a href like this?
public FileContentResult Download(Guid customerOrderId)
{
// your code
var response = new FileContentResult(bytes, "text/csv");
response.FileDownloadName = filename;
return response;
}
The link:
Download
You can store the file on server and send the URL with response. Then on ajax success function window.location=data.URL
Venerik has a valid answer as well, but keeping in line with your current implementation, I'd suggest the following.
You can return the string of the URL after saving the file to your server. Then do the window location redirection upon your success. I removed the variable assignments since nothing is being done with them other than sending to a method.
Here we write the file and return the string. You'll need to adjust the return to match your site information, etc.
public ActionResult Download(Guid customerOrderId)
{
var order = this.UnitOfWork.GetRepository<CustomerOrder>().Get(customerOrderId);
var csv = new StringBuilder();
csv.AppendLine("Customer,Bill To Name,Ship To Name,Patient,Order#,Order Date," +
"Line,Item#,Item Description,Qty,UOM,Price,Ext Price,Carrier," +
"Notes,Purchase Order");
foreach (var cartLine in order.OrderLines)
{
//Customer,Bill To Name,Ship To Name,Patient,Order#,Order Date," +
//"Line,Item#,Item Description,Qty,UOM,Price,Ext Price,Carrier," +
//"Notes,Purchase Order
csv.AppendLine(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}",
order.CustomerNumber, order.BTDisplayName, order.ShipTo.CustomerName, "", order.OrderNumber, order.OrderDate, cartLine.Line, cartLine.Product.ProductCode, cartLine.Description,
cartLine.QtyOrdered, cartLine.UnitOfMeasure, cartLine.ActualPriceDisplay, cartLine.ExtendedActualPriceDisplay, order.ShippingDisplay, order.Notes, order.CustomerPO));
}
csv.AppendLine();
csv.AppendLine("Subtotal,Shipping & Handling,Tax,Total");
csv.AppendLine(string.Format("{0},{1},{2},{3}", order.OrderSubTotalDisplay, order.ShippingAndHandling, order.TotalSalesTaxDisplay, order.OrderGrandTotalDisplay));
var filename = "MSD-Order-" + orderNum + ".csv";
using (StreamWriter sw = File.CreateText(Server.MapPath("~/files/" + filename))
{
sw.Write(csv.ToString());
}
// adjust your url accordingly to match the directory to which you saved
// '/files/' corresponds to where you did the File.CreateText
// returning Content in an ActionResult defaults to text
return Content("http://foo.com/files/" + filename);
}
And in your AJAX method update your success function to redirect the page which will prompt the download:
function download(customerOrderId) {
$.ajax({
url: insite.core.actionPrefix + '/Checkout/Download/?customerOrderId=' + customerOrderId,
type: 'Post',
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
success: function (data) {
window.location.href = data;
},
error: function (ex) {
console.log(ex);
}
});
}