Pass Data from one jsp page to another jsp page - javascript

I have two pages (page1.jsp and page2.jsp). in page1.jsp i retrieve some values from database and display hyperlinks corresponding to those values. Now what i want is when i click any of those hyperlinks, in page2.jsp i should display other fields coressponding to the vlaue from the database. So what i essentially want is when a link is clicked the associated value must be passed to page2.jsp where i query the database to retrieve other fields.

when a link is clicked the associated value must be passed to page2.jsp where i query the database to retrieve other fields
So, you want to preprocess the HTTP request before displaying the JSP? For that you need a servlet.
Assuming that the links in page1.jsp are displayed like follows:
<ul>
<c:forEach items="${ids}" var="id">
<li>View data for ID ${id}</li>
</c:forEach>
</ul>
Then you will be able to preprocess the HTTP request in the doGet() method of a HttpServlet which is listening on an <url-pattern> of /page2:
Long id = Long.valueOf(request.getParameter("id"));
Data data = dataDAO.find(id);
request.setAttribute("data", data); // Will be available as ${data} in JSP.
request.getRequestDispatcher("/WEB-INF/page2.jsp").forward(request, response);
In page2.jsp you will be able to access the data as follows:
<p>The data for ID ${param.id} is:</p>
<p>Field 1: ${data.field1}</p>
<p>Field 2: ${data.field2}</p>
See also:
All about Servlets - contains Hello World example and useful links

You can do that by either passing GET or POST variables to the corresponding jsp page and reading them using jsp:
using GET method:
link
If you want to do this dynamically you will have to add to that on click using javascript:
GET using jQuery js library:
<script>
$(document).ready(function(){
$('#mylink').click(function(){
$(this).attr('href', $(this).attr('href')+'?datatobesend=value');
});
});
</script>
link
There are many ways to use GET/POST to send data from one page to another, this is just as quick as I could write one up :-) Using form submissions are another place you should look into if this way doesn't work out for you.

lIf you are talking about a variable that can't be serialized as a string and passed as an http parameter, as suggested, then you need to store the variable within the session.
--page1.asp
<?
session.setAttribute( "val", record );
?>
--page2.asp
<?
//Cast this to your type
Object record = session.getAttribute("val");
// Clean it up now that you're done
session.removeAttribute( "val" )
?>

Related

Whats the proper way to highlight the text input fields if i make changes to it . I am populating the form if there is param( in form ofid) in url

Working on VueJS.
<template>
<v-text-fields v-model="a">
</template>
<script>
export default class SampleClass extends Vue{
a = null;
async mounted(){
if (this.$route.params.id) {
this.a= populatesFunction();
} }
</script>
In above code say i have a form to fill the data and call the api when i click a certain button which will save the data.
But say there is conditional check which look for parameter in url in my case id of the saved entries and if the condition is true then i call a function which perform GET request and retrieve the saved entry and use the retrieved data to populate the fields .
In other sense i can edit already saved data.
What i wanted to achieve is to highlight text-fields if there is any kind of change is made(id as param in url). I don't want to highlight text field if i am creating a new entry.

Populate Select element with Jquery and AJAX and without async:false attribute

I am trying to populate a select element from database, I need to pass some variable from my Jquery script first (id of a button). For this purpose I used AJAX call and passed variables to PHP file, made SQL query, fetched data... Everything turned out to be fine... but when I created html code and then passed from PHP to AJAX. The Jquery variable html was not taking any data from AJAX call... Then I read about using async:false attribute within AJAX call.. But I know it is not a good solution... I am new to web development.. I want you to suggest me what should I do...
Example of my code is as below
'''
<span id="span_product_details"></span>
<script type="text/javascript">
$(document).ready(function(){
var v1=1; //actually id of a button will be saved in this variable which is necessary to make database query
var v2=2;
var v3=3;
var html='';
html += '<select name="abc" id="abc" class="form-control selectpicker" data-live-search="true" required>';
$.ajax({
url:"practice.php",
method:"POST",
data:{v1:v1,v2:v3,v3:v3},
dataType:"html",
success:function(data)
{
html += data;
}
});
html += '</select>';
$('#span_product_details').append(html);
$('.selectpicker').selectpicker();
});
</script>
<?php
//example code of practice.php file (a seperate file)
//$query = (based on $_POST['v1'], $_POST['v2'] and $_POST['v3'])
$str='<option value="1">Hello</option>'; //data obtained from database
$str.='<option value="2">Hi</option>'; //data obtained from database
echo $str;
?>
'''
For more detailed understanding I am explaining the problem with more details..
I have a table each row of that table has 4 columns,
ProcessID, ProcessDate, Edit_btn, Delete_btn
during each process multiple parts were processed lets say part No. A1, A2, A3
ID of Edit button is also same as ProcessID.
Now When Edit button is pressed, a modal will open, an AJAX call is performed and that modal shows
rows with data as follows,
(select element with Part number) (part status accepted, rejected etc) (remarks)
Now while Editing user must be able to add more parts to the same process... For this purpose there is an (Add button)
With first row of modal,
Now When Add button is pressed, a new row will be added to the modal,
that row must have a select element which should be populated with a list of already processed parts
and parts which were not processed...
For this purpose I had to make an AJAX call, which will pass the EDIT_BTN id (to fetch already processed parts under this.processID)
to php file,
And get the options for select element. During this operation I am having the above stated issues...
One way is to use async:false which will work.
the other way is to append basic html first, the load data
or you can just write your select html in modal and on modal show event, load data,
p.s. data v1,v2,v3 you use it your way, i just outlined the solution,
$(document).ready(function(){
var v1=1; //actually id of a button will be saved in this variable which is necessary to make database query
var v2=2;
var v3=3;
var html='';
html += '<select name="abc" id="abc" class="form-control selectpicker" data-live-search="true" required>';
html += '</select>';
$('#span_product_details').append(html);
load_dropdown(v1,v2,v3);
}
// use v1,v2,v3 however you have, either in function or global, param, or any other way
function load_dropdown(v1,v2,v3) {
$.ajax({
url:"practice.php",
method:"POST",
data:{v1:v1,v2:v3,v3:v3},
success:function(data)
{
console.log(data); // if in console it display html then fine,else check format
$('#abc').append(data); // or use .selectpicker as selector if its unique
$('.selectpicker').selectpicker();
}
});
}

How do I pass Javascript variables from my html template page to a Django views function?

I am working on a Django environment.
I have created a form in my html page which contains a textbox for input for a label like "Enter your name" .
I have a submit button below the textbox.
I need to pass the inputted name to the button as a value and then this button value is to be passed to a python function in views.py.
Can anyone help me with this ?
To do this you need to use Ajax, its like calling a url in the background without affecting the user. but first to call a a url(view) we need a url and a view. so i will think you have something like this
url('^click/btn/(?P<data>[0-9]+)', views.click_btn, name="btn_click");
and the view
def click_btn(request, data):
# do whatever you want with the data....
return HttpResponse('Done')
now to call this from the fron-end we will use jQuery.ajax
first you have the button
<button id="btn_click">Click me!</button>
now create a script tag and type the following
the script tag must be after the button so he can see it
<!-- if you haven't included jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
// get your input value...
var data = $('#my_input').val();
$.ajax({
url: `/click/btn/${data}`,
success: function (res) {
// every code in this function will execute when Ajax call the url
alert(`Nice! you called the url and get this data: ${res}`)
}
});
</script>

Passing Javascript variable to route in laravel 5.3

I'm having a Laravel blade form which includes a table wihch displays some data from the database. And when i click on a certain column i wrote a js function to catch that id of the certain selected item to a js variable "var selectedItem".
Now i wanna pass this js variable to the 'edit.item.blade' page and load the relevant record corresponding to this value.
My question is what is the best way to edit a selected item in laravel ? and is there anyway to pass this JS variable to a route at a button click event and load the 'edit.item.blade' using the relevant record to edit.
What you usually do in laravel is pass the id of the record you want to see in the url. Say you want to view the details of a report with the id of 1 you'd go to the url "/reports/1" which points to a show function in the reports controller.
Routes
In your routes/web.php you'd add:
Route::get('/reports/{report}',RecordController#show);
What this is does is take anything typed after /reports/ and pass it to the show function. So if you'd go to /reports/1 the route would pass 1 to the show function
Controller
In your controller you have to make a show function which accepts the variable passed by your route. You'd then take that variable to look up the corresponding record and pass it along to a view.
Which would look like this
public function show($id){
$report = Report::find($id); // Find the corresponding report
// Pass the report along to the view resources/views/reports/show.blade.php
return view('reports.show',compact($report));
}
Show view
In your show view you can now use $report to get any information from the report like $report->name, depending on your database.
Index
Now in the index view, the view you were talking about I presume, you loop over all records from some table. Since you haven't included any code in your post I'm just going to assume you loop over your data using a foreach loop. Using that loop we can give each record a link depending on their id.
Which would look a bit like this
<table>
<tr>
<td> Name </td>
<td> Edit </td>
</tr>
#foreach($reports as $report)
<tr>
<td> $report->name </td>
<td>Edit</td>
</tr>
#endforeach
</table>

How do I implement cascading dropdown using golang's templates

Scenario:
I have a cascade scenario, where values in second dropdown depends upon first. I have three templates "layout", "input" and "inner".
Attempt:
I'm making ajax call on change of first dropdown in "input" template and stuck with handling the response returned. Currently I found a way to fix it by replacing html of second dropdown. But, I think this is not the better way to handle. I want something in line of rendering templates where I do not need to amend html.
please help in acheiving the task in better way or point to some wiki. Only Standard Library
Thanks,
Layout.html:
http://play.golang.org/p/LikKy6rf3-
Input.html:
http://play.golang.org/p/wM7EpPdXuM
Inner.html:
http://play.golang.org/p/xFpInKZfFT
Main.go:
http://play.golang.org/p/cxtJU-Lhi1
On the higher level you have 2 options:
Either send all the values for the dropdown lists (e.g. as a tree) and change the values on the 2nd and 3rd level when the dropdown of a higher level changes (suitable for small lists, unsuitable for large dataset)
Or the one you chose: when selection changes, you make an AJAX call (triggered from onchange) and you populate the list from the results.
Elaborating #2: populating list from the AJAX call result
You also have 2 options to do this:
Either the AJAX call returns HTML call which you can simply use to replace the inner HTML of the HTML <select> tag.
Or the AJAX call may only return the data (e.g. encoded using JSON), and a Javascript code can build the content of the list.
AJAX returning HTML
The AJAX call may return the complete HTML code needed to be replaced as the inner HTML of the <select>. To achieve this at server side, you can create/separate the HTML template responsible only to generate the HTML code of this, for example:
{{define "innerList"}}
{{range .}}
<option value="{{.Key}}">{{.Text}}</option>
{{end}}
{{end}}
You can execute only this template like this:
// tmpl is the collection of your templates
values := ... // Load/construct the values
tmpl.ExecuteTemplate(w, "innerList", values)
Here values is a slice of the following structure:
type Pair struct {
Key string
Text string
}
Building <select> content with Javascript
The AJAX call may return a JSON datastructure, an array/list of value;text pairs from which you add the <option> child tags yourself.
To add an <option> to a <select> tag:
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.value = "1234";
option.text = "Kiwi";
x.add(option);
So basically what you need to do is remove current children of the <select>, iterate over the list received as the response and add a new <option> tag constructed from each.

Categories

Resources