Passing a variable from jsp page to servlet - javascript

If a user clicks on the following, he will be send to another page via the servlet.
<li><a method="POST" href="ToolServlet?action=goToUserRolesOverview">SOME TEXT</a></li>
I want to send a variable with the submit to the servlet, I came up with this:
<li><a method="POST" href="ToolServlet?action=goToUserRolesOverview">SOME TEXT<input type="hidden" name="user_emailHidden" id="user_emailHidden" /></a></li>
To fill in the hidden 'user_emailHidden', I do the following JavaScript:
console.log("user_email: " + params.user_email); /*Testing only: it works */
document.getElementById("user_emailHidden").value = params.user_email;
The value is set to the hidden variable, I tested this with:
console.log("user_email test: " + document.getElementById("user_emailHidden").value);
This is not working. Any help on how to include the variable with the submit when the user clicks on this item?
Thanks

this way to send variable with the url to the servlet .
javaScript
<script type="text/javascript">
function navigate() {
var userEmail = document.getElementById('user_emailHidden').value;
window.location = '${pageContext.servletContext.contextPath}/ToolServlet?id='
+ userEmail;
}</script>
href
SOME TEXT <input
type="hidden" name="user_emailHidden" id="user_emailHidden"
value="123546" /></a>
Servlet
#RequestMapping(value = "/ToolServlet")
public void getEmailId(HttpServletRequest request) {
System.out.println(request.getParameter("id"));
}

Found the solutions.
For the link, I send the variable with the url to the servlet as so:
<li id="insertUserEmail">SOME TEXT</li>
To add the user-email to the end of the href:
$('#insertUserEmail a').attr('href',function(i,str) {
return str + params.user_email;
});

Related

How to call a function in a php file using jquery load?

I am trying to display the data i retrieve from the database but it is not being displayed. I have a function in the file getComments.php called "getComments(page)" page is just a integer parameter to choose that database. and as you can see that i need to call this function to print the users comments. I am trying to use "load" but it is not being successful i just want to call this function to load the comments on the page. thank you in advance.
<?php
use TastyRecipes\Controller\SessionManager;
use TastyRecipes\Util\Util;
require_once '../../classes/TastyRecipes/Util/Util.php';
Util::init();
function getComments($page){
echo "<br><br>";
$controller = SessionManager::getController();
$controller->getComments($page);
SessionManager::setController($controller);
}
and in my web page where i want to display it using java script, i tried the following
<div class="page" id="comments">
<p class="style">Comments</p>
<button class="btn" id="load-comments">See Previous Comments</button><br>
<br><br>
<?php
if(isset($_SESSION['u_id'])){
echo " <input type='hidden' id='uid' value = '".$_SESSION['u_uid']."'>
<input type='hidden' id='date' value = '".date('Y-m-d H:i:s')."'>
<textarea id='message'></textarea><br>
<button class = 'btn' type = 'submit' id = 'submitCom'>Comment</button>";
}
else{
echo "<p>Please log in to comment</p>";
}
?>
</div><br>
<script>
$(document).ready(function(){
$("#load-comments").click(function(){
document.getElementById('#comments').innerHTML =
$("#comments").load("../extras/getComments.php", getComments(1));
});
});
</script>
Just change your click handler to this:
$("#load-comments").click(function(){
$("#comments").load("../extras/getComments.php", { page: 1 }); //i also added where the elements are loaded
});
and in getComments.php (if practical, otherwise you might need to create a new PHP file which calls the getComments() function and call that from the click handler instead) add something like:
if (isset($_POST['page'])) {
getComments($_POST['page']);
// do any other necessary stuff
exit;
}

Value of element created in JS required in Spring MVC controller

I created an input tag inside the javascript, and I also provide the attribute name to it,
var tdTotalEmployees = row.insertCell(k++);
tdTotalEmployees.innerHTML = rowData.totEmployees !== null ? '<h4>' + rowData.totEmployees + '</h4><input type="hidden" name="migrationRef" value=' + rowData.migrationReference + '>' : ' ------ ';
Now as usual, I need this variable value in my controller, I used #RequestParam("migrationRef")String migrationRef
it didn't work,
I used SOUT on request.getParameter("migrationRef"), it displays null. means no value supplied from, but when I inspect the element, I clearly see the value of this element
#RequestMapping(value = "/employee_details")
private ModelAndView getEmployeeList(HttpServletRequest request) {
ModelAndView mav = new ModelAndView("migrate_salary_hr/pre_migration_emp_list");
HttpSession session = request.getSession();
Userdetail loginUser = (Userdetail) session.getAttribute("loginUser");
System.out.println("migration ref no" +request.getParameter("migrationRef") );
try {
mav.addObject("yearMonth", request.getParameter("ym"));
mav.addObject("status", request.getParameter("s"));
mav.addObject("historyList", request.getParameter("h"));
if (loginUser.getEmployee().getRegion().getRegionId() != null && loginUser.getEmployee().getCircle() != null) {
mav.addObject("Region", loginUser.getEmployee().getRegion().getRegionId());
mav.addObject("circle", loginUser.getEmployee().getCircle().getCircleId());
} else {
mav.addObject("Region", loginUser.getEmployee().getRegion().getRegionId());
}
mav.addObject("orderBy", OrderByMap.PREMIGRATIONEMPLIST_ORDERBY);
} catch (Exception e) {
e.printStackTrace();
}
return mav;
}
kindly suggest me the best solution.
The value of the hidden input migrationRef is not sent to the server when one click on the link. That's why you don't see it server side.
I can see two ways to solve this :
Either add the parameter migrationRef into the href attribute of your link, and remove the useless <input type="hidden" ...
Or, if you really don't want to see the parameter migrationRef in the URL, you have to POST it using a form. In this scenario, the action attribute of the form should be of the like action="../emp_list_sm/employee_details?ym=...&s=...&h=...". Then in the Spring MVC controller you will have to use #ModelAttribute in place of #RequestParam on a Java Bean that has a migrationRef attribute.
I think workaround will be create form element and onclick of anchor trigger form submit. This will enable you to post all the information.
<form action="/{you-url}">
<a id="go" href="#" target="_blank"/>click here</a>
<input type="hidden" name= "ym" value = "+rowData.yyyymm+"/>
<input type="hidden" name="s" value="false"/>
<input type="hidden" name="h" value = "true"/>
<input type="hidden" name="migrationRef" value=' + rowData.migrationReference + '/>
<input type="submit"style="display:none"/>
<script>
document.querySelector("#go").onclick = function(){document.querySelector("input[type='submit']").click()};
</script>
</form>

ajax method ($.post) with mysql not working simple code

i have problem this code not working , i want display result of mysql without send no data
my simple code ajax
$('.myClass').on('click',function(){
$.post('resultAll.php');
});
code html
<li class="myClass" > click this </li>
code php / mysql for display result on page (name resultAll.php)
$stmt = $connect->prepare('SELECT * FROM table WHERE price = :aff');
$stmt->execute(array(':aff'=>'5'));
$res = $stmt->fetchAll();
foreach ($res as $row) {
?>
<div class="noon" style="width: 1000px;height: 500px">
<?php print_r($row['id'].' '); ?>
</div>
result these nothing
As per your code snippet, you want to fetch data from resultAll.php file into your HTML page. If I am correct then your code is wrong, you have to use below method instead of $.post() method
$('.myClass').on('click',function(){
$("#result").load('resultAll.php');
});
Your HTML code should be
<li class="myClass" > click this </li>
....
...
<div id="result"></div>
I mean in your page must have one div tag with id="result".
I hope this is works for you.
As you say that your Jquery is not working. Is your element .myClass is created with JS dynamically? Ensure this:
$(document.body).on('click', '.myClass', function(){
$.post('resultAll.php');
});
Edit
Add response from $.post to body:
$('.myClass').click(function(){
$.post('resultAll.php', function(response){
$(body).append(response);
});
});

Pulling the string value in Javascript

So I have this unordered list of items that is made from querying a mysql database
<ul>
<li>apple</li>
<li>orange</li>
<li>pear</li>
</ul>
I want there to be an onclick event that will pass 'apple' when I click apple and 'orange' when I click orange.
I also want to pass this information to another page through php. So this is my idea for the javascript function.
<script>
function passName(obj){
var pass = "<?php $x= " + obj.getName() + " ?>";
}
function getname(obj){
return 'string';
}
</script>
My Question: is there a method that exists within JavaScript that allows me to pull the raw string value of my unorderedlist without writing my own function? If I have to write my own JavaScript function, is there a way to set the 'name' strings automatically, while the list is populating?
Use JQUERY AJAX for send data into php page
/* Get value from clicked li */
$(function() {
let value = "";
$('ul li').on("click", function() {
value = $(this).text();
console.log(value);
});
/* AJAX for send value into result.php page */
$.post("result.php", {value: value}, function(res) {
console.log(res); // return from result.php page
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<ul>
<li>apple</li>
<li>orange</li>
<li>pear</li>
</ul>
result.php
if(isset($_POST['value']) && !empty($_POST['value'])) {
echo $_POST['value'];
}
This is how you can do it. On click you can change the page or do whatever you want. In the new url you can append the fruit value as a parameter to pass it to php
<ul>
<li onclick="fruitsClick('apple')">apple</li>
<li onclick="fruitsClick('orange')">orange</li>
<li onclick="fruitsClick('pear')">pear</li>
</ul>
<script>
function fruitsClick(fruit){
// do whatever you want
window.location.href = "[yourpageurl]?fruit=" + fruit
}
</script>

Remove query string on page reload

I have a hyperlink which i am redirecting to a page.
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
window.location = '/Merging/Index/?workItemID=' + id;
});
My action in the controller page is
public ActionResult Index(int? workItemID)
{
MergingVM mergingVM = new MergingVM();
mergingVM.SourceList = GetSourceDropdownList();
mergingVM.WorkItem = (workItemID==null? 0: workItemID.Value) ;
mergingVM.MergeActionSelectList =
GetMergeProcessActionDropdownList();
PopulateDropDowns(mergingVM);
return View(mergingVM);
}
So what it does is when i click on the hyperlink it redirects me to the merging page.
After redirecting to Merge page, the drop down fills with id(selected in home page) and correspondingly triggers the button click.
My issue When i reload the merge page the value in the drop down doesn't get clear. I.e if i have redirected from home page to merge page , then the drop down has some value. but when i refreshes it the selected value should go. I understand that the query string still holds the value. But is there any alternative to send parameter to action without using windows.location.href in jquery.
If you are using hyperlink then also you can try it
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
$(this).attr('href','/Merging/Index/?workItemID=' + id)
});
In order to clean the query string you should use redirect to another view.
public ActionResult Index(int? workItemID)
{
MergingVM mergingVM = new MergingVM();
mergingVM.SourceList = GetSourceDropdownList();
mergingVM.WorkItem = (workItemID == null ? 0 : workItemID.Value);
mergingVM.MergeActionSelectList =
GetMergeProcessActionDropdownList();
PopulateDropDowns(mergingVM);
//to send this model to the redirected one.
TempData["model"] = mergingVM;
return RedirectToAction("CleanIndex");
}
public ActionResult CleanIndex()
{
var model = (MergingVM)TempData["model"] ?? new MergingVM();
// Do something
return View("Index", model);
}
To find alternatives to an send parameter to a method you first need to understand the model Bindding action.
The model bidding searches a value in:
Form Data
Route Data
Query String
Files
Custom (cookies for example)
If your action must need to be HttpGet you lose the Form Data which would be a nice alternative for you.
If I understand correctly... the below worked for me.
If there's an ID appended to the URL, it gets logged to the console as the variable "param". The URL is then replaced (so that if you refresh the page, the ID is removed from the URL).
$(document).ready(function() {
var url = window.location.toString;
var hostname = window.location.hostname;
var pathname = window.location.pathname;
var param = window.location.search;
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
window.location = '/new-page.php?' + id;
});
if ( pathname == "/new-page.php" && param ) {
console.log(param);
window.history.pushState("string", "Title", "http://yourURL.com/new-page.php");
//Do something with param...
}
});
This assumes that if there is no ID appended to the URL, the drop-down won't do anything. You also would need to update the URLs to the correct ones (I ran this on my local server).
I think you should use POST where you don't want to presist workItemID.
I mean all places where you have links you should use somethink like this:
<form action="/Merging/Index" method="POST">
<input type="hidden" name="workItemID" value="1" /> <-- your Id
<input type="submit" value="Link to workItemID 1!" /> <-- your link
</form>
This way you will get your View but without workItemID in URL. But you should change css to make your POST link look like <a> tags.
Here is with your table:
#if (#Model.DataSetList[i].StateID == 43)
{
<td>
<form action="/Merging/Index" method="POST">
<input type="hidden" name="workItemID" value="#Model.DataSetList[i].Workitem_ID" />
<input class="lnkMerging" type="submit" value="Merging" />
</form>
</td>
}
else
{
<td>
<text style="color:darkgrey" contenteditable="false">Merging</text>
</td>
}
You can save the parameter in local storage api of html5, and then use those parameters in Page load of index page.
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
localStorage.setItem("workItemID",id);
window.location = '/Merging/Index/;
});
On page load of index you can retrieve it using getItem
localStorage.getItem("workItemID"); and use it as per your requirement.
On page load of Merge page, you have to explicitly set the selected option like below and then remove the value from local storage.
$(document).ready(function(){
if(localStorage.getItem("workItemID")!=null){
$("#mydropdownlist").val(localStorage.getItem("workItemID"));
localStorage.removeItem('workItemID');
}
});
Make sure in var id = $(this).attr('data-id'); id should get same value as you have in the options on the merge page.

Categories

Resources