WebGrid Paging/Sorting AJAX is extending the querystring [closed] - ajax

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a WebGrid in a cshtml view and i'm using the ajaxUpdateContainerId parameter to page/sort it using AJAX. But, each time i click on a link to page/sort the WebGrid, the href is changing and the querystring add a "__swhg" parameter.
Please refer the attached image
And the querystring just keep growing like this each time I click on the sort/pager, the "__swhg" parameter keep growing because "href" attributes in the WebGrid are adding this to the simple "?sort=&sortdir=" or "?page=".!

This parameter represents an unique timestamp and is added to each url on purpose. Since the AJAX requests are using GET verb, those requests might be cached by the browser. This means that when the user clicks on the links, your server might never be reached. The parameter ensures that the responses are not cached, because each time you get an unique url. Currently this is hardcoded in the WebGrid and there's no way to disable it.
Of course if for some reason you want to shoot yourself in the foot and remove this parameter one possibility is to subscribe to a custom AJAX callback:
var grid = new WebGrid(
Model,
ajaxUpdateContainerId: "grid",
ajaxUpdateCallback: "callback"
);
in which you could replace all links and remove the __swhg parameter:
function callback() {
$('a[data-swhglnk="true"]').attr('href', function () {
return this.href.replace(/&__swhg=[0-9]{13}/, '');
});
}

Related

Knockout and downloading csv/pdf [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am using ASP.NET MVC and knockout.
I have a form to gather information.
The last field in the form, is the output type:
which can be HTML/CSV/PDF.
I have difficulties to output the result into CSV or PDF.
As knockout submit the form using ajax and ajax cannot save
the result into CSV or PDF.
If you have any idea, could you please let me know.
Thanks.
you cannot use knockout to create pdf. post your data to the server via ajax, and make asp.net create the pdf via C# from the server, and once the pdf is created, you can make it available to download.
Use a form to post the data parameters to the server.
If you need to use parameters that are KO Observables or js variables, you can append them to the form using a js function like this:
function downloadFile(idForm, parameters) {
var id = '#' + idForm;
$(id).submit(function () { //listen for submit event
$(id + ' input').empty().remove();
$.each(parameters, function (i, item) {
$('<input />').attr('type', 'hidden')
.attr('name', item.name)
.attr('value', item.value)
.appendTo(id);
});
return true;
});
$(id).submit();
};
You could pass an extra parameter indicating if you want to download a HTML, CSV or PDF file.

Can we change the content of the page without using AJAX [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I mainly use AJAX to update parts of a web page, without reloading the whole page.
can i do it without using AJAX
Please refer, Refresh content of a div without ajax
If something is to be done in server side without refresh you should be using AJAX. Else you can simply use javascript codes.
For show/hide content(if nothing to be done in server side), you can just simply use javascript codes or jquery.
eg.
simple javascript
document.getElementById('myContent').display = 'none';
document.getElementById('myContent').display = 'block';
jquery
$('#myContent').hide();
$('#myContent').show();
where myContent is the content element id
If you don't need any new information from the server, just use JavaScript to manipulate the DOM. Add event handlers to your HTML elements to trigger your JavaScript code.
One example to get new information from the server and feed it to your JavaScript: add <script src="..."> node to the DOM.
If you want to change images only, then change the .src attribute of a DOM image, or create a new Image from JavaScript and add it to the DOM.
If you want to draw something onto a rectangle, create a <canvas> element and draw to it using JavaScript.
Possibly there are many other ways.
Yes. I have often done this e.g. using a tabbed menu therefore the header, footer and menu stay the same but the content changes. I did this by wrapping a class around both pieces of content, I then displayed:none; on one of the classes which causes it to hide. Then on click of your choice, using a jquery function within a javascript function, you can then toggle between the two classes which effectively gives you a content change. It works perfect for me see what you think. Here is the code:
function doSlide()
{
$('#sidepanel').toggleClass("hidesidepanel showsidepanel", 1000);
$('#maincontent').toggleClass("show maincontent hidemaincontent", 1000);
$('#openmenu').toggleClass("openmenuleft openmenuright", 1000);
}

Ajax state history in coldfusion page

I'm confused as to how to accomplish this. I have a page which, has a popup filter, which has some input elements and an "Apply" button (not a submit). When the button is clicked, two jquery .get() calls are made, which load a graph, a DataTables grid, photos, and miscellaneous info into four separate tabs. Inside the graph, if one clicks on a particular element, the user is taken to another page where the data is drilled down to a finer level. All this works well.
The problem is if the user decides to go back to the original page, but with the ajax generated graph/grid/photos etc. Originally I thought that I would store a session variable with the filter variables used to form the original query, and on returning to the page, if the session var was found, the original ajax call would be made again, re-populating the tabs.
The problem that I find with this method is that Coldfusion doesn't recognize that the session variable has been set when returning to the page using the browser's back button. If I dump out the session var at both the original and the second page, I can see the newly set var at the second page, and I can see it if I go to the original page through the navigation menu, but NOT if I use the back button.
SO.... from reading posts on here about ajax browser history plugins, it seems that there are various jquery plugins which help with this, including BBQ. The problem that I see with this approach is that it requires the use of anchor elements to trigger it, and then modifies the query string using the anchors' href attributes. I suppose that I could modify the page to include a hidden anchor.
My question, at long last is: is an ajax history plugin like BBQ the best way to accomplish this, or is there a way to make Coldfusion see the newly created session var when returning to the page via the back button? Or, should I consider re-architecting the page so that the ajax calls are replaced by a form submission back to the page instead?
Thanks in advance, as always.
EDIT: some code to help clarify things:
Here's the button that makes the original ajax calls:
<button id="applyFilter">APPLY</button>
and part of the js called on #applyFilter, wrapped in $(document).ready():
$('#applyFilter').click(function(){
// fill in the Photos tab
$.get('tracking/listPhotos.cfm',
{
id: id,
randParam: Math.random()
},
function(response){
$('#tabs-photos').html(response);
}
);
});
Finally, when the user calls the drill-down on the ajax generated graph, it uses the MaintAction form which has been populated with the needed variables:
function DrillDown() {
//get the necessary variables and populate the form inputs
document.MaintAction.action = "index.cfm?file=somepage.cfm&Config=someConfig";
document.MaintAction.submit();
}
and that takes us to the new page, from which we'd like to return to the first page but with the ajax-loaded photos.
The best bet is to use the BBQ method. For this, you don't have to actually include the anchor tags in your page; in fact, doing so would cause problems. This page: http://ajaxpatterns.org/Unique_URLs explains how the underlying process works. I'm sure a jQuery plugin would make the actual implementation much easier.
Regarding your other question, about how this could be done with session variables - I've actually done something similar to that, prior to learning about the BBQ method. This was specifically to save the state of a jqGrid component, but it could be easily changed to support any particular Ajax state. Basically, what I did was keep a session variable around for each instance of each component that stored the last parameters passed to the server via AJAX requests. Then, on the client side, the first thing I did was run a synchronous XHR request back to the server to fetch the state from that session variable. Using the callback method for that synchronous request, I then set up the components on my page using those saved parameters. This worked for me, but if I had to do it again I would definitely go with the BBQ method because it is much simpler to deal with and also allows more than one level of history.
Some example code based on your update:
$('#applyFilter').click(function(){
var id = $("#filterid").val(); // assumes the below id value is stored in some input on the page with the id "filterid"
// fill in the Photos tab
$.get('tracking/listPhotos.cfm',
{
id: id // I'm assuming this is what you need to remember when the page is returned to via a back-button...
//randParam: Math.random() - I assume this is to prevent caching? See below
},
function(response){
$('#tabs-photos').html(response);
}
);
});
/* fixes stupid caching behavior, primarily in IE */
$.ajaxSetup({ cache: false });
$.ajax({
async: false,
url: 'tracking/listPhotosSessionKeeper.cfm',
success: function (data, textStatus, XMLHttpRequest)
{
if (data.length)
{
$("#filterid").val(data);
$('#applyFilter').trigger('click');
}
}
});
This is what you need on the client-side to fetch the state of the photo list. On the server side, you'll need to add this modification to tracking/listPhotos.cfm:
<cfset session.lastUsedPhotoFilterID = URL.id>
And add this new one-line file, tracking/listPhotosSessionKeeper.cfm:
<cfif IsDefined("session.lastUsedPhotoFilterID")><cfoutput>#session.lastUsedPhotoFilterID#</cfoutput></cfif>
Together these changes will keep track of the last ID used by the user, and will load it up each time the page is rendered (whether via a back button, or simply by the user revisiting the page).

How can I add a URL parameter but hide others in a POST - Spring MVC

I'm trying to add a URL parameter within a Spring MVC application. It's a basic search page that shows results.
In the search page, there is a form that is set to POST. There are many hidden fields and other fields I don't want in the URL. So, I don't want to do a GET.
I do want the search query in the URL. So after clicking the search button, the resulting search results page needs to have a URL like /search?query=hello
To get it to work, I'm creating a RequestMapping method in the Spring MVC Controller and doing a redirect: tacking on the query parameter. However, I'm not sure using a redirect is the best answer, seems there could be performance concerns redirecting as well.
I looked around and noticed folks using javascript and the location object, but setting the location object obviously relaunches the URL you set it to. I also looked at the HTTPServletResponse & HTTPServletRequest objects, but couldn't find much.
Any thoughts on how I can force the search parameter to be added to the URL?
Your form will have an 'action' specified telling it where to POST to. I'd have thought you could attach an onclick event to your submit button (or an onsubmit event to your form) that updates the action url by appending "?query=" to it.
document.<form name>.action += "?query=...";
Then you just have to worry about someone posting your form without JavaScript enabled - in this case you could fall back to your redirect.
I don't know how the server technology so I can't say if it will be happy giving you both GET and POST parameters, if not you'll have to manually strip the GETs out of the URL.
But anyway, this seems like a rather odd situation to be in - is it really that big a deal to show the parameters in the URL? Anything that gets posted by an HTML form can still be inspected with the right tools, it's just ever so slightly more difficult.
I wanted to provide a more complete answer to my question with code. The previous user helped me down this path, so I'll keep it as the accepted answer. However, there is one item to note:
If you add on to the action, and you have an input text box with the same name, the page posts a duplicate value like: query=hello,hello.
So, I needed to remove the name on the input box, and use the following javascript. Note, I am using the prototype.js framework:
Event.observe(window, 'load', function(event) {
Event.observe('searchForm', 'submit', function(event) {
$('searchForm').action += "?query="+$('searchBox').value;
});

jqGrid. add dialog

I have jqGrid with some columns, I want to add additional fields in Add dialog, that not displaying in grid, but sending in request. How i can make this functional?
You can modify Add dialog inside of beforeShowForm event handler. You can see a working example here. This example I made as an answer to the question "jqGrid: Disable form fields when editing" (see also a close question "How to add a simple text label in a jqGrid form?")
UPDATED: I reread your question and could see that I answered originally on another question as you asked. What you need is just usage of editData parameter which can be for example like
$("#list").jqGrid('navGrid','#pager',{del:false,search:false,refresh:false},
{}, // edit parameters
{ // add parameters
url: '/myAddUrl',
editData: {
someStaticParameter: "Bla Bla",
myDynamicParameter: function() {
return (new Date()).toString();
}
}
}
);
see demo. The demo has nothing on the server side, but you can easy verify with Fiddler or Firebug, that the data sent to the the server contain someStaticParameter and myDynamicParameter parameters.
This one is good. I'm voting this one up.
This solution applies to what I'm looking for. I have a users table with the typical username, password, and etc details. I have an edit and add button as well.
Security-wise, it's not good to send all the users along with their passwords. So in the edit form, an admin can only edit everything except the password.
In the add form, an admin can create a new account with a new password. Since the password field doesn't exist in the grid, it will not show in the add form. By following this example, I'm able to add a custom field without exposing my users passwords. Thanks a lot Oleg

Resources