Related
I am trying to update someone else's code, which uses a XMLHttpRequest setup to get product information from the server for use on some SilverStripe templates. I want to grab the url() function from Product.php so I can use it to get the url for the Product data object and send it to Google Analytics. However, simply appending it to the existing add_fields data does not work--the url function does not get retrieved.
I'm not very familiar with XMLHttpRequests so I'm kind of clueless as to what to do here.
Here is the JavaScript code that is getting the product data:
document.addEventListener("DOMContentLoaded", function(event) {
var productCatalogService = (function() {
var endpoint = "/api/v1/Product/";
return {
'getProductById': function(id, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', endpoint + id + ".json?add_fields=NutritionalInformationLabelURL,SortOrder,BeautyShotURL,url,Recipe"); //url function is not grabbed
xhr.onload = function() {
if (xhr.status === 200) {
callback && callback(JSON.parse(xhr.responseText));
}
else {
console.error('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
}
};
})();
var utils = (function() {
return {
'removeClass': function(node, className) {
node.className = node.className.replace(className, '');
return node;
},
'addClass': function(node, className) {
node.className = node.className.replace(className, '');
node.className += " " + className;
},
'hasClass': function(node, className) {
return node.className.indexOf(className) >= 0;
}
}
})();
var changeProduct = function(product) {
var name = document.querySelector('.product-name'),
subname = document.querySelector('.product-subname'),
tagline = document.querySelector('.product-tagline'),
description = document.querySelector('.product-description'),
beautyShot = document.querySelector('.beauty-shot'),
nutritionFacts = document.querySelector('.ingredients-list'),
mobileNutritionLabel = document.querySelector('.mobile-nutrition-label img'),
nutritionLabel = document.querySelector('.nutritional-label img'),
recipeName = document.querySelector('.recipe-name'),
recipeDescription = document.querySelector('.recipe-description'),
recipeContainer = document.querySelector('.recipe-container');
name.innerHTML = product.Name;
subname.innerHTML = product.SubName;
description.innerHTML = product.Description;
tagline.innerHTML = product.Tagline;
beautyShot.src = product.BeautyShotURL;
if(product.NutritionalInformationLabelURL){
nutritionLabel.src = product.NutritionalInformationLabelURL;
mobileNutritionLabel.src = product.NutritionalInformationLabelURL;
}
if(product.NutritionFacts){
nutritionFacts.innerHTML = product.NutritionFacts;
if(utils.hasClass(nutritionFacts, 'hidden')) {
utils.removeClass(nutritionFacts, 'hidden');
}
} else {
utils.addClass(nutritionFacts, 'hidden');
}
// var pagePath = product.url();
console.log(product.url); //returns undefined
typeof(ga) !== "undefined" && ga('send', 'pageview', {
'page': location.pathname, //want to use the url() function in Product.php here
'title': product.PageTitle
});
};
NodeList.prototype.forEach = Array.prototype.forEach;
var products = document.querySelectorAll('.carousel-products .product');
products.forEach(function(product) {
product.onclick = function() {
var productId = product.getAttribute('data-product-id');
productCatalogService.getProductById(productId, function(product) {
console.log(product);
changeProduct(product); //add recipe data to be pulled in here (fields are above)
});
};
});
});
Product.php
<?php
class Product extends DataObject implements Pageable, Searchable {
private static $api_access = true;
private static $db = [
'Name' => 'varchar(255)',
'SubName' => 'varchar(255)',
'Tagline' => 'varchar(255)',
'Description' => 'HTMLText',
'WhereToBuy' => 'varchar(500)', // external link
'NutritionFacts' => 'HTMLText',
'PageTitle' => 'varchar(250)',
'MetaKeywords' => 'Text',
'MetaDescription' => 'Text',
'SortOrder' =>'Int'
];
private static $has_one = [
'BeautyShot' => 'Image',
'ThumbImage' => 'Image',
'NutritionalInformationLabel' => 'Image',
'Category' => 'Category',
];
private static $summary_fields = [
'GridThumbnail' => 'Photo',
'Name' => 'Name'
];
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab('Root.Main', new TextField("Name", "Name"));
$fields->addFieldToTab('Root.Main', new TextField("SubName", "SubName"));
$fields->addFieldToTab('Root.Main', new TextField("Tagline", "Tagline"));
$fields->addFieldToTab("Root.Main", new HtmlEditorField("Description", "Description"));
$fields->addFieldToTab('Root.Main', new TextField("WhereToBuy", "WhereToBuy"));
$fields->addFieldToTab("Root.Main", new HtmlEditorField("NutritionFacts", "NutritionFacts"));
$fields->addFieldToTab("Root.Main", new UploadField("BeautyShot", "BeautyShot"));
$fields->addFieldToTab("Root.Main", new UploadField("ThumbImage", "ThumbImage"));
$fields->addFieldToTab("Root.Main", new UploadField("NutritionalInformationLabel", "NutritionalInformationLabel"));
$fields->addFieldToTab('Root.SEO', new TextField("PageTitle", "PageTitle"));
$fields->addFieldToTab('Root.SEO', new TextareaField("MetaKeywords", "MetaKeywords"));
$fields->addFieldToTab('Root.SEO', new TextareaField("MetaDescription", "MetaDescription"));
$fields->removeByName('SortOrder');
return $fields;
}
public function getGridThumbNail() {
if ($this->BeautyShot()->exists()) {
return $this->BeautyShot()->SetWidth(100);
}
return '(no image)';
}
public function getBeautyShotURL() {
return $this->BeautyShot()->URL;
}
public function getNutritionalInformationLabelURL() {
if ($this->NutritionalInformationLabel()->Exists()) {
return $this->NutritionalInformationLabel()->URL;
} else {
return "";
}
}
public function getCouponImageURL() {
if ($this->CouponImage()->Exists()) {
return $this->CouponImage()->URL;
} else {
return "";
}
}
public function getProductFullName(){
return $this->Name." ".$this->SubName;
}
public function AbsoluteLink() {
return Director::absoluteURL($this->url());
}
private function url() {
return sprintf("/home/products/%s/%s", $this->Category()->slug(), $this->slug());
}
// lifted from Artisa
public function MetaTags() {
$tags = "";
$generator = trim(Config::inst()->get('SiteTree', 'meta_generator'));
if (!empty($generator)) {
$tags .= "<meta name=\"generator\" content=\"" . Convert::raw2att($generator) . "\" />\n";
}
$charset = Config::inst()->get('ContentNegotiator', 'encoding');
$tags .= "<meta http-equiv=\"Content-type\" content=\"text/html; charset=$charset\" />\n";
if($this->MetaDescription) {
$tags .= "<meta name=\"description\" content=\"" . Convert::raw2att($this->MetaDescription) . "\" />\n";
}
if($this->MetaKeywords) {
$tags .= "<meta name=\"keywords\" content=\"" . Convert::raw2att($this->MetaKeywords) . "\" />\n";
}
if(Permission::check('CMS_ACCESS_CMSMain')
&& in_array('CMSPreviewable', class_implements($this))
&& !$this instanceof ErrorPage
&& $this->ID > 0
) {
$tags .= "<meta name=\"x-page-id\" content=\"{$this->ID}\" />\n";
$tags .= "<meta name=\"x-cms-edit-link\" content=\"" . $this->CMSEditLink() . "\" />\n";
}
$this->extend('MetaTags', $tags);
return $tags;
}
public function canView($member = null){
return true;
}
public function canEdit($member = null) {
return true;
}
public function canCreate($member = null) {
return true;
}
public function slug()
{
return Utilities::friendlyName($this->Name);
}
public function Link()
{
return $this->url();
}
public function getTitleFields() {
return ['Name', 'SubName'];
}
public function getContentFields() {
return ['Description'];
}
public static function getSearchFilter() {
return [];
}
}
// Handles Products and categories
class ProductCsvBulkImporter extends CsvBulkLoader {
protected function processRecord($record, $columnMap, &$results, $preview = false) {
$categoryName = $record['Main Category'];
$productName = $record['Product ID'];
$productSubName = $record['Product Type'];
$productTagline = $record['Product Label'];
$productDescription = $record['Product Description'];
$productKeywords = $record['Keyphrase'];
$category = Category::get()
->filter(['Name' => $categoryName])
->first();
if (!$category) {
$category = new Category();
$category->Name = $categoryName;
$category->write();
}
$product = Product::get()
->filter(['Name' => $productName])
->first();
if (!$product) {
$product = new Product();
}
$product->PageTitle = sprintf("%s %s", $productName, $productSubName);
$product->Name = $productName;
$product->SubName = $productSubName;
$product->Tagline = $productTagline;
$product->Description = $productDescription;
$product->MetaKeywords = $productKeywords;
$product->CategoryID = $category->ID;
$product->write();
return $product->ID;
}
}
I don't know if the code, as it's setup now, is best practice or not as I didn't make it, so if there are mistakes, I can't tell for sure.
Is there some way to append the url() function from Product.php to the .json?add_fields ajax response?
As you can see in the Product class, the url() method it's private, so you don't have access to it outside that class:
private function url() {
return sprintf("/home/products/%s/%s", $this->Category()->slug(), $this->slug());
}
If you change that to:
public function url() {
return sprintf("/home/products/%s/%s", $this->Category()->slug(), $this->slug());
}
it'll probably work... That's all I can say based on the code you submitted. You should know, there's probably a reason why that url() method is private - most probably it's only used internally in the Product class.
If it's still not working, try to duplicate that function like this:
public function getUrl() {
return sprintf("/home/products/%s/%s", $this->Category()->slug(), $this->slug());
}
...and then in the JS code you can use it like this:
console.log(product.Url);
As you can see, you have calls like this in the JS code: product.BeautyShotURL, but the actual method in the Product class it's called getBeautyShotURL(), so it should work with product.Url (this might also work tough: product.getUrl)
I'm facing a very strange issue where I'm able to make asynchronous HTTP call in my local Cent-OS environment but as soon as I push my code to demo server somehow the HTTP calls are not executed asynchronously.
Below is the function that I'm trying to execute,
$scope.getResults = function(){
$http({
url: /getResults,
method: 'POST',
data: data,
headers: {'async': true}
})
.then(function (response) {
var contactId = response.data.contactId[0];
$scope.loadProfileInfo(contactId);
var requestId = response.data.requestId;
$scope.getTotalCount(requestId);
}
});
};
$scope.loadProfileInfo = function(id){
$http({
url: /getProfileInfo,
method: 'POST',
data: {contactId: id},
headers: {'async': true})
.then(function (response) {
//perform operations
});
};
$scope.getTotalCount = function(id){
$http({
url: /getTotalCount,
method: 'POST',
data: {some: data},
headers: {'async': true})
.then(function (response) {
//perform operations
});
};
When I call the function getResults() it loads the results and calls the function loadProfileInfo() which loads the profile information as expected.
Now the issue is the function getTotalCount takes a lot longer to execute and until it does not return the response no other HTTP calls are processed even if they are very small.
I'm using Laravel PHP framework.
Real Code
Reference:
pageChangeHandler() = getResults()
getCount() = getTotalCount()
showProfileAction() = loadProfileInfo()
$scope.pageChangeHandler = function(num) {
$scope.checkMoreResults = false;
console.log("pageChangeHandler begins");
//removing cached values from previous results
$("#analyticsResults").text("...");
$scope.showTitleLevelGraph(['','','','',''], [0,0,0,0,0]);
$scope.showScoreGraph([0,0,0,0,0,0]);
$scope.showGenderGraph([0,0,0]);
$scope.showCompanySizeGraph([0,0,0,0]);
$scope.analyticsFlag = false;
$("#loading-bar").show();
$("#loading-spinner").show();
if ($window.Math.ceil(num*50)>50000){
sweetAlert("Oops", "Seeking is limited to 50,000 results. Please narrow your search or contact a Customer Support rep at 866-535-3960 if you are interested in larger quantities of data.", "error");
} else {
$('body').css('cursor', 'progress');
// if downloadList exists, save it so it can be added to after reloading.
if ($scope.downloadList.length>0) {
$scope.storedSelectedContacts = angular.copy($scope.downloadList);
$scope.storedLiUrl = angular.copy($scope.liUrl);
$scope.storedCompanyName = angular.copy($scope.companyName);
$scope.storedCompLink = angular.copy($scope.compLink);
}
$scope.selectedPage = num;
//$scope.showProfile = false;
//$scope.profileData = null;
if (num > 1 || null!==$scope.shortCode) {
// use code
var data = {'code': $scope.shortCode};
} else {
$scope.shortCode = null;
var data = angular.copy($scope.wizardData);
console.debug(data+" "+JSON.stringify(data));
try{
if (data.state.length > 0) {
for (var x = 0; x < data.state.length; x++) {
data.tbl_company_State[x] = data.state[x].value;
}
data.state = null; // null it out to prevent issues in LV controller
}
}catch(e){
}
}
//console.debug(data);
if ($scope.searchFast == true){
var url = $scope.baseUrl + "/search/fast?page=" + num;
} else {
var url = $scope.baseUrl + "/search/wizard?page=" + num;
console.log("wizard: "+num);
var newsearch = true;
}
console.log("Real data: "+JSON.stringify(data));
$http({
url: url,
method: 'POST',
data: data,
headers: {'async': true}
})
.success(function (response) {
(function() {
setTimeout(function() {
// code-here
//response = response.data;
console.log("Search results: "+JSON.stringify(response));
$('body').css('cursor', 'auto');
//console.debug(response);
if (response.error){
if (response.error == 1000000) {
sweetAlert("Oops", "Your search returned more than 1 million results. Please narrow your search or contact a Customer Support rep at 866-535-3960 if you are interested in larger quantities of data.", "error");
$scope.totalResults = '1000000+';
} else {
sweetAlert("Oops", response.error, "error");
$scope.totalResults = '0';
}
} else {
if (response.data) {
//loading the profile of the first result from the fast load
$scope.selectedAll = false;
$scope.searchResults = response.data;
$scope.totalResults = response.total;
$scope.resultStart = $window.Math.ceil((response.per_page * response.current_page) - response.per_page + 1);
$scope.resultEnd = $window.Math.ceil(response.per_page * response.current_page);
if ($scope.resultEnd > $scope.totalResults) {
$scope.resultEnd = angular.copy($scope.totalResults);
}
$scope.resultsPerPage = response.per_page;
$scope.pageSize = $scope.resultsPerPage;
$scope.lastPage = response.last_page;
$scope.currentPage = response.current_page;
if (response.code) {
$scope.shortCode = response.code;
$scope.disableRange = false;
}
$scope.shareUrl = $scope.baseUrl + '/search/code/' + $scope.shortCode;
console.log();
if (response.data.length > 0) {
if ($scope.currentPage > 1 && $scope.passedCode!='') {
$scope.passedCode=''
}
if ($scope.currentPage == 1 && ($scope.searchFast==true || $scope.searchFast==null)) {
//------Edit Jeet kapadia---//
if($scope.newSearchFlag == false){
$scope.showResults = true;
//loading the profile of the first result from the fast load
$scope.firstContactId = response.data[0].ContactID;
console.log("1 Profile loaded");
$scope.showProfileAction($scope.firstContactId);
}
}*/
//-----End Jeet Kapadia-----//
}
if(newsearch == true && $scope.newSearchFlag == true){
//console.log(response.data[0]);
//$scope.newSaveSelectSearch();
$scope.showResults = false;
newsearch = "false";
}
angular.forEach($scope.searchResults, function (item) {
item.Selected = false;
if (arrayObjectIndexOf($scope.storedSelectedContacts, item.ContactID)>-1 || arrayObjectIndexOf($scope.downloadList, item.ContactID)>-1) {
item.Selected = true;
}
});
$scope.buildDownloadList();
if (response.more){
$scope.totalResults = 'Loading...';
$scope.searchFast=false;
$scope.disableRange = true;
$scope.checkMoreResults = true;
$scope.pageChangeHandler(1);
}else{
$scope.getCount();
//reloading the profile of the first result if the contact changes after all
//the records have been loaded
if($scope.firstContactId != response.data[0].ContactID){
console.log("2 Profile loaded: "+$scope.firstContactId+" "+response.data[0].ContactID);
$scope.showProfileAction(response.data[0].ContactID);
}
//fetching all results to perform analytics on
console.log("short code: "+$scope.shortCode);
//globalAnalyticsInterval = $interval(function () {
}
} else {
sweetAlert("Oops", "Your search returned 0 results. Please widen your search parameters a bit.", "error");
}
}
}
}, 500)
})()
});
}
};
$scope.getCount = function(){
var data = angular.copy($scope.wizardData);
console.debug(data+" "+JSON.stringify(data));
try{
if (data.state.length > 0) {
for (var x = 0; x < data.state.length; x++) {
data.tbl_company_State[x] = data.state[x].value;
}
data.state = null; // null it out to prevent issues in LV controller
}
}catch(e){
}
var url = $scope.baseUrl + "/search/getCount";
$http.post(url, data)
.success(function (response) {
//response = response.data;
$scope.lastPage = response.last_page;
$scope.totalResults = response.total;
console.log("Count: "+JSON.stringify(response));
});
};
$scope.showProfileAction = function(id) {
$scope.liTimeoutFlag = false;
$scope.liResponseFlag = false;
$scope.storedContactId = id;
console.log("showProfileAction: "+id);
$scope.showProfile = false;
$scope.profileData = null;
$("#qualityScoreText").text("Verifying");
$scope.socialScoreFlag = false;
$scope.emailScoreFlag = false;
$("#profileInfo").addClass("visibilityHidden");
try{
$scope.canceller.resolve();
}catch(err){
//console.log("showProfileAction: "+err.message);
}
$scope.userNoteContactId = id;
//getting user notes for the contact
$scope.getUserNoteComment(id);
//console.debug(id);
if (id > 0) {
$scope.idContactSelected = id;
var url = $scope.baseUrl + "/search/contact/" + id;
$('body').css('cursor', 'progress');
$('#profilePanel').css('background-color: #ccc');
$http.get(url)
.then(function (response) {
response = response.data;
$('body').css('cursor', 'auto');
$('#profilePanel').css('background-color: #fff');
if (response.error) {
sweetAlert("Oops", "Contact info could not be loaded.", "error");
} else {
if (response.id) {
if ($scope.mapMarker!==null) {
$scope.mapMarker.setMap(null);
}
$timeout(function(){
$scope.showProfile = true;
}, 100)
$scope.profileData = response;
$("#profileInfo").removeClass("visibilityHidden");
$scope.lat = parseFloat($scope.profileData.Latitude).toFixed(6);
$scope.lon = parseFloat($scope.profileData.Longitude).toFixed(6);
$scope.mapOptions = {
zoom: 14,
center: new google.maps.LatLng($scope.lat, $scope.lon),
// Style for Google Maps
styles: [{"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#ffff00"},{"lightness":-25},{"saturation":-97}]}],
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.mapMarker = new google.maps.Marker({
map: $scope.myMap,
position: $scope.mapOptions.center
});
for(var key in $scope.profileData) {
//console.log(key+" "+$scope.profileData[key]);
}
//verifying the email address of the loaded profile
var emailUrl = $location.protocol() + '://'+ $location.host() + '/contact/verify/' + id;
$http.post(emailUrl)
.then(function (result) {
var singleVerificationKey = result.data.verification_key;
var emailStatus = result.data.status;
var singleEmailResult = result.data.result;
console.log("single email call: "+JSON.stringify(result)+" "+emailStatus);
if($scope.storedContactId == result.data.contactid){
if(emailStatus == "0"){ //when something goes wrong while verifying the email
$("#qualityScoreEmail").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact is UNKNOWN.'></i> Email");
}else if(emailStatus == "2"){ //when the email is verified in last 24 hours
if((singleEmailResult == 'pass')){ //success
$("#qualityScoreEmail").html("<i class='fa fa-check' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact IS up to date.'></i> Email");
}else if((singleEmailResult == 'fail')){ //failed
$("#qualityScoreEmail").html("<i class='fa fa-remove' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact is NOT up to date.'></i> Email");
}else if((singleEmailResult == 'unknown')){ // unknown
$("#qualityScoreEmail").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact is UNKNOWN.'></i> Email");
}
}else if(emailStatus == "1"){
console.log("single email key: "+singleVerificationKey);
//instantiate a Pusher object with our Credential's key
var pusher = new Pusher('2703a05dc7f552e2a2d5', {
encrypted: true
});
//Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe(singleVerificationKey);
//Bind a function to a Event (the full Laravel class)
channel.bind('EmailSingleVerification', $scope.singleEmailVerification);
}
}else{
console.log("single email creation information from previous request");
}
});
// //verifying the social information of the loaded profile
var liUrl = $scope.baseUrl + '/socialVerifyBatch';
var contactIdArr = [id];
var postData = {'id': contactIdArr, 'background': false};
$http.post(liUrl, postData)
.then(function (result) {
setTimeout(function () {
console.log("Timeout: start");
$scope.liTimeoutFlag = true;
if(($scope.storedContactId == result.data.contactid) && (!$scope.liResponseFlag)){
console.log("Timeout: making unknown");
$("#qualityScoreSocial").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact is UNKNOWN'></i> Social");
$scope.animateScore($scope.profileData.Quality_Score, $scope.profileData.Quality_Score-1, 1000);
console.log("here 1");
var url = $scope.baseUrl + '/contact/verifySocial/' + $scope.storedContactId + "/6";
$http.post(url)
.then(function (result) {
console.log("Timeout: Update quality score: "+JSON.stringify(result));
}
);
}
}, 20000);
console.log("single li: "+JSON.stringify(result)+" "+$scope.storedContactId+" "+result.data.contactid);
if($scope.storedContactId == result.data.contactid){
//if the social information was verified in last 24 hours
if(result.data.status == "exist"){
if(result.data.passed == 1){ //success
$("#qualityScoreSocial").html("<i class='fa fa-check' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact IS up to date.'></i> Social");
}else if(result.data.failed == 1){ //failed
$("#qualityScoreSocial").html("<i class='fa fa-remove' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact is NOT up to date.'></i> Social");
}else if(result.data.unknown == 1){ // unknown
$("#qualityScoreSocial").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact is UNKNOWN'></i> Social");
}
}else if(result.data.status == "done"){
var uniqueString = result.data.download_key;
console.log("karthik key: "+uniqueString);
//instantiate a Pusher object with our Credential's key
var pusher = new Pusher('2703a05dc7f552e2a2d5', {
encrypted: true
});
//Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe(uniqueString);
//Bind a function to a Event (the full Laravel class)
channel.bind('SocialBulkVerification', $scope.singleSocialVerification);
console.log("end karthik key");
}
}else{
console.log("single social creation information from previous request");
}
});
}
}
});
} else {
}
}
Any help is appreciated. Thanks in advance.
I have read through this question ASP.NET MVC DropDownListFor not selecting value from model and answer but I don't know the solution to my problem.
This is part of my controller, here is first time when I call the ddl for the view, but not yet select any value.
private void bindDDLRefund(FormModel mod){
// refundCodes = _uow.ParameterRefund.GetAll().Where(e => e.IsDeleted.Value == false).Select(e => e.RefundCode).FirstOrDefault();
mod.DdlRefundPercentage = _uow.ParameterRefund.GetAll().Where(e => e.IsDeleted.Value == false).ToList().Select(e => new SelectListItem { Text = e.CfPercentage.ToString(), Value = e.RefundCode.ToString() }).OrderBy(e => e.Value);
//mod.DdlRefundPercentage = _uow.ParameterRefund.GetAll().Where(e => e.IsDeleted == false).ToList().Select(e => new SelectListItem() { Text = e.CfPercentage.ToString(), Value = e.RefundCode.ToString(), Selected = (e.RefundCode == mod.RefundCode) }).ToList();
}
public ActionResult Add(){
var mod = new FormModel();
//var percentage = GetAllPercentage();
//mod.ddlRefundPercentage = GetSelectListItems(percentage);
bindDDLRefund(mod);
mod.isCreate = true;
return View("Form",mod);
}
Then here is the selected value is being selected from controller,
public JsonResult GetTicketData(string ticketnumber){
bool isSuccess = false;
var result = new spRefTicketRefundRetrieve();
int isError = 0;
string errorDesc = "";
var mod = new FormModel();
try{
spRefTicketRefundRetrieveHeader obj = _uow.StoreProc.spRefTicketRefundRetrieve(ticketnumber);
isError = obj.IsError;
errorDesc = obj.ErrorDesc;
if (obj.IsError == 0){
result = obj.detailData;
}
isSuccess = true;
}
catch (Exception ex){
Logger.LogError("Reload Ticket Data", "Id = " + ticketnumber, ex);
}
return Json(new { success = isSuccess, value = result, isError = isError, errorDesc = errorDesc }, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult GetRefundData(string refund_id)
{
bool isSuccess = false;
var result = new spRefTicketRefundDetail();
int refundId = Encryption.Decrypt(refund_id);
try
{
result = _uow.StoreProc.spRefTicketRefundDetail(refundId);
isSuccess = true;
}
catch (Exception ex)
{
Logger.LogError("Reload Refund Data", "Id = " + refundId, ex);
}
return Json(new { success = isSuccess, value = result }, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult GetCFData(string ticketNumber, string refundCode)
{
bool isSuccess = false;
var result = new spRefTicketRefundChangeCF();
int isError = 0;
string errorDesc = "";
try
{
spRefTicketRefundChangeCFHeader obj = _uow.StoreProc.spRefTicketRefundChangeCF(ticketNumber, refundCode);
isError = obj.IsError;
errorDesc = obj.ErrorDesc;
if (obj.IsError == 0)
{
result = obj.listData;
}
isSuccess = true;
}
catch (Exception ex)
{
Logger.LogError("Reload CF Data", "Id = " + ticketNumber, ex);
}
return Json(new { success = isSuccess, value = result, isError = isError, errorDesc = errorDesc }, JsonRequestBehavior.AllowGet);
}
The selected value is about CfPercentage and variable result contains CF_PERCENTAGE which is representate of CfPercentage,
And here is my view and jQuery;
#Html.DropDownListFor(e => e.RefundCode, Model.DdlRefundPercentage, new { #class = "form-control", id= "ddl-refund",onchange="CFChange();" })
var GetRefundData = function (refundId) {
$.ajax({
url: '#Url.Action("GetRefundData")',
type: 'POST',
data: { refund_id: refundId },
success: function (result) {
console.log(result);
if (result.success) {
SetFormDetail(result.value);
}
else
{
}
},
error: function (result) {
alert('Something error occured, please refresh the page.')
}
});
};
var GetRefundViewData = function (refundId) {
$.ajax({
url: '#Url.Action("GetRefundData")',
type: 'POST',
data: { refund_id: refundId },
success: function (result) {
console.log(result);
if (result.success) {
SetFormView(result.value);
}
else {
}
},
error: function (result) {
alert('Something error occured, please refresh the page.')
}
});
};
var GetTicketData = function (ticketNumber) {
var target = $("#loading");
$.ajax({
beforeSend: function () {
target.html('<img src="#Url.Content("~/Content/images/ajax-loader.gif")"> loading...');
$('#divForm').css('display', 'none');
},
url: '#Url.Action("GetTicketData")',
type: 'POST',
data: { ticketnumber: ticketNumber },
success: function (result) {
console.log(result);
if (result.success) {
target.html('');
if (result.isError == "0") {
$('#divForm').css('display', 'block');
$('#txtHiddenTicketNumber').val(ticketNumber);
SetForm(result.value);
GetCFData();
}
else {
alert(result.errorDesc);
}
}
else {
$("#loading").html('');
}
},
error: function (result) {
alert('Something error occured, please refresh the page.')
}
});
};
var CFChange = function ()
{
GetCFData();
};
var GetCFData = function ()
{
var TicketNumber = $('#txtHiddenTicketNumber').val();
var RefundCode = $("#ddl-refund option:selected").val();
$.ajax({
url: '#Url.Action("GetCFData")',
type: 'POST',
data: { ticketNumber: TicketNumber, refundCode: RefundCode },
success: function (result) {
console.log(result);
if (result.success) {
SetCFDetail(result.value);
}
else {
}
},
error: function (result) {
alert('Something error occured, please refresh the page.')
}
});
};
var SetForm = function(list){
$(list).each(function () {
$('#txtManualRefundNo').val(this.MANUAL_REFUND_NO);
$('#lblLocOfficeCode').html(this.LOCATION_OFFICE_CODE);
$('#lblPnrCode').html(this.PNR_CODE);
$('#lblPnrTicket').html(this.PNR_CODE + "/ " + this.TICKET_NUMBER);
$('#lblIssuedDate').html(this.ISSUED_DATE_STR);
$('#lblPassengerName').html(this.PASSENGER_NAME);
$('#lblRouteClass').html(this.ROUTE + "/ " + this.CLASS_CODE);
$('#lblFlight').html(this.FLIGHT_DATE_STR + " - " + this.FLIGHT_NUMBER);
$('#lblBaseComm').html(this.BASE_PRICE_STR + "/ " + this.COMMISSION_NOMINAL_STR);
$('#lblTax').html(this.TOT_TAX_STR + "/ " + this.TOT_NON_TAX_STR);
$('#lblPublish').html(this.PUBLISH_RATE_STR);
$('#lblRefundPercentage').html(this.CANCELLATION_FEE_PERCENTAGE_STR);
$('#lblCancelFee').html(this.CANCELLATION_FEE_AMOUNT_STR);
$('#lblAdminFee').html(this.ADMIN_FEE_STR);
$('#lblCommFee').html(this.COMMISSION_FEE_STR);
$('#lblTicketUsed').html(this.TICKET_USED);
$('#lblTotalRefund').html(this.REFUND_AMOUNT_STR);
$('#txtReason').val('');
$('#ddl-refund :selected').text(this.CANCELLATION_FEE_PERCENTAGE_STR);
});
};
var SetFormDetail = function (list) {
$(list).each(function () {
$('#txtManualRefundNo').val(this.MANUAL_REFUND_NO);
$('#lblLocOfficeCode').html(this.LOCATION_OFFICE_CODE);
$('#lblPnrCode').html(this.PNR_CODE);
$('#lblPnrTicket').html(this.PNR_CODE + "/ " + this.TICKET_NUMBER);
$('#lblIssuedDate').html(this.ISSUED_DATE_STR);
$('#lblPassengerName').html(this.PASSENGER_NAME);
$('#lblRouteClass').html(this.ROUTE + "/ " + this.CLASS_CODE);
$('#lblFlight').html(this.FLIGHT_DATE_STR + " - " + this.FLIGHT_NUMBER);
$('#lblBaseComm').html(this.BASE_PRICE_STR + "/ " + this.COMMISSION_NOMINAL_STR);
$('#lblTax').html(this.TOT_TAX_STR + "/ " + this.TOT_NON_TAX_STR);
$('#lblPublish').html(this.PUBLISH_RATE_STR);
$('#lblCancelFee').html(this.CANCELLATION_FEE_AMOUNT_STR);
$('#lblAdminFee').html(this.ADMIN_FEE_STR);
$('#lblCommFee').html(this.COMMISSION_FEE_STR);
$('#lblTicketUsed').html(this.USED_FEE_STR);
$('#lblTotalRefund').html(this.REFUND_AMOUNT_STR);
$('#txtReason').val(this.DESCRIPTION);
$('#lblRefundPercentage').html(this.CANCELLATION_FEE_PERCENTAGE_STR);
//$('#txtHiddenTicketNumber').val(this.TICKET_NUMBER);
$("#ddl-refund").val(this.REFUND_CODE);
});
//GetCFData();
};
var SetFormView = function (list) {
$(list).each(function () {
$('#txtManualRefundNo').val(this.MANUAL_REFUND_NO);
$('#lblLocOfficeCode').html(this.LOCATION_OFFICE_CODE);
$('#lblPnrCode').html(this.PNR_CODE);
$('#lblPnrTicket').html(this.PNR_CODE + "/ " + this.TICKET_NUMBER);
$('#lblIssuedDate').html(this.ISSUED_DATE_STR);
$('#lblPassengerName').html(this.PASSENGER_NAME);
$('#lblRouteClass').html(this.ROUTE + "/ " + this.CLASS_CODE);
$('#lblFlight').html(this.FLIGHT_DATE_STR + " - " + this.FLIGHT_NUMBER);
$('#lblBaseComm').html(this.BASE_PRICE_STR + "/ " + this.COMMISSION_NOMINAL_STR);
$('#lblTax').html(this.TOT_TAX_STR + "/ " + this.TOT_NON_TAX_STR);
$('#lblPublish').html(this.PUBLISH_RATE_STR);
$('#lblCancelFee').html(this.CANCELLATION_FEE_AMOUNT_STR);
$('#lblAdminFee').html(this.ADMIN_FEE_STR);
$('#lblCommFee').html(this.COMMISSION_FEE_STR);
$('#lblTicketUsed').html(this.USED_FEE_STR);
$('#lblTotalRefund').html(this.REFUND_AMOUNT_STR);
$('#lblPaymentType').html(this.PAYMENT_TYPE);
$('#lblReason').html(this.DESCRIPTION);
$('#lblRefundPercentage').html(this.CANCELLATION_FEE_PERCENTAGE_STR);
//$('#txtHiddenTicketNumber').val(this.TICKET_NUMBER);
$("#ddl-refund").val(this.REFUND_CODE);
});
//GetCFData();
};
var SetCFDetail = function (list) {
$(list).each(function () {
$('#lblCancelFee').html(this.CANCELLATION_FEE_AMOUNT_STR);
$('#lblAdminFee').html(this.ADMIN_FEE_STR);
$('#lblCommFee').html(this.COMMISSION_FEE_STR);
$('#lblTotalRefund').html(this.REFUND_AMOUNT_STR);
});
};
After I running this, the view is always not select percentage based on sp that is relevant to ticketnumber. I have tried to modified it but nothing works. feel happy to be help :)
This line,
$('#ddl-refund :selected').text(this.CANCELLATION_FEE_PERCENTAGE_STR)
It actually set's the currently selected option's text to whatever value in this.CANCELLATION_FEE_PERCENTAGE_STR . It won't actually change the selected option. You can see it in action here.
What you should be doing Get the RefundCode value from your server call, and pass that in the val() method to set specific option item as the selected item.
Assuming your razor rendered your dropdown with this markup.
<SELECT id="ddl-refund">
<option value="25">Twenty Five</option>
<option value="26">Twenty Six</option>
<option value="28">Twenty Eight</option>
<option value="29">Twenty Nine</option>
And json data you received from your server call has a property called RedundCode.
$(list).each(function () {
$("#ddl-refund").val(this.RefundCode);
}
It will work if this.RefundCode is either 25 or 26 or 28 or 29.
I am not quite sure, why you are sending an array when all you want to send is a single item. But that is a different thing to fix.
I am working with MVC and Ajax and jQuery. I am returning my JSON value from my action method like below.
public ActionResult GetMYSDRViews(List<string> AssetNames, List<string> UtilizationHubs, string RedirectView)
{
try
{
//ViewBag.InitParams = MvcApplication.objInitParams;
string UserType = MvcApplication.objInitParams.UserType;
bool Execute;
List<MYSDR> MysdrListCollection = new List<MYSDR>();
ServiceClient objService = new ServiceClient();
objService.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("v-saramb", "sdatnov#2014", "REDMOND");
objService.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
var result = String.Empty;
if (RedirectView == "Agent View")
{
ViewData["Flag"] = "AgentView";
#region Agent View
result = objService.SalesDeskAgent_DynamicAsset("REDMOND\\v-susudh", "", "");
#endregion
}
else if (RedirectView == "Manager View")
{
//result = objService.SalesDeskAgent_DynamicAsset("REDMOND\\v-susudh", "", "");
ViewData["Flag"] = "Manager View";
userHUbdata.Clear();
foreach (string Hub in UtilizationHubs)
{
ServiceReference.MYSDRFields obj2 = new ServiceReference.MYSDRFields();
obj2.Hub = Hub;//cmbHubs.SelectedItem.ToString();
if (obj2.Hub != "All")
userHUbdata.Add(obj2);
}
result = objService.SalesDeskManagerView_ConditionbasedwithFilters("", "", userHUbdata, true);
}
//else if (RedirectView == "BulkAssignment View")
// {
// result = objService.SalesDeskManagerView("REDMOND\\v-susudh", "");
// }
XDocument xmldoc = null;
try
{
xmldoc = XDocument.Parse(result.ToString());
Execute = true;
}
catch
{
Execute = false;
}
if (Execute)
{
#region
MysdrListCollection.Clear();
var data = (from info in xmldoc.Elements("NewDataSet").Elements("Table1")
where Convert.ToString(info.Element("Status").Value) != "" && Convert.ToString(info.Element("Status").Value) != "New" && Convert.ToString(info.Element("Status").Value) != "Projected"
select new MYSDR
{
SRNO = Convert.ToString(info.Element("SRNO").Value),
CustomerName = Convert.ToString(info.Element("CustomerName0").Value),
ServiceLevel = Convert.ToString(info.Element("TypeofRequest").Value.Replace("Unsolicited", "Proactive").Replace("Partner Proactive", "Proactive")),
CRMID = Convert.ToString(info.Element("CRMID").Value),
//DueDate_Date = Convert.ToDateTime(info.Element("DueDate").Value),
RequestType = ((Convert.ToString(info.Element("TypeofRequest").Value) == "Managed Proposal") || (Convert.ToString(info.Element("TypeofRequest").Value) == "Standard Proposal") || (Convert.ToString(info.Element("TypeofRequest").Value) == "Unsolicited Proposal") || (Convert.ToString(info.Element("TypeofRequest").Value) == "Unsolicited Proposal Lite")) ? "Proposal" : ((Convert.ToString(info.Element("TypeofRequest").Value) == "AIO") || (Convert.ToString(info.Element("TypeofRequest").Value) == "AIO Prep")) ? "AIO" : ((Convert.ToString(info.Element("TypeofRequest").Value) == "M&A Full") || (Convert.ToString(info.Element("TypeofRequest").Value) == "M&A Light")) ? "M&A" : Convert.ToString(info.Element("TypeofRequest").Value),
Region = Convert.ToString(info.Element("Region").Value),
Segment = Convert.ToString(info.Element("Segment").Value),
Assigned = ((Convert.ToString(info.Element("Status").Value) == "Projected") || ((Convert.ToString(info.Element("Status").Value) == "New"))) ? "Assign" : Convert.ToString(info.Element("AssignedToName").Value),
Language = Convert.ToString(info.Element("Language").Value),
ID = Convert.ToString(info.Element("ID").Value),
Status = Convert.ToString(info.Element("Status").Value),
AM = Convert.ToString(info.Element("AM").Value),
Hub = Convert.ToString(info.Element("Hub").Value),
DueDate = Convert.ToDateTime(info.Element("DueDate").Value).Date,
RequestDate = Convert.ToDateTime(info.Element("Requestdate").Value).Date,
PrimaryContact = Convert.ToString(info.Element("PrimaryContact").Value),
Country = Convert.ToString(info.Element("Country").Value),
SolutionForProposal = Convert.ToString(info.Element("SolutionForProposal").Value),
Reactive = ((Convert.ToString(info.Element("TypeofRequest").Value).Contains("Research")) && (Convert.ToString(info.Element("RequestOrigin").Value) == "Reactive")) ? "R" : "",
CoOwner = ((Convert.ToString(info.Element("Status").Value) == "New") || (Convert.ToString(info.Element("Status").Value) == "Projected") || (Convert.ToString(info.Element("TypeofRequest").Value).StartsWith("QA"))) ? "" : (((Convert.ToString(info.Element("Status").Value) != "New") || (Convert.ToString(info.Element("Status").Value) != "Projected")) && (Convert.ToString(info.Element("Coowner").Value) == "")) ? "Add Co-Owner" : (Convert.ToString(info.Element("Coowner").Value)),
}).AsEnumerable();
MysdrListCollection = data.ToList<MYSDR>();
// Session["MYSDRGridAgentView"] = MysdrListCollection.OrderBy(a => a.DueDate);
// return View(data);
#endregion
}
var serializer = new JavaScriptSerializer();
var resultContent = new ContentResult();
serializer.MaxJsonLength = Int32.MaxValue; // Whatever max length you want here
resultContent.Content = serializer.Serialize(MysdrListCollection.OrderBy(a => a.DueDate));
resultContent.ContentType = "application/json";
return resultContent;
// return Json(MysdrListCollection.OrderBy(a => a.DueDate),JsonRequestBehavior.AllowGet);
// return View("Mysdrviews",MysdrListCollection.OrderBy(a => a.DueDate));
//return MysdrListCollection;
}
catch (Exception ex)
{
return Json("");
}
}
I am using my Ajax call from jQuery like below.
$.ajax({
url: '#Url.Action("GetMYSDRViews", "MYSDR")',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
// url: '/MYSDR/PostbtnSubmit',
data: JSON.stringify({ AssetNames: itemsListAssets, UtilizationHubs: itemUtilizationHub, RedirectView: 'Manager View' }),
success: function (result) {
debugger;
var grid = $('#MYSDRGridAgentView').getKendoGrid();
grid.dataSource.data(result);
grid.refresh();
$('#Loader').oLoader('hide');
// $('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
debugger;
// $('#result').html(response);
}
});
Up to here everything is fine. But when I try to return my JSON result in my return view method like below, I am not getting any error, but I am not able to successfully return result, and my debugger pint also is not hitting at the Success or Error functions in my jQuery.
Please let me know where to change my Ajax function. I am stuck here like anything.
Make the function a JsonResult and return Json(something).
public JsonResult GetMYSDRViews(List<string> AssetNames, List<string> UtilizationHubs, string RedirectView)
{
...
return Json(MysdrListCollection.OrderBy(a => a.DueDate));
}
You put failure instead of error.
error: function (response) {
debugger;
// $('#result').html(response);
}
I try following way :
My Action is :
[HttpPost]
public ActionResult PaymentVoucherCommit(string sParameter)
{
try
{
_oVoucher = new Voucher();
_oVoucher = _oVoucher.CommitVoucherNo(2, 1); // Here 2 refere VoucherTypeID that is PaymentVoucher & 1 refere jam company ID
_oVoucher.BaseCurrencyId = 1; //jas......this code is temporary
_oVoucher.CompanyID = 1;//jas......this code is temporary
_oVoucher.VoucherTypeID = 2;//jam for temporary basis code 2 is paymenttypeid that is payment voucher
_oVoucher.CurrencyId = 1;
_oVoucher.BaseCurrencyNameSymbol = "Taka[Tk]"; //jas......this code is temporary
_oVoucher.VoucherDetailLst = VoucherDetail.Gets(_oVoucher.VoucherID);
_oVoucher.LstCurrency = Currency.Gets();
_oVoucher.Operation = "AddPaymnetVoucher";
_oVoucher.DebitAccountHeadName = "Press Enter";
_oVoucher.CreditAccountHeadName = "Press Enter";
return View(_oVoucher);
}
catch (Exception ex)
{
return View(ex.Message);
}
}
And my javascript code is :
$('#btnCommit').keypress(function (e) {
debugger;
var keyCode = e.keyCode || e.which;
if (keyCode == 13) {
$.ajax({
type: "POST",
dataType: "text json",
url: '#Url.Action("PaymentVoucherCommit", "Voucher")',
data: { sParameter: "Bangladesh" },
contentType: "application/json; charset=utf-8",
success: function (data) {
// debugger;
alert(data);
},
error: function (xhr, status, error) {
alert(error);
}
});
return false;
}
})
please fix this bug.
Note : same type of task i am successfully complete for [httpGet] request. But i a triad for post type action(Action Result)
Try simply:
$('#btnCommit').keypress(function (e) {
debugger;
var keyCode = e.keyCode || e.which;
if (keyCode == 13) {
$.post('#Html.Raw(Url.Action("PaymentVoucherCommit", "Voucher"))', { sParameter: "Bangladesh" }, function(view){
alert(view);
});
return false;
}
})
If you want to return Json, then:
[HttpPost]
public JsonResult PaymentVoucherCommit(string sParameter)
{
try
{
_oVoucher = new Voucher();
_oVoucher = _oVoucher.CommitVoucherNo(2, 1); // Here 2 refere VoucherTypeID that is PaymentVoucher & 1 refere jam company ID
_oVoucher.BaseCurrencyId = 1; //jas......this code is temporary
_oVoucher.CompanyID = 1;//jas......this code is temporary
_oVoucher.VoucherTypeID = 2;//jam for temporary basis code 2 is paymenttypeid that is payment voucher
_oVoucher.CurrencyId = 1;
_oVoucher.BaseCurrencyNameSymbol = "Taka[Tk]"; //jas......this code is temporary
_oVoucher.VoucherDetailLst = VoucherDetail.Gets(_oVoucher.VoucherID);
_oVoucher.LstCurrency = Currency.Gets();
_oVoucher.Operation = "AddPaymnetVoucher";
_oVoucher.DebitAccountHeadName = "Press Enter";
_oVoucher.CreditAccountHeadName = "Press Enter";
return Json(_oVoucher);
}
catch (Exception ex)
{
return Json(ex.Message);
}
}