PHP and javascript combining variables issue - javascript

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>

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;
}
}

Passing Javascript variable to php on the same page

I'm trying to pass a javascript variable to php on the same page. I tried some code but nothing worked.
The current code looks like this:
function init(e){
$('#DeleteDaily').click(function() {
d = document.getElementById("DailyRequestsList");
selected = d.selectedIndex;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "index.php?i=" + selected, true);
xhttp.send();
});
}
$(document).ready(init);
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
<?php
if(isset($_POST['DeleteDaily'])) {
$Index = $_GET['i'];
}
?>
});
});
If I try to use Index as an argument for a python script it should delete an entry in a textfile and an element from a select object should be deleted on the website which doesn't happen. The python script itself works fine.
But I don't know why the variable isn't passed to php.
You can't just "mix" javascript and PHP like you're doing.
If that is inside a web page, the PHP code will be rendered (in your case, it will return nothing), and the page will just interpret an empty javascript function.
You need that PHP to be on the server, or turn it into javascript...
you can done it by
PHP Code
<?php
if(isset($_POST['DeleteDaily'])) {
$Index = $_GET['i'];
}else{
$Index='';
}
?>
Javascript code
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
var index = '<?php echo $Index;?>';
if(index == ''){
//put your code
}else{
//put your code
}
});
});

send data to a page through jquery ajax and.data() method while going to that page

<script>
function user_pro(useron){
$.post("userprofile.php", { useron:useron } );
document.location.href="userprofile.php";
}
$(document).on('click','#userprofile',function(){
var useron=$(this).data('id4');
user_pro(useron);
});
</script>
i am trying to send data to the page "userprofile.php" through the jquery ajax .post() when i click a button with id 'userprofile'. i have stored the username of the user(which i retrieved from my database in data-id4 attribute ). i want to send this username to my userprofile.php page and display his profile(like dp,status and all...). the .data('id4') method is working fine as i am able to store data in the variable useron . but i am not able to send the data to userprofile.php . and i also simultaneous want to be directed to that page when i click the button with id="userprofile".
<a data-id4='".$row['username']."' id='userprofile' class='w3-btn w3-teal w3-hover-indigo'>profile</a>
this is the html element. the html is inside the echo tag of of a php page(that is why those quotes).
can somebody plz help me out here . thanks in advance :) .
this code worked ...
function post(path, parameters) {
var form = $('<form></form>');
form.attr("method", "post");
form.attr("action", path);
$.each(parameters, function(key, value) {
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", key);
field.attr("value", value);
form.append(field);
});
// The form needs to be a part of the document in
// order for us to be able to submit it.
$(document.body).append(form);
form.submit();
}
$(document).on('click','#userprofile',function(){
var useron=$(this).data('id4');
post("userprofile.php",{useron:useron});
});
thanks everyone.

how can i use javascript var in scriplets

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>

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