how can i use javascript var in scriplets - javascript

I am trying to learn jsp. I know a little bit java and I dont know much about html tags so I simple use java codes as much as I can. What I am trying to do there is getting data from variables from text boxes and using them as string.
var text1 =<% request.getParameter("locationId"); %>;
<%
if ((text1 != null && text2 != null) && (!text1.equals("") && !text2.equals(""))) {
kw1 = "'%"+text1+"%'";
kw2 = "'%"+text2+"%'";
.
.
.
}
%>

Scriptlet is executed before any data about webpage get sent from server to client. Whatever you want to do you need to send postback to server (with forms or ajax call). I usually use jQuery so my answer will use it but feel free to modify it to use native JS code. First, I would create a page on server called something like createJsonObject, call it from client with $.ajax (type: "POST") and passed my argument as object
{varID: varID}
On server I would place my JSP on that page, read argumants upon page load, execute function and return object with data to client. In .done() I would do something with that data (display them in form, save them in JS variables...).
Hope this helps you out.
Example (Just showing how you can use Ajax with form example)
HTML form:
<form name="formName" method="post" action="">
<input type="text" name="name" id="firstName" value="" />
<input type="text" name="lastName" id="lastName" value="" />
<input type="submit" name="Update" id="update" value="Update" />
</form>
Ajax Post:
$("#update").click(function(e)
{
e.preventDefault();
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var dataObject = {};
dataObject.firstName = firstName;
dataObject.lastName = lastName;
$.ajax({
type:'POST',
data:dataObject,
url:'returnData.php',
success:function(data)
{
alert(data);
}
});
});
PHP:
<?php
$receivedObject = json_decode($_POST['data'], true);
$name = $receivedObject['firstName'];
$lastName = $receivedObject['lastName'];
echo $name . ' ' . $lastName;
?>
I've not test this, so there might be somewhere i've gone wrong. But try something like my example and just ask if you need any help.

Ali, you can not use a javascript variable into jsp scriplate.
<%
String locationId=request.getParameter("locationId");
if ((text1 != null && text2 != null) && (!text1.equals("") && !text2.equals(""))) {
kw1 = "'%"+text1+"%'";
kw2 = "'%"+text2+"%'";
.
.
.
}
%>
but vise versa is possible you can use JSP variable into you javascript code.like this.
<script>
var locationId='<%=request.getParameter("locationId")%>';
alert(locationId);
</script>

Related

I am Having Problems Updating My MySQL table value From my Modal form Sing PHP

I created a modal form (that pops up upon a link click, i.e trigger()). This is the HTML code:
<div class="modalbg">
<div class="modalPopup">
<form action="samepage.php" class="formContainer" method="post">
<h2>Change Desk Number</h2>
<label for="studentid">
<strong></strong>
</label>
<input type="password" placeholder="Your KEY" name="studentid" required/>
<label id="status" style="color:red;"></label>
<button type="submit" class="btn" onclick="return verify()">Upgrade</button>
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</form>
</div>
</div>
The JavaScript that controls this modal is:
function trigger(){
document.getElementById("modalPopup").style.display = "block";
}
function closeForm() {
document.getElementById("modalPopup").style.display = "none";
}
function verify() {
var studentid = document.getElementById("studentid").value;
if (studentid != dbstudentid || !studentid){
document.getElementById("status").innerHTML="Invalid Student ID!";
function trigger(event) { event.preventDefault(); }
return false;
}
else{
document.getElementById("modalPopup").submit();
}
}
Everything works at this point (i.e it pops up whenever I click the link and whenever I knowingly try to enter a wrong studentid, it returns the "Invalid student ID" on the "status" label. (Note: I had already saved the session's student ID in the variable dbstudentid using:
var dbstudentid = <?php echo json_encode($dbstudenid);?>;
My problem however comes from when I try to execute the PHP on the same page.
Whenever I insert the PHP code into the modalbg div or modalPopup div inside it, the entire modal refuses to pop, let alone submit.
This is the PHP code I used (it should be noted that at the beginning of the page, I had already used include(configure-db.php) and session_start() ) :
<?php
if(isset($_POST['studentid'])){
$studentid = $_POST['studentid'];
$desk = 1;
$deskstatus ="";
$select = "UPDATE users SET deskNo = '$desk' WHERE name='$SESSION';
}
if (mysqli_query($MyConn, $select)) {
$deskstatus = "Desk changed successfully!";
} else {
$deskstatus = "Error";
} return $deskstatus;
?>
I have tried everything, the modal just refuses to come every time, let alone successfully make the Desk Update on my Database. to make things worse, whenever I refresh the page, the modal which I set to display:none; by default on CSS suddenly starts showing. But whenever I remove the PHP code, it returns to normal.
Do I need to make the action execute in a separate page? If yes, please how?
Else, how please?
I world highly suggest you think about using AJAX to handle this probolem.
let's clear up things.
you can write var dbstudentid = '<?= $dbstudenid ?>'; instead of var dbstudentid = <?php echo json_encode($dbstudenid);?>; this will give you freedom of JS native datatype.
you need to send this form request through ajax and recive output there.
Change the php code else part to like this
else { $deskstatus = "Error: " . mysqli_error($MyConn); }
Now when there is a actual problem on code you will know what was the problem. and it will not break you interface.
4. Create seperate file that handle this form request.
5. Here is code snippet of plaing JS AJAX implementation
let post = JSON.stringify(postObj)
const url = "https://jsonplaceholder.typicode.com/posts"
let xhr = new XMLHttpRequest()
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8')
xhr.send(post);
xhr.onload = function () {
if(xhr.status === 201) {
console.log("Post successfully created!");
let AlertDiv = document.querySelector('#alert');
AlertDiv.innerHTML = xhr.response;
}
}

How to use variables from another php file to include in a html page javascript function

I have an HTML file, and in the file, I have a javascript validate function to validate if the input of the text field in the other PHP file is blank or not. How can I use the 'gateway' name from myFile.html. This is what i have now:
myfile.html
<script type="text/javascript">
function Validate() {
if ((document.getElementsByName("gateway")[0].value == '')) {//I need to get access to "gateway" from myOtherFile.php
alert('Response required');
return false;
}
else { return true; }
}
</script>
myOtherFile.php
<div id="gatewayInput">
<form action="/action_page.php">
Gateway: <input type="text" name="gateway" placeholder="Gateway Name"><br>
</form>
</div>
#kkmoslehpour there are three ways
make an Ajax call
function Validate() {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
var value_from_gateway = ajax.responseText;
}
}
ajax.send();
ajax.open("Get", "myOtherFile.php?value_from_gateway", true);
if ((value_from_gateway == '')) {//You have access now to "gateway" from myOtherFile.php
alert('Response required');
return false;
}
else { return true; }
}
create a redirect function on the myOtherFile.php on the top on the page -NECCESSARY
function redirect($location) {
header("Location: ". $location);
}
then program your myOtherfile.php to work with th $_GET and send the value
<div id="gatewayInput">
<form action="/action_page.php" method="post">
Gateway: <input type="text" name="gateway" placeholder="Gateway Name"><br>
</form>
</div>
<?php
if(isset($_GET['value_from_gateway'])) {
$gateway_value = $_POST['gateway'];
redirect('value_page.php?value_to_js='. $gateway_value);
}
?>
then create the whole value_page.php to echo the value on that same page;
<?php // This is all that there should be on this page
if(isset($_GET['value_to_js'])) {
echo $_GET['value_to_js']; //we are echoing this! it will be the response to the Ajax
}
?>
The ajax call wont have any problem with this, and whatever is display on the current page (value_page.php) will be sent as the response in myfile.php
I cannot comment but if you want to get info from your php file by your html file and javascript it could be done with ajax call to check what is inside php file and returns back with some info.
Otherwise you need to include that html file with script below your element with that name so you can use javascript to find that element and get its what you want.
You should put the validation code into the same file as the form, as it has to run on the client side. But if for some reason you really have to have it in a separate file (and that file only contains the script tag):
echo file_get_contents('myfile.html');
It is now magically in this file as well. But seriously just put it in the same file.

pass variables from javascript to php with a cookie

this has been asked before, i want to do it so i can avoid refreshing the page caused by POST and GET, and ajax seems the right way
but i was wondering if i can make a cookie with javascript and then (from the same page) access it with php. is it possible?
small example:
//html code:
<form name="PLForm" onsubmit="myFunction()">
<input type="text" name="PLName"/>
</form>
//JS part:
myFunciton() {
var cname = "playlistName";
var cvalue = document.form["PLForm"]["PLName"];
document.cookie = cname + "=" + cvalue;
}
//in php:
<?php
$x = $_COOKIE["playlistName"];
//some code
?>

PHP and javascript combining variables issue

I have a PHP file where I display a html table (HTML) with data from a mysql table.
<?php
include 'connexion.php';
session_start();
$idfirm = $_REQUEST['idfirm'];
$namefirm = $_REQUEST['namefirm'];
The rows in the table have the
<tr class="clickableRow"...
Then on row click (javascript) I want to be able to call (POST) another PHP file that will display other information based on some info from the table row.
I have difficulties in achieving this.
What I have done so far is:
echo '
...
jQuery(document).ready(function($) {
$(".clickableRow").click(function() {
var tableData = $(this).children("td").map(function() {
return $(this).text();
}).get();
// So I can access the field data either like this
var myID = $.trim(tableData[0]);
// or like this:
var name = $(this).closest(\'tr\').find(\'td:eq(1)\').text();
alert(myID);';
echo" // here I would need to access some variables that I received above in PHP from POST
var namefirmx = '{$namefirm}';
var idfirmx = '{$idfirm}';
";
// and here I would like to call another PHP file (with POST) that will display info about the employee
So, how can I make a POST to another php file and send POST variables:name,namefirmx, idfirmx,myID
I am not sure how to make the POST.
I believe there is no other way to call the POST but javascript. (Remember that the POST must be made on row click)
Please help me out here...
Quick example of php script, some html tags are missed, but I think you will get a picture:
<?php
print_r($_POST);
?>
<script src="http://codeorigin.jquery.com/jquery-1.10.2.js"></script>
<script>
jQuery(document).ready(function($) {
$(".clickableRow").click(function() {
$(this).find("form").submit();
});
});
</script>
<table border="1">
<tr class="clickableRow">
<td>
<form method="post"><input type="hidden" name="p1" value="v1"><input type="hidden" name="p2" value="v2"></form>
v1
</td>
<td>v2</td>
</tr>
</table>
I solved my problem using a SO previous question. I am not sure what to do with this question.
Anyway, the answer is: adding a function in javascript, and calling it with my variables.
The function is:
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
You can always add php variables inside your js code like the following :
<?php
$x="ABC";
?>
<script language="javascript">
jsX="<?php echo $x;?>";
alert(jsX);
</script>

get post field by JavaScript

as you know we can get post field by server side language like php,for example in php
$var1 = $_POST['field1']now I wanna know is it possible to get it by JavaScript to?(or any Client Side Language like VBScript)
for example I have page which has got form
<form method = "post" action="test.php">
in test.php I wanna get field by JavaScript,not by php.
Is it possible and how can I do it if it's possible?
You cannot read $_POST data using JavaScript.
When you submit data through the GET method, the generated query string can be read through the location.search object. Another method to "post" data from page 1 to page 2 is by using hashes.
The location object (JavaScript)
location.href = http://example.com/test.php?formElem=value&another=true#hash
location.search = ?formElem=value&another=true
location.hash = #hash
Example (based on the URL at the previous paragraph)
<script>
var $_GET = (function(){
var query_string = location.search.substr(1); //Exclude the first character: `?`
var data = query_string.split(/&+/); //
var $_GET = {};
for(var i=0; i<data.length; i++){
var qs = data.match(/^([^=]+)(?:=(.*))?$/);
$_GET[qs[1]] = qs[2];
}
return $_GET;
})()
alert($_GET["formElem"]); //Alerts "value"
</script>
An alternative method to transmit data from a form to a JavaScript HTML page is by using hashes:
<form action="index.html#someHash" method="get">
<input type="submit" name="someName" value="someValue" />
</form>
After submission, the following page will be requested: index.html?someName=someValue#someHashThe hash is available through the location.hash property.
in your test.php file, echo your post fields as a JSON object.
echo '<script> var data = '. json_encode($_POST).' </script>' ;
It can be accessed as a dictionary in javascript then.
Output in test.php
<script>
var data = { 'field1' : 'value1' , 'field2' : 'value2' } ;
alert(data['field1']);
</script>

Categories