ASP MVC Redirect using Ajax - ajax

I am having trouble with my redirects picking up the existing url. I have a page that has google charts on it where I have added a listener to the bars in a bar chart. When a user clicks on one of the bar charts a case statement determines what id to pass to the router.
google.visualization.events.addListener(wrapper, 'select', selectHandler);
function selectHandler() {
var selection = wrapper.getChart().getSelection()
var monthsTransform = 0;
switch(selection[0].column)
{
case 1:
monthsTransform = 0;
break;
case 2:
monthsTransform = 3;
break;
case 3:
monthsTransform = 6;
break;
case 4:
monthsTransform = 12;
break;
case 5:
monthsTransform = 18;
break;
//no need to default as already set to 0!
}
var url = "newController/newPage/" + monthsTransform;
window.location.href = url;
}
The problem I have is that the
window.location.href
is appending the newController/newPage to the existing url, so it ends up like:
localhost:1234/oldController/oldPage/newController/newPage/id

Use window.location.assign("/newController/newPage/" + monthsTransform), instead of window.location.href
It would even be nicer if you added the server name and protocol in front of the new URL, and used Html.Action html helper to generate the url.

Check my blog post on creating URL's on the server side:
http://ilovedevelopment.blogspot.co.uk/2012/04/aspnet-mvc-3-generating-actionlink-in.html
The crux of it I've pasted below for brevity - modify as required:
string absoluteAction = string.Format("{0}://{1}{2}",
Url.RequestContext.HttpContext.Request.Url.Scheme,
Url.RequestContext.HttpContext.Request.Url.Authority,
Url.Action("ActionName", "ControllerName", new {Id = "Data"}));
This can be done inside a controller method so you could make an ajax call and return the proper url "absoluteAction" as a Json result.

Related

Google script spreadsheet - I need to run one script from multiple buttons but with different parameters

I have two buttons (Button1 and Button2) and one function: MyFunction(number). And I either need to pass a parameter to the function or find out what button the function was started from. Is it possible?
function MakePDF(number) {
var ui = SpreadsheetApp.getUi();
//Get Active Spreadsheet
var spreadSheet=SpreadsheetApp.getActiveSpreadsheet();
spreadSheet.getRange('B2').setValue(number); //HERE I NEED TO GET THE SPECIFIC NUMBER FROM 1 TO 100
//Get Sheet to print of the spreadsheets
var sheets=spreadSheet.getSheets();
var Faktura = spreadSheet.getSheetByName("Invoice");
var sheetID = Faktura.getSheetId();
//Export URL with Parameters
var spreadSheetId = spreadSheet.getId();
var URL = "https://docs.google.com/spreadsheets/d/"+spreadSheetId+"/export"+
"?format=pdf&"+
"size=7&"+
"fzr=false&"+
"portrait=true&"+
"fitw=true&"+
"gridlines=false&"+
"printtitle=false&"+
"sheetnames=false&"+
"pagenum=UNDEFINED&"+
"attachment=true&"+
"gid="+sheetID;
//the HTTP method for the request: get and headers : authorization : Bearer tokens to access OAuth 2.0-protected resources
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
//Return the data inside this object as a blob.
var response=UrlFetchApp.fetch(URL,params).getBlob();
//To set name of file
var VS = listOvladani.getRange('B6').getValue();
var firma = listOvladani.getRange('B5').getValue();
firma = removeDiak(firma);
firma = firma.toString().replace(/ /g, '-');
firma = firma.toString().replace(/\./g,'');
firma = firma.toString().replace(/,/g,'');
var namePDF = VS + "_" + firma + "_Autonapul.pdf";
// Load it to specific directory
var dir = DriveApp.getFoldersByName("Rucnifaktury").next();
var pdfFile = dir.createFile(response).setName(namePDF);
// Display a modal dialog box with custom HtmlService content.
const htmlOutput = HtmlService
.createHtmlOutput('<p>Click to open ' + spreadSheet.getName() + '</p>')
.setWidth(300)
.setHeight(80)
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Export Successful');
//Email it
/* MailApp.sendEmail('trnka#trnka.cz', 'Pokus', 'Nějaký text', {
attachments: [{
fileName: "Faktura_pokusna" + ".pdf",
content: response.getBytes(),
mimeType: "application/pdf"
}]
});
*/
}
More details More details More details More details More details More details More details More details More details More details More details More details
You can do it in a different way:
Replace buttons through checkboxes and bind to your script an onEdit(e) trigger which will automatically fire the script on each edit.
You can implement a statement to verify either the edited column was your checkbox column and if so - which checkbox has been checked.
Sample:
function onEdit(e) {
if(e.range.getColumn()==2&&e.range.getValue()==true){
Logger.log(e.range.getA1Notation());
}
}
References:
Event objects
getValue()
getColumn
A1 notation
You can use two more functions who just call the main function with a different parameter, so button 1 calls pressButton1 and button 2 calls pressButton2.
function MakePDF(number) {
//do stuff
}
function pressButton1(){
MakePDF(1);
}
function pressButton2(){
MakePDF(2);
}
This is the easiest way to handle the situation.

Dynamic menu configuration section with conditional inputs on Magento custom module

I've followed this tutorial to create a custom dynamic backend configuration with serialized data, and everything is working as expected. yay
But now I want to take another step and only show some inputs when a specific value is selected in a select box. I know that I can use when doing this with system.xml, but how can I accomplish the same thing via code with dynamics serialized tables?
I ended up doing some kind of Javascript workaround to enable/disable a certain input.
function togleSelect(element)
{
var val = element.value;
var name = element.name;
if (val == 0) // select value to be triggered
{
name = name.substr(0, name.lastIndexOf("[")) + "[name_of_my_input]";
var target = document.getElementsByName(name);
target[0].disabled = false;
}
else
{
name = name.substr(0, name.lastIndexOf("[")) + "[name_of_my_input]";
var target = document.getElementsByName(name);
target[0].disabled = true;
}
}
It's not the best solution but it's working.

Pass get values to method and call in jsp page

I'm using spring mvc, making a small web-app.
I have a form in a jsp page, and I'm trying to pass the values from my .GET controller to a method and display the results from the called method after pressing the "Submit" button on the same JSP page or another, preferrably on the same page.
This is how the form looks like:
http://i65.tinypic.com/6gyo02.png
This is the method I want to be called after getting the values from the form:
public void calcMacros() {
int goal = 0;
if (this.goal == 0.7){
goal = 1;
} else if (this.goal == 0.9) {
goal = 2;
} else if (this.goal == 1) {
goal = 3;
} else if (this.goal == 1.2){
goal = 4;
}
switch (goal) {
case 1: weightLoss();
weightLossProtCalc();
weightLossCarbCalc();
weightLossFatCalc();
break;
case 2: weightLoss();
weightLossProtCalc();
weightLossCarbCalc();
weightLossFatCalc();
break;
case 3: tdeeCalculator();
maintainProteinCalc();
maintainCarbCalc();
maintainFatCalc();
break;
case 4: weightGain();
weightGainProtCalc();
weightGainCarbCalc();
weightGainFatCalc();
break;
default:
break;
}
System.out.println("selected goal was " + goal + "and proper methods have been called.");
}
Best question would be, how can I transform this method into a .POST controller so I can display it's results in the same JSP page. Also how do I call this method/controller in the JSP page?
Thank you!
Edit: Controller
#RequestMapping(value = "/calculator" , method = RequestMethod.GET)
public String calculatorPage(ModelMap model, MacroCalculatorForm macroCalculatorForm) {
model.addAttribute("user",getPrincipal());
macroCalculatorForm.calcMacros();
return "calculator";
}
Would this do it, or should I rewrite the method I want to get called into this controller?
You should have two methods in your #Controller:
(1) One method which supports GET : This is to provide the display View of the first page (before the calculations).
(2) One method which supports POST: This is to process the inputs received from the first page and then sending the results to the View (JSP) back.
Reading values from GET requests is easy. It's only need to define parameters with input names as following for age example :
#RequestMapping(value = "/calculator" , method = RequestMethod.GET)
public String calculatorPage(ModelMap model,
MacroCalculatorForm macroCalculatorForm,
#RequestParam(value = "age") int age)
{
//Now you can use age value in your method
model.addAttribute("user",getPrincipal());
macroCalculatorForm.calcMacros();
return "calculator";
}

Zend 1 ajax with dojo informatiom person

I'm working with Zend 1 with dojo and do not know how to use ajax . In my particular case that when selecting a select , whether made ​​in consultation ajax back from the database information. To enter a ID from user print the information from user by ajax.In my work I can't use jquery.
Good question!
Not is very productive work with dojo, but is possible make exactly how do you want. You will create p element with information captured in data base
In your form, add attribute 'onChange'
$form->setAttrib('onChange', 'recoveryData()');
In js file do you have a function recoveryData(), something as:
dojo.require("dojo.html");
// clean data
var myNewElement = dojo.byId('myNewElement');
if (myNewElement != null) {
dojo.empty("myNewElement");
}
dojo.xhrPost({
content: {id: dojo.attr(dojo.byId("myElement"), "value")},
url: 'your-base-path/recovery-data/',
load: function (response) {
if (response != false) {
// converte to obj
var obj = dojo.fromJson(response);
// creat new element
var node = dojo.create("span", {
innerHTML: obj.NomeServidor,
id: "myNewElement",
'class': 'row'
}
);
dojo.place(node, dojo.byId("myElement"), "after");
}
}
});
Now, you need create an Action "recoveryDataAction()" in your Controller like this:
$data = $this->getrequest()->getPost();
$id = $data['id'];
if ($this->getrequest()->isXmlHttpRequest()) {
// disable layout
$this->_helper->layout()->disableLayout();
// disable view render
$this->_helper->viewRenderer->setNoRender();
$yourTable = new Project_Model_YourTable();
$row = $yourTable->fetchRow($id);
if ($infos != null) {
echo Zend_Json::encode($row);
return;
}
echo false;
}

How to Cache Multiple Versions of a Page using Razor Dynamic Query & WebCache

I decided to implement caching to improve the performance of the product pages.
Each page contains a large amount of the product's images.
I created the following code in a Razor view.
#{
var productID = UrlData[0].AsInt();
var cacheItemKey = "products";
var cacheHit = true;
var data = WebCache.Get(cacheItemKey);
var db = Database.Open("adldb");
if (data == null) {
cacheHit = false;
}
if (cacheHit == false) {
data = db.Query("SELECT * FROM Products WHERE ProductID = #0", productID).ToList();
WebCache.Set(cacheItemKey, data, 1, false);
}
}
I'm using the data with the following code:
#foreach (dynamic p in data)
{
<a href="~/Products/View/#p.ProductID"
<img src="~/Thumbnail/#p.ProductID"></a>
}
The caching code works well, but when passing the new query string parameter (changing the version of the page) the result in browser is the same for the declared cashing time.
How to make caching every version of the page?
Thanks
Oleg
A very simple approach might be to convert your key (productID) to a string and append it to the name of your cacheItemKey.
So you might consider changing the line:
var cacheItemKey = "products";
to read:
var cacheItemKey = "products" + productID.ToString();
This should produce the behavior you are looking for -- basically mimicking a VaryByParam setup.
ps. Please keep in mind I have not added any sort of defensive code, which you should do.
Hope that helps.

Resources