In one of my webpage I print one button multiple times and all have different logId. I want that when user click then there will JQuery into the picture and there should be no server side post-back. Since a unique log id is associated with every button so I pass the information to JS file from *.Module as below when the button is clicked:-
*.module File -- PHP File
$thm_button .= '<input type="button" class="clsPrevious" id="btnPrev_'.$user->uid.'_'.$logid;>';
*.js File
$('.clsPrevious', context).click(function (event) {
var previousLog=this.id.split('_');
//Retrieve log Id and Process the log id using AJAX call
}
This is working fine here but I feel there is security concern as everyone can view the log id of the button in HTML source.
Are there any ways in Drupal/PHP/HTML to pass the sensitive information to JS without showing in HTML Viewer.
You can pass values from PHP to Javascript with "Drupal.settings".
Read more about it here.
You can create a input button which looks something like this.
$thm_button .= '<input type="button" class="clsPrevious" data-myModule=" . $key . ">;
where $key is a random/serial variable but is unique per Log ID.
Create a mapping array of key value pair and pass to javasript using drupal_add_js()
<?php
drupal_add_js(array('myModule' => array('_YOUR_CUSTOM_KEY_1_' => '_LOG_ID_1_')), 'setting');
?>
And now modify your click function to,
$('.clsPrevious', context).click(function (event) {
var key = $(this).attr("data-myModule");
// Now a this point you have the lookup table in Drupal.settings.myModule
// use the "key" variable to find the LOG ID
}
Related
Hello and good day everyone! I am here to ask on how to pass a file type using javascript, so that I can use it to another php page. The following is an input for type file:
<input type="file" name="imgCompany" id="imgCompany">
I am getting the file like this in php:
$file = $_FILES['imgCompany']['tmp_name'];
The first question I have to ask is how can I get the $file variable to be place in a javascript function? (same php page). So far this was my attempt to do so:
function addImage() {
var companyImage = $('#imgCompany').val();
}
The second question I have to ask how do I pass that file value once it is declared in the addImage() function using a method like this:
$.post('addImage.php', {postimage:file},
function(data)
{
//returns the echoed value from the php file
$('#result').html(data);
});
Or is there another way?
I am going to use what I pass from the post to another php page, so I can upload that image into a database. I am uploading this image into a database like this:
...
$image = addslashes (file_get_contents($_FILES['image']['tmp_name']));
//$image_name = addslashes ($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if ($image_size == FALSE)
echo "<h3 class='warningStyle' align='center' style='position:absolute; top:235px; left:660px;'>No Image was Selected</h3>";
else {
if (!$insert = $db->query ("INSERT INTO company VALUES('','$companyName','$image')"))
echo "<h3 class='warningStyle' align='center' style='position:absolute; top:235px; left:650px;'>Problem uploading the image</h3>";
else {
echo "<h3 class='successStyle' align='center' style='position:absolute; top:235px; left:620px;'>Company Account successfully created</h3>";
}
}
I cannot read JQuery (nor do I want to), but here are a few pointers:
The file name in file-upload: javascript-how-to-extract-filename-from-a-file-input-control
The second question I have to ask how do I pass that file value once it is declared in the addImage() function using a method like this:
You don't have to, the file will be send in the form you are sending.
I do not understand what you are trying to accomplish by adding javascript to that. The original filename will also be send to the server. (Inspect the $_FILES on arrival to see it for yourself)
About the insertion in the database:
addslashes? Really? Escape it in another way, preferable with the quotation/escape functionality delivered with your database.
And another thing: If you go to "another page" your $_FILES will be empty. Handle it on arrival, not after invoking a new page. I am not sure what or how you are doing it, but keep that in mind when you see an empty $_FILES while you expected some information in it. :-)
I have a webpage which contains an array generated with JavaScript/jquery. On a button press, I want to run a PHP function, which updates a MySQL database with the JavaScript array.
I have a .php file with a PHP function that connects to the database and runs an UPDATE query, I want to use the array with that.
So I have home.php, which has the button:
<?php
include_once ('submit.php')
?>
<center><button id="submit" class="button1" >Submit<span></span></button></center>
and the array:
<script>
selectedItemsArray;
</script>
and I have submit.php, which has the sql UPDATE:
function submit(){
$sql = $dbh->prepare("UPDATE pending_trades SET item_list=:itemlist,");
$sql->bindParam(':itemlist', /*array taken from home.php*/);
$sql->execute();
}
I'll convert the array into a JSON before I put it into the database, but I need to know how to get access to the array with my submit.php file, and how to run the submit() function on the HTML button click.
There are multiple issues here. Most crucially, you seem to be confusing server-side and client-side scripting.
You are including submit.php in home.php, which declares a function submit() on the server-side. Your code never executed this function while on the server-side, and so the server-side output is empty,i.e. <?php include_once ('submit.php');?> evaluates to nothing. What the client-side receives is a HTML file with only the button, the function submit() is never passed to the browser.
Remember: server-side scripts are ALWAYS executed on the server and NEVER passed to the browser. That means you will never see anymore <?php and ?> when the file hits the browser - those PHP codes have long finished.
What you need to find out in order to accomplish what you intend:
Use client-side script (JavaScript) to listen to button clicks.
Use client-side script (JavaScript) to submit the form to server through AJAX.
Use server-side script (PHP) to read the data POST-ed, extract the data into an array.
In effect, you are asking three questions. And they are really straightforward; you can read up yourself.
What I'd do is to suggest an architecture for you:
home.php or home.html: contains the button, <link href="home.css"> and <script src="home.js">.
home.js: client-side script to listen for button click and submit AJAX to submit.php.
home.css: styles for the button and other elements in home.html/home.php.
submit.php: server-side script to check for POST variables and the SQL update operation.
Another issue: you are using a deprecated tag <center>. I'd advise you to remove it and layout the button using CSS instead.
use jquery AJAX.
<button id = "submit" class = "button1" > Submit <span></span></button>
your js code
$('#submit').click(function(){$.ajax({
method: "POST",
url: "submit.php",
data: itemlist,
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
and your php file. don't include file
$array = json_decode($_POST['itemlist'], true);
Remember your js array itemlist should be json format e.g.
$itemlist = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
I am creating a website that has users log in and select a pdf document that they want to download. When they open up the document to view and possibly download, I want data to be logged into a database at the same time.
The code to send the data to the database works (Except for: Undefined index: learningMaterial). But when I want to have the pdf document open and at the same time log the user and other data, all that happens is the document opens up.
Any advice would be appreciated, even for overall better methods of going about what I'm trying to achieve here. Still inexperienced with PHP.
See code below.
HTML
<form name="myform" method='post' action="../includes/writeStats.php">
<input type='hidden' name='learningMaterial' id='learningMaterial' value='learningMaterial'>
<a href='../documents/test.pdf' id='mylink' class='courses' name='Driver Training'> Driver Training </a>
</form>
JS - In header
<script type="text/javascript">
function submitform(){
document.myform.submit(); }
var form = document.getElementById("myform");
document.getElementById("mylink").addEventListener("click", function () {
submitform();
});
</script>
PHP
<?php
$con=mysqli_connect("localhost","root","password","qmptest");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Get latest log nr
$result = mysqli_query($con,"SELECT * FROM logbook ORDER BY log DESC LIMIT 1");
while($row = mysqli_fetch_array($result)) {
$log = $row['log'] + 1;
//If statement to check if log is 0(first entry) to go here
}
$date = date("Y/m/d");
session_start(); // Start a new session
$person = $_SESSION['currentUser'];
//Not sure if this is correct along with my HTML input
$material = mysqli_real_escape_string($con, $_POST['learningMaterial']);
//Insert into database
$sql="INSERT INTO logbook (log, date, person, learningMaterial)
VALUES ('$log', '$date', '$person', '$material')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
Your way, clicking the link will override the form being submitted. This leads to the file opening and the form never going through.
Instead, you could try either opening the file in a new window by adding target="_blank" to the tag, or send the files URL through to the PHP, executing the database code then adding to the end:
header("Location: http://yourdomain.com/yourfile.pdf");
Your file is just a normal file being returned by your web server:
<a href='../documents/test.pdf' ...
So while you may be able to suggest to users or browsers that they should invoke some code before downloading this file, you can't actually require it. Any user can just request the file directly. And since PDF files don't execute PHP code (thankfully), your server-side PHP code has no way of knowing that the file has been requested.
What you can do is obscure the file itself behind a PHP request. You can create something like a download.php page which accepts the name of a file (test.pdf) and returns that file.
Be very careful when doing this. Don't just allow users to request any file and blindly return whatever they request. A user can request something like "../../../../../../../../../../etc/passwd" and if your code just builds a path and returns the file then you've just given users a sensitive file. It's best practice to keep a finite known list of identified files (perhaps in a database table) and let users request by the identifier rather than by the file path itself. That way the actual path is only ever known server-side in data that you control.
The main point here, however, is that by using such a page you inject some PHP code in between the user and the file. In order to get the file, the user needs to make a request to a PHP page. On that page you can record the act of the user having requested the file. (As well as perform authorization checks to validate that the user is allowed to view the file, etc.)
Never assume client-side code is going to do what you expect it to do. If you want to ensure something happens for anything approaching security or auditing purposes, it needs to happen in server-side code.
I am developing a php page containing a drop down select button. On changing its value, I am calling a javascript method and passing value selected in drop down. Now I want to use the value passed to get further details from MySql using PHP. How can I write PHP code withing javascript?
I am a beginner to PHP. Suggest me a simple and easiest way to do this
For onchange event of dropdown, you can call php page using ajax and passing your params and get the output.
Try to use ajax like this (http://www.w3schools.com/php/php_ajax_database.asp)
and this (http://coursesweb.net/ajax/multiple-select-dropdown-list-ajax_t)
Front-end client side script (Javascript) can't directly 'invoke' or run PHP code. This is because of the separation between client side (browser) and server side (server) components of a web page. When you make a normal request to a server to return a page (eg. index.html), it will return the content of the page and terminate the execution.
What you're trying to achieve is something called AJAX, which is described on Wikipedia. There's also a pretty good and basic example of how to run a PHP script from Javascript.
In basic terms, AJAX is an asynchronous execution of the server side component of a web page. You can target a page 'test.php' with an ajax request, much the same was as you would when you open the page in your browser, and the content of the page would be returned.
To get the additional content, you can use either a POST ($_POST) or GET($_GET) request to send details back to the server. Typically when you're performing a search, you would use GET. If you're performing an update or create, you would use POST.
So your page URL might be something like http://mywebsite.dev/ajax.php?select=apples (where mywebsite.dev is the development URL). If you have a table of apple types, your MySQL query would be:
$type = $_GET['select'];
// Do some filtering on $type, eg. mysql_real_escape_string() and a few others
SELECT fruit.types FROM fruit WHERE fruit.main_type = '$type';
And then return a formatted JSON object back to the browser:
$return = Array(
0 => 'Pink Lady',
1 => 'Sundowner',
2 => 'Granny Smith',
...
);
$json = json_encode($return);
// expected result
{['Pink Lady'],['Sundowner'],['Granny Smith']};
You can always give extra indexes to arrays (multi-dimensional) or use stdClass to give better structure.
Then in your Javascript you use a for loop to iterate over the json object to build a new list of options.
var output = '';
for (var i = 0, k = json.length; i < k; i++) {
output += '<option value="' + json[i] + '">' + json[i] + '</option>';
}
Hope that helps.
Hi for this you need to use ajax.
try :
index.php code : This script will grab data from from using jquery and post it to search.php file via ajax
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#userid').change(function(){
userid=this.value;
$.ajax({
url:'search.php',
data : 'userid='+userid,
type:'POST',
success:function(result){
$('#result_div').html(result);
}
});
});
});
</script>
</head>
<body>
<form name='getUserData' id='getUserData' action='#' method='GET'>
Select User : <select id='userid' name='userid'>
<option value='1'>Lokendra</option>
<option value='2'>Amit</option>
<option value='3'>Nitin</option>
<option value='4'>Rishabh</option>
</select>
</form>
<div id='result_div'></div>
</body>
</html>
search.php code : This file will contain you business logic . and return value to ajax success method. You can fill retrun result any container.
<?php
$userArray=array(
1 => 'Lokendra',
2 => 'Amit',
3 => 'Nitin',
4 => 'Rishabh',
);
$postedData=$_REQUEST;
// Fire your select query here and diplay data
if(isset($postedData['userid'])){
echo "Selected User name =>".$userArray[$postedData['userid']];die;
}
?>
Dont forget to accept answer if it helps you. :)
i'm trying to update is a javascript which when you hover over an image, a div object floats near your mouse with information, this information is stored in a .js file as an array,
eg.
Text[0]=["image 1","data 1"]
Text[1]=["image 2","data 2"]
in the past if this array is change/data added to/removed from it would require uploading a new copy of the .js file, if data was added to/removed from it would also require a change to the .dwt file for the new image which would update every file that use the .dwt file as the main template which could result in 20+ pages being uploaded
i figured i can automate this by using the database by flagging records if they are active and using a mysql query to get only those which are active, this way a blackened app can add to the database and deactivate record thus eliminating having to upload files every so soften.
to do this, i had planned on storing the information in the database and building the above array based off the results, researching how to use mysql queries in javascript lead me to code like this
$.ajax( "path/to/your.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
now i understand that i need to make a .php file which runs my query and that my formatting of the query results into the array would be one in the .done part but what i don't understand is what i'm supposed to do in the .php file to output the query results how in the .done part i'm supposed to reference the output
bellow is the code i use to echo my query results to the page to ensure i am getting results
$resultIndex = 0
while($row = $results->fetch_array(MYSQLI_ASSOC))
{
echo '<'.strval($resultIndex).'><br>';
echo 'id = 'strval($row['id']).'<br>';
echo 'name = 'strval($row['name']).'<br>';
echo 'desc = 'strval($row['desc']).'<br>';
echo 'active = 'strval($row['active']).'<br>';
echo '-----------------------<br>';
$resultIndex += 1;
}
i am wondering 2 things
do i just echo or print_r what i want returned from my .php file
how to i access what my .php file returns in .done
I recommend using http://www.php.net/json_encode to output into Json. Yes, just echo the output. On success, a callback is called passed with the data from server.
$.post (url, function (data){
//do some stuff with data from server
});
See http://api.jquery.com/jQuery.post/
Your $.ajax function just points to a page and reads the data on that page. If you want that page to use MySQL, you will need to use php to set up the MySQL query and print the data. The layers of a web app are complicated, but I'll try to break it down for you.
A traditional php/mysql setup works like this:
Javascript:
Client side, only deals with content already available on the page. Often edits html based on user interaction.
HTML
Client side, defines the content on a page
PHP
Server side, runs on the server and construct the html
MYSQL
Server side, used to communicate between the php and the database
Database
Server side, used to permanently store data
Ajax is a way for the Javascript layer to call some php in the background. That php can use MySQL to access data in the database and print it out in a format that the javascript can parse and use. Typically the javascript will then edit the HTML.