A brief question about JavaScript or AJAX - javascript

I have been finding ways around this for a long time but think it's time I addressed it.
If I have a page that has a dropdown menu, is there anyway I can select a value which will subsequently load other values further down.
Can this be done without a page reload?
I will give you an example.
Say I was making some tools for an admin panel, but first of all they needed to select a member to work with.
They would select the member and then below, the fields about that member would be populated based on what was selected in the first menu.
As I have already asked, can this be done without a page reload?
Thanks for reading.

Yes it can be done without AJAX. When the page is rendered pass all the collections that will be used by the dropdown lists as JSON objects into the HTML:
var collection = [{ id: 1, name: 'John' }, { id: 2, name: 'Smith' }];
...
Then register for the change event of the first drop down and based on the selected value go and fetch the data from the other collections. Of course if you have lots of data this might not be practical as your pages will become very large and in this case AJAX woulld be more appropriate.

Answer YES it can be done.
Firstly you'll need an event, in this case you need to take action on the onChange event for the selectBox. So when an item changes you run a function.
Now you have 2 choices. You can do this using AJAX or NOT, it really depends on the complexity / security of your application.
In the following I refer to
Users : those using the application
Hidden Client Side Data : Data sent to the client during page load, but not visible to all users, however using view source, or downloading JS files, the Data is not secured.
Method 1 - NO AJAX
Basics: You send all the possible display options down initially when the page is first loaded, but display only the sections relevant to the user during selectbox onchange events.
Recommended when: No security condiderations if hidden client side data is detected (or won't be detected, or you simply trust your audience to use the app in the intended manner). Lastly when your total view permutations are low.
Method 2 - AJAX
Basics: You send down initially only the page skeleton, when the user changes the value of the select box, you then do an AJAX request to the server - grab the new view info thats relevant to that user, send it back down to a script which will inject that user data into the DOM.
Recommended when: You have a public site, or a site where security is a consideration. Where you have lots of view permutations or want more customizations per user than in scenario 1.
As you see both methods do not require a repost - method 1 ships everything upfront, method 2 uses AJAX to fill in data when required. Both methods are valid depending on your requirement.

Yes. Ajax is mainly used for that i.e. (without a page reload)
You have to use following step to achieve
Create a link and call a JavaScript function on it's onchange function
In the JavaScript function you have to call Ajax request.
Update the div in your ajax response.

Related

How can a web page find what value to POST?

I'm currently making an application for a client to automatically fill some web forms on the website he uses to store his item pricing. The website doesn't have a documented public API, and there doesn't seem to be a way to add bulk pricing on the website itself. In order to accomplish this, I'm making a simple python application that reads his data, then sends POSTs to the website.
Their website is giving me a hard time, however, because it's sending payloads containing dozens of fields, while the form used to enter the pricing information only has 4 input fields. On top of that, their website uses angularjs to generate most of the web page, so I can't just find the <form>[...]</form> block and look at what's being sent, because that's not what they use.
Here is what the payload json looks like:
{
"entities":
[
{
"Price_Line_ID":"{}",
"Price_List_ID":"{}",
"Item_ID":"{}",
"Uofm_ID":"{}",
"Amount":"{}",
"Dtstamp":"{}",
"Tenant_ID":"{}",
"Created_On":"null",
"Created_By":"null",
"Changed_On":"null",
"Changed_By":"null",
"Seq":"0",
"Begin_Qty":"0",
"End_Qty":"0",
"Customer_ID":"null",
"Tax_Before_Discount":"false",
"Discount_Target":"All",
"Max_Discount_Amount":"null",
"Min_Discount_Amount":"null",
"Customer_Name":"null",
"Uofm":"null",
"Item_Number":"null",
"Uofm_Schedule_ID":"null",
"Uofm_Schedule":"null",
"Inactive":"false",
"entityAspect":
{
"entityTypeName":"PriceLine:#SalesPad.Spo.Api.Model",
"defaultResourceName":"PriceLines",
"entityState":"Added",
"originalValuesMap":
{},
"autoGeneratedKey":
{
"propertyName":"Price_Line_ID",
"autoGeneratedKeyType":"Identity"
}
}
}
],
"saveOptions":
{}
}
The 7 values at the top (with values of "{}") are found when I do a GET or POST action on the website's other pages. I've managed to find where all the values originate from, except the "Price_Line_ID" one, because it appears to change from page to page (and it changes after a price is added).
I know a web page can get the data needed for a POST event either in its own html (when using tags like <form>), and it can get them from other GET and POST events. Is there any other way for a web page to determine a value that will be sent in a POST event?
I'm not very familiar with angularjs, although from what I understand it only creates a bunch of Javascript for the page. Does it offer different ways of determining what values are sent in a POST or GET event?
Edit: I've already tracked all responses from GET and POST events from logging-in to adding a price, the Price_Line_ID field changes from page to page, and adding the price appears to use an ID different to the one received in the GET event. I just want to know the different ways that a web page (specifically one using angularjs might use to determine the value of the data sent in POST events.

AJAX: dynamically change contents of second page

I am attempting to change contents of a second page depending on changes in another page. Simply put i have an image display page - #1 and an information display page - #2.
Page #1 displays an image depending on a get variable which i acquire with javascript function and another function sends it off to a php page with an XMLHTTPRequest and handles it.
Now my question is do I need to use a Database table to store the variable and then create another PHP script acting as a listener from the database and if the variable changes send it off to Page #2 with the display information or is there a simpler way?
In simpler terms - The get variable is set to 1 -> display picture 1 AND show information related to product 1 on PAGE #2. Then get variable set to 2, then 3 and so on...
Thank you!
4 options:
1 - You have a PHP website and go ahead as you describe:
Just reuse the parameter received by the first page (www.mysite.com/page1.php?id=1) to load the second one. Your script can take the parameter and modify the link for the second page so that you have www.mysite.com/page2.php?id=1 and on page 2 you know how to get your parameter and use it.
2 - You have a PHP website but you can make things a lot simpler:
The link www.mysite.com/page1.php?id=1 makes your PHP code to intercept the parameter directly so that you load your content directly there and make the link for the second page (www.mysite.com/page2.php?id=1) from the server or PHP and this is sent to the client directly. You don't need so much JavaScript and AJAX, your second page is a PHP page again, so you load everything from the server again. It's the most common way. I hope you don't have any obstacles with this method.
3 - You have a single page application in JavaScript:
If your JavaScript gets the id, just keep the value in a variable and the "second page" would access this variable too.
4 - If your second page is already open and you want it to update when the first one gets modified, YES you need to keep the variable on your server and why not a database.
And you need ajax repetitively called with setInterval() (or maybe better with setTimeout() ) to get the variable from a PHP script that will query your database.
I would not advise you to make your second page to refresh, it is unpleasant for the user.
There are potentially some other cases if you have other restrictions. Don't hesitate to ask for some details if something is not clear.

Javascript control page and user view page

Currently I'm working on a project where a user enters a lot of data constantly for a hour long window. I'm looking to have one user control all the data via some control panel and then have a link they can distribute to other users that will allow them to view that data without the ability to edit it.
Right now I'm doing some extremely weird methods. I have an XHR request on the control page that fires whenever a field is finished being edited. From there the data is sent to a php file that converts the data into a simple text file. Then the distributed link file will load that file one time and translate it into the necessary format.
Some potential problems I've run into are it seems odd that I'm sending starting as javascript data then going to a php file then to a text file then translating the data all the way back into javascript data again. Another problem I've come into is I'm not sure of a way to force users to reload the page when a field is edited in the control panel after the user has opened the view page.
Have I totally gone overboard here? What are some better concepts I could employ to accomplish this task?
If i understand what you want to do this is how i will do this:
First the data entry
if you have lot of fields you better use a form wizard, i don't have a particular one in mind right now but there is lot of them just search jQuery Form wizard
Here is an example:
http://i.stack.imgur.com/Luk2b.jpg
The concept of the form wizard is to guide user via multiple page and also validate the data. And click save when and the end.
Then save date in database.
Display content
All you need to do is to create a global separate page to display your content.
Let see something like: http://yourserver.com/view/{id}
where id is the identifier of the particular row in your database.
i'm not sure if i totally understand what u about to do. i'm trying to make your work description shorter here:
want to build a website that one person can edit a single page's content in 1 hour, and others can view the content change in that 1 hour.
if this is what u want to build, here's the module:
teacher: the one who can edit the page
student: the one who can only view the page
server: information center
teacher client edits page -> teacher client sends update data to server -> server saves data -> server sends update notice to student client -> student client receives update notice -> student fetches update data from server
to make this module work well, i suggest try socket instead of http reqeust, just like online games or IMs do.
well, try socket.io

MVC3, switching between Views in the same page

I am working on a MVC project that is supposed to have one page only, with two zones. On one zone I have a Google Map with markers, and the second zone is populated with the selected marker's details.
The details view has a button that when clicked should change the entire view into edit mode without refreshing the page or redirecting it. I have used two views, for details and edit and with the help of ajaxForm function I am switching back and forth between these two views. I'm adding the ajaxForm on documentready for edit view.
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#currentDiv').ajaxForm(function(data) {
$('#currentDiv').html(data);
});
});
</script>
The problem appears when on server-side an error appears while trying to save data from edit view and I want to return to the same edit view with the errors displayed. The ajaxForm handler is not added any more and even if the new values that will try to be saved are ok, the detail view is loaded in another page.
Unfortunately, the use of ajaxForm creates some other problems because I don't have control over the cases when the ajax call fails.
Any ideas on how could I fix this? Is it some other solution to switch between those two views without using ajaxForm and without refreshing the page?
I think there are a couple of different questions that you are asking.
First off, you add jquery handlers to deal with the case when you get a 500 type error from the server.
Something like the following. I suggest taking a look at the docs for more info.
$(document).ajaxError(function(event,jqXHR,ajaxSettings,thrownError){
if (jqXHR.status != 0){
window.location = <error page>
}
}
The second problem seems to stem around error handling of known errors (say invalid input). In this case I suggest the following workflow.
1) User clicks on edit button, taken to edit screen
2) User enters in data, use client side validation to do initial check
3) User submits, user is then taken to the view screen and is shown a
success or error message.
The server response could look like:
public ActionResult Edit(EditModel model){
if (!ModelState.IsValid)
{
return Json(new {successful = false, message = "Failed.."});
}
...
}
On the client side, your form callback should now handle the message and the fact it was successful or not. In my implementation, I used knockoutjs to create a "message" area that I could update and clear. (I created templates, etc).
Remember to use client side validation for the easy field validation stuff.... This will save a trip back to the server.
Yours could be quite simple, by popping up the message returned from the server.
Lastly, document ready only fires when the original document is done loading, never again for an ajax call (at least that is my understanding). Just put that code that is the document.ready at the bottom of the edit page. It will fire after the html it is targeting has already been rendered.
Hope that helps!
I have begun to move away from the asp.net views available in ASP.Net MVC due to some incompatibilities and/or unnecessary complexities when trying to achieve functionalities expected of AJAX enabled sites of the day.
I would recommend moving towards a design where you use "dumb" HTML files, use jQuery to download them using AJAX and drop them into a container (personally I use a div) and then use another AJAX call to gather the data from a controller. There are a number of advantages to this approach:
It establishes a real (not fake) separation between client side and server side code.
Html files can be cached on the client cutting down on the amount of data transmitted.
Binding of the Html elements becomes a client side task achieved using jQuery offloading processing cycles from the server.
Controllers essentially become collections of web methods which means they can be untilized by iPhone and Android apps making mobile deployment easier.
I realize this probably isn't the exact answer you're looking for and this may not be an option for you but my hope is that it will help someone at some point make a decision to move away from mixing HTML and server side code.

Shall I use javascript for page submission?

I am working on a big site, and in the site there is a search module. Searching is done by using a a lot of user submitted values, so in pagination I must pass all these data to the next page, appending the values to url make the url very big.
Sso how can I solve this issue? I am planning to use a javascript based page submission (POST) with all the values in hidden fields to the next page the read all the values from the next page.
Will it cause any problems? Or should I use database to keep the search criterias?
I would create a server side object, possibly with a database backend which is updated by the different pages.
It is at my opinion the most clear and easy solution. Giving parameters from page to page, either by post or javascript or cookie will work too but it's more of a quirk in my experience.
Also if a search query is so complex that it needs multiple pages to create it, it might be helpfull for the user to have all the data stored on the server so he can change it more easily by switching back and forth between the different pages.
I would store all the search criterias in some kind of session-store on the server when the initial search is being triggered.
For pagination I would retrieve the criterias from the session-store and then just show the appropriate results. Also I would append some kind of key to the pagination links (so this would be the only hidden post-field) under which the search criterieas can be found.
Even though the session is per user, you might have several search windows open within the same session, and you don't want to mess them up with the pagination.
In order to make a reliable search with pagination, we need to do a bit more than normal.
We need to handle the following cases.
Once search is done, user may choose to do browser back and forward. Here, if you are doing form submission on every page, it would be an overload. Also, if user presses browser refresh button, it will unnecessarily warn him that data is being submitted.
Searching on a large database with lots of criteria is costly. Hence, optimization is important.
So you should NOT do the following:
Submit data on every page change
Not store data in cookie. (This is not secure and not even reliable.)
For large database with complex query, cache the result in session.
In case, you need very up-to-date and real-time result, ignore point (3) and try doing partial search for every page.
Thus, for your case, you can do the following:
When user searches first time, make the form POST data to a search page.
This search page will store the search query in session and generate a unique id for it.
Now render the result page. The result page will be passed the search id (generated in point 2) and the page number. Example result.aspx?searchId=5372947645&page=2
The result page will puck up the query from session using the searchId and then provide result based on the page number sent.
Using hidden fields and POST method should be fine too unless you are able to get them on the next page right.
To supplement Sarfraz's answer...
It's not necessary to use Javascript to make a POST.
<form action="destination_url" method="POST">
...
</form>

Categories