Refreshing page without losing checkboxes information in cakephp - javascript

I'm developing a website with CakePhp.
I have a view to select some items on a list, via checkboxes in a form, and each item has a "more info" link which refreshes the page with additional information of this item.
The problem is that if I click any "more info" link, I obviously lose the data about what checkboxes were selected before. The only thing I come up with is updating $this->Session each time a checkbox is changed, but I need to trigger a function in a controller when this happens.
Is there any other solution?
I've been searching everywhere and I've found some things about Javascript and JQuery, but I have no idea of how to do it this way neither.
Thanks in advance.

If you don't mind sending all the text it's quite easy:
<div class='article'>
<div>short textmore info</div>
<div class="more hidden">long text</div>
</div>
jquery part
$(".article").on('click', '.morebtn', function(){
$(this).parents('.article').find('.more').removeClass('hidden');
});
css
.hidden { display: none }
Here is a fiddle
The better solution is to use ajax request. Also not that hard to implement.
Here is a fiddle showing the very basic request. You could use the full $ajax request too if you want need to do more advanced requests.
note that the example of the ajax request does not work due to invalid url. The url need to be from the same origin as the current page (same protocol, domain and port) to make it work. There are work arounds but that's a different issue

Read up on AJAX, it's a really cool technology which will make it very simple to do what you need. Outline:
When the button is clicked, the browser sends an AJAX request to the server for the text to display somewhere on the page.
When the response (some HTML fragment from the server) is received by the browser, a function is called which looks like so:
function(data) {
$('#description').html(data);
}
Doing AJAX requests is 5-10 lines of code (mostly configuration + building the URL).
The main work is on server side where you need to write a controller which provides the texts.
Since the page is never reloaded, there is no need to preserve the form values.
To learn AJAX, start with this tutorial.

Related

dynamically generate content for a page when clicking on product

everyone. I am making a website with t-shirts. I dynamically generate preview cards for products using a JSON file but I also need to generate content for an HTML file when clicking on the card. So, when I click on it, a new HTML page opens like product.html?product_id=id. I do not understand how to check for id or this part ?prodcut_id=id, and based on id it generates content for the page. Can anyone please link some guides or good solutions, I don't understand anything :(.
It sounds like you want the user's browser to ask the server to load a particular page based on the value of a variable called product_id.
The way a browser talks to a server is an HTTP Request, about which you can learn all the basics on javascipt.info and/or MDN.
The ?product_id=id is called the 'query' part of the URL, about which you can learn more on MDN and Wikipedia.
A request that gets a page with this kind of URL from the server is usually a GET request, which is simpler and requires less security than the more common and versatile POST request type.
You may notice some of the resources talking about AJAX requests (which are used to update part of the current page without reloading the whole thing), but you won't need to worry about this since you're just trying to have the browser navigate to a new page.
Your server needs to have some code to handle any such requests, basically saying:
"If anybody sends an HTTP GET request here, look at the value of the product_id variable and compare it to my available HTML files. If there's a match, send a response with the matching file, and if there's no match, send a page that says 'Error 404'."
That's the quick overview anyway. The resources will tell you much more about the details.
There are some solutions, how you can get the parameters from the url:
Get ID from URL with jQuery
It would also makes sense to understand what is a REST Api and how to build a own one, because i think you dont have a backend at the moment.
Here some refs:
https://www.conceptatech.com/blog/difference-front-end-back-end-development
https://www.tutorialspoint.com/nodejs/nodejs_restful_api.htm

IsPostBack sometimes doesn't work in asp.net webforms [duplicate]

The best explanation I've found for a postBack is from Wiki.
a postback is an HTTP POST to the same page that the form is on.
While the article does explain how a second page was needed in ASP, but no longer needed in ASP.NET, it doesn't give much detail or background. I am looking for a freakin' tome of information on PostBacks. Much like the simple question of "how can I clean a house" can be addressed by this 900 page book. I don't need 900 pages worth, but details please. I found a nice little tutorial for ASP.NET life cycle, but it seriously glosses over postbacks (amongst other things).
I am looking to the developers who have been around before .NET and really don't take these kinds of things for granted. Books and hyperlinks are reasonable answers or additions to your answer.
So far I've seen the right answer alluded to repeatedly, and almost everyone has come shy of what I consider subjectively to be the mark.
Let's start with the basics:
An HTTP request can be any of the HTTP verbs, but the two that people use most are GET and POST. Well, those are the two a programmer uses most frequently. The others all have some purpose, if they're implemented on the server. When you send information to the server, you can do so either through the use of the URL (to request a page) or within the body of the request (POST, PUT, DELETE, for instance).
Now you'll remark (I'm sure) that the URL in a GET request often contains data, and this is true, but according to W3C, you should not use GET to alter state, and yet we do often. It's sort of a hack that we all agree is an actual use, and not a hack. Whether that makes it a hack or an actual implementation detail I leave up to you.
So when you send the body of the POST (skipping the others for now, you can figure it out from here) with the form elements, you're sending back certain elements. How those elements are defined is up to you and to the environment you're working in. You could post to a server with a JSON element in the body, or with XML, or with form fields. Generally we do posts from a FORM element in the body of the HTML.
Now everyone says, "oh, a postback is a subsequent request to a page." But, that's not true. A postback is when you send data via POST -> back to the server. I say this because the difference between a GET request and a POST request is if data is included in the body (and the verb used, but the client usually knows how to deal with that). You could postback to the page on the first time the page is visited, and in fact ASP.NET has tools for doing that in the library. You could certainly have a desktop client POST data to a server (think Twitter) without showing any webpage at all from the server (ok, so twitter is probably not the best concept to use for an example here, but I want to illustrate that you can use a client that doesn't show the webpage, so no request is necessary).
So really what you should read there in "postback" is "I'm POSTing data BACK to the server for processing". It's presumed that you retrieved the page initially with a GET to show the user the <form> element that has <input> fields for them to interact with, and that at the end you're sending data back. But I hope you can see that it doesn't have to be in that order.
So here's something else to consider:
What if you gave the user a page with a bunch of <input>s and no <form> but instead, had a button wired up in javascript to concat all those <input>s with &value-n= and send them as a GET? Does the same thing, but violates that concept of only using GET for requests. (possibly) ensuing discussion encourages me to reinforce that GET should have no side effects (no updating values)
It's how come you can send someone a link to a google search, for instance. So we don't ALWAYS have to POST BACK to the server to get data.
Hope this helps.
Cheers
See ASP.NET Page Life Cycle Overview on MSDN for a good general introduction about what happens when a requests hits the server.
A PostBack is any request for a page that is not the first request. A PostBack will always be in response to a user action (triggered most commonly by a Button, AutoPostBack control or Ajax).
POSTBACK: Part of ASP.NET's contrived technique for hiding the true stateless nature of the web/HTTP behind a stateful facade. This results in complex code (IsPostback, ...), a hard to understand page lifecycle, many different events, ... and numerous problems (ViewState size, web-farm stickyness, state servers, browser warnings (not using PRG pattern), ...)
See ASP.NET MVC instead.
A post back is round trip from the client (Browser) to the server and then back to the client.
This enables you page to go through the asp engine on the server and any dynamic content to be updated.
here is a nice explanation
ASP.Net uses a new concept (well, new compared to asp... it's antiquated now) of ViewState to maintain the state of your asp.net controls. What does this mean? In a nutshell, if you type something into a textbox or select a dropdown from a dropdownlist, it will remember the values when you click on a button. Old asp would force you to write code to remember these values.
This is useful when if a user encounters an error. Instead of the programmer having to deal with remembering to re-populate each web control, the asp.net viewstate does this for you automatically. It's also useful because now the code behind can access the values of these controls on your asp.net web form with intellisense.
As for posting to the same page, yes, a "submit" button will post to an event handler on the code behind of the page. It's up to the event handler in the code behind to redirect to a different page if needs be (or serve up an error message to your page or whatever else you might need to do).
The Wikipedia definition of postback is pretty good, but I'd add the following:
A postback is a subsequent HTTP POST to the same page that the form is on.
If I have a page with a form on it and, rather than having my Submit button redirect the browser to another page that will process the form, instead have the Submit button refresh the current page (and perform some specific steps to validate/save the page, presumably), then that Submit button is said to have posted back to the current page.
Postbacks can be either full (refresh the entire page) or partial (in a case where AJAX is employed). A partial page postback will re-render only a part of the page (like a single drop-down list, a table, etc.).
In the old HTML, the only way to make something updated on the webpage is to resend a new webpage to the client browser. That's what ASP used to do, you have to do this thing call a "PostBack" to send an updated page to the client.
In ASP .NET, you don't have to resend the entire webpage. You can now use AJAX, or other ASP.NET controls such that you don't have to resend the entire webpage.
If you visit some old website, you would notice that once you click something, the entire page has to be refresh, this is the old ASP. In most of the modern website, you will notice your browser doesn't have to refresh the entire page, it only updates the part of the content that needs to be updated. For example, in Stackoverflow, you see the page update only the content, not the entire webpage.
Simply put this by a little code. Hope it is helpful to you.
When you firstly request the page url. you can view the source code of it in most browser. Below is a sample of it .
The essential of Post Back is actually call the __doPostBack which submit all the form data got from your firstly requested back to the server. (__EVENTTARGET contains the id of the control.)
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
NHibernate Demo
</title>
<script language="javascript" type="text/javascript">
function dopost() {
__doPostBack('LinkButton1', '');
}
</script>
</head>
<body>
<h1>NHibernate Demo</h1>
<form name="ctl01" method="post" action="Default.aspx" id="ctl01">
<div>
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTMxNzcwNTYyMWRkKHoXAC3dty39nROvcj1ZHqZ5FYY=" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['ctl01'];
if (!theForm) {
theForm = document.ctl01;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<div>
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="B2D7F301" />
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwKZx5vTCgKM54rGBgLM9PumD20dn9KQguomfpAOdTG0r9Psa7al" />
</div>
<a id="LinkButton1" href="javascript:__doPostBack('LinkButton1','')">LinkButton</a>
<input type="button" value="testPostBack" id="testpostback" onclick="dopost();" />
</form>
</body>
</html>
Postback is a request during which ASP restores values of controls' properties from view state.

Display form result in same page with only client-side script possible?

I have a bit of a tricky work problem I hope to get some help with.
To handle various forms and storing entries, we use an in-house tool which I cannot modify. Basically what happens is:
I enter he URL the original page, and the URL of the destination page after successful submission.
The tool spits out some HTML and Javascript code, the most important of which is a unique URL, let's call it (redactedURL), that goes after the action attribute.
When the form is submitted, the page will refresh to one of two possible destination URLs: the one I inputted if success, or (redactedURL) if error.
I can download all the entries from the tool afterward.
The HTML is quite simple. checkform() is a simple validation script.
<form action="(redactedURL)" name="enenForm" method="POST" onSubmit="return checkForm()">
The issue with this is that I can't style the (redactedURL) error page, which is quite ugly. I am wondering if there is anyway I could
Suspend automatic display results of form submission
Determine the destination URL, and based on that, write out a custom thank you/error message (since I cannot access the server-side script, this seems to be the only solution to determine if the submission is successful or not).
Make sure that tool still properly stores all the entries.
Any help would be much appreciated. Thanks!
Don't use a form. Instead use AJAX. I think this SO Question will provide a start. Basically you use JavaScript to submit data to a server using XMLHttpRequest. The returned HTML is a string which you could either modify or (better yet) normalize and add to the DOM.
For an advanced example jQuery-Mobile does this concept when you click a link instead it gets the HTML from the server as an AJAX request copies the HTML inside the <body> and inserts it into the DOM.
Search for tutorials about AJAX and jQuery (or your prefered JS library). Like this one.

Handling ajax URLs from different pages?

So I have my site at http://example.com/foo/ (under a directory, the main domain is for something else).
Using .htaccess, I've set up my pages so the URLs look like http://example.com/foo/about/, http://example.com/foo/polls/, http://example.com/foo/registration/, etc. This works great and the site loads fine and can be traversed without any Javascript issues.
Now, I'd like to add some AJAX functionality to the navigation. If I'm on http://example.com/foo/ and I click the navigation for "About", it changes the URL to http://example.com/foo/#about and dynamically loads the about page in one section of the site. I also have this working.
I have two problems which involve handling switching between AJAX and non-AJAX URLs.
If I'm on http://example.com/foo/about/ and I click on polls, it would look like http://example.com/foo/about/#polls which doesn't look very pretty. Ideally, I'd want every AJAX URL to be formatted with just the main directory and a hash, like http://example.com/foo/#about.
Should I handle it by forcing an actual (non-AJAX) redirect to the index page with a hash symbol then load it from there?
The other problem is the reverse. If I send http://example.com/foo/#about to someone who has Javascript disabled, or maybe if someone links to it and a bot crawls that link, is there any way to handle that to redirect to the correct non-AJAX page or is this just an unfortunate fact of life I'll have to deal with?
If you need non-javascript support, I'd change all your urls directly to the pages. Like http://example.com/foo/#about to http://example.com/foo/about/
Then, the javascript can intercept it, call event.preventDefault(), and 'redirect' it to #about, which will follow your ajax functionality.
If the client doesn't have javascript, it will go to http://example.com/foo/about/ as normal.
As for being on http://example.com/foo/about/, a javascript client should never get here as they will always be redirected to hashtags.
1) if you redirect to the main page and then use ajax to load the about page that would just not make much sense. what you should do is make everything work through ajax : there should never be a http://example.com/foo/about/ in the first place only http://example.com/foo/#about then you just update the hash and the content when you click on polls.
2) there is no way to avoid, sorry.

jQuery get page with use of #/page

Hello I have a question recently I seen more and more sites using #/pagename instead of going to /pagename which is useful because it does not reload the page.
How can I do the same thing with jQuery? http://mysite.com/id#/1 <-- would load user with id 1 if you would change that 1 to say 4564 http://mysite.com/id#/4564 the page would load user data fro 4564 with out refreshing the page it self.
Thanks in advance
You are actually seeing two things:
The request for content is be done asynchronously (AJAX). To accomplish this look at jQuery.Ajax. http://api.jquery.com/jQuery.ajax/
There is also a 'hash trick' to enable back button support. Typically, a standard Ajax call does not play well with the back button. For this look into the BBQ jQuery library. http://benalman.com/projects/jquery-bbq-plugin/
Hope this helps.
Bob
YOU are looking for the jQuery history plugin. I've had great success with it, and there are triggers for when the hash changes so you can do whatever you want: load content with AJAX, or load a different slide, etc.
I would recommend you look at sammy.
It's a very light javascript framework intended to implement a thin-server model like this where the rendering occurs on the client's computer in javascript instead of served pages from a remote server. This is what allows many sites to avoid doing full reloads of a page every time a user performs an action.

Categories