Good afternoon,
I've been looking around for info on this and have come up dry. The idea is to have a form that uses select boxes to display info from a mysql database. This is mainly done with html/php, but I have added JavaScript functionality that allows a user to press a button to create an additional array of selects to indicate additional products. The problem I am currently facing is that I cannot seem to get the php to work inside of the JS innerHTML.
order-add.php
<script src="/js/addProduct.js" language="Javascript" type="text/javascript"></script>
<tr>
<td>Product(s)</td>
<td><div id="dynamicInput">
<select name="orders_product[]">
<option value="">Select One</option>
<?php
$orders_product_query = $conn->prepare("SELECT product_name FROM product");
$orders_product_query->execute();
$orders_product_query->bind_result($orders_product_result);
while ($orders_product_query->fetch()) {
echo "<option value = '$orders_product_result'>$orders_product_result</option>";
}
$orders_product_query->close();
?>
</select>
</div>
<input type="button" value="Add product" onClick="addInput('dynamicInput');">
</td>
</tr>
addProduct.js
var counter = 1;
var limit = 10;
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " products.");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "
<select name='orders_product[]'>
<option value=''>Select One</option>
<?php
$orders_product_query = $conn->prepare('SELECT product_name FROM product');
$orders_product_query->execute();
$orders_product_query->bind_result($orders_product_result);
while ($orders_product_query->fetch()) {
echo 'test';
}
$orders_product_query->close();
?>
</select>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
With all of the testing I've been trying to run on this, it appears that the issue is with the newdiv.innerHTML portion of the addProduct.js. I'm thinking that it is not accepting php, but it also could be that I have the inner quotes somehow messed up.
Thanks in advance for your help!
I think you are not understanding how this works. PHP code is executed when the client requests the page on the server side. JS is executed on the client side. There is no PHP interpreter on the web browser. What you could do is putting the PHP code in a separate file (Example: fragment.php) and calling it through AJAX. In that case your code will be executed in the server.
I hope this helps!
Is addProduct.js included as a tag? If so, take a look in your developer tools. This is probably showing exactly as you have it posted here, with the php tag as part of the text. You'll need to change the extension of this file to .php and change it in the script tag as well to get php to parse the file.
Alternatively, you can try somethign like what #NMO suggested, and retrieve this via AJAX.
Related
I'm trying to create a roulette system, which should work as follows: The user clicks on a submit button, which is then checked on the opening_case_handler.php file to see whether the user has sufficient funds in his account or not, and if he does it will echo javascript code which will create the animation for the roulette and will also come out with the winning prize. For security purposes I am executing the js code in php so the user has no access to it since it is executed in the server side.
The issue here is that the js and jquery code do not get executed once this line of code has been reached:
var gw = $(".gift").outerWidth(true);
in the opening_case_handler.php.
You will notice that there are two alerts before and after the previous line code I have just mentioned. If I uncomment alert("TEST1") it will get executed and an alert message will appear however the rest of the code will no be executed. Also if I uncomment only the alert("TEST2") it will not be executed and nothing will happen.
To make sure that the javascript code actually works. I previously tested it in a javascript file and sourced it in the index.php file and it worked perfectly.
index.php
This page contains the roulette with all the different images of each item. The submit button is at the bottom. This is the button that users will click to be able to spin the roulette.
<div class='rafflebox'>
<div class='pointer'></div>
<div class='boxwrapper'>
<ul class='giftwrapper'>
<div class="gift item bg-size2 box-bg3">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
<div class="gift item bg-size2 box-bg2">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
<div class="gift item bg-size2 box-bg3">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
<div class="gift item bg-size2 box-bg4">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
</ul>
</div>
</div>
<form method="post">
<button type="submit" name="opening_case" class="btn open-box-btn btn-openbox-font button"><img id="lock" src="graphics/iconos/Candado Cerrado Black.png">ABRIR CAJA</button>
</form>
</div>
opening_case_handler.php
<?php
session_start ();
if(isset($_POST['opening_case']))
{
opening_case ();
}
function opening_case ()
{
if ($_SESSION['balance'] >= $_SESSION['box price'])
{
echo '
<script>
//alert("TEST1");
var giftamount = 10;
var gw = $(".gift").outerWidth(true);
//alert("TEST2");
var giftcenter = gw/2;
var cycle = 7;
var containercenter = $(".boxwrapper").outerWidth(true)/2;
for(var i = 0; i <=5; i++)
{
var giftduplicate = $(".giftwrapper").children().clone(true,true);
$(".giftwrapper").append(giftduplicate);
}
$(".button").click(function()
{
alert("You DO have sufficient funds");
var btn = $(this);
btn.hide();
var randomgift = Math.floor(Math.random() * 4) + 1;
var dev = Math.random()*(giftcenter+1);
var distance = giftamount * cycle * gw + (randomgift*gw) - containercenter -24 +dev;
console.log(distance);
$( ".giftwrapper" ).css({left: "0"});
$(".giftwrapper").animate({left: "-="+distance},10000,function()
{
alert("You Won Gift" + randomgift);
btn.show();
});
});
</script>';
} else {
//to be done
}
}
?>
Please feel free to express your ideas on how this type of system should be better built. I am open to all suggestions, I am fairly new to this.
Thank you!!
Try using Heredoc string quoting example for printing your JavaScript:
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
Heredoc text behaves just like a double-quoted string, without the
double quotes. This means that quotes in a heredoc do not need to be
escaped, but the escape codes listed above can still be used.
Variables are expanded, but the same care must be taken when
expressing complex variables inside a heredoc as with strings.
If it is just a php code file. You can try some below.
<?php
echo "some stuff here"
if ($condition){ ?>
<script>
alert("condition true");
</script>
<?php } else { ?>
<script>
alert("condition false");
</script>
<?php }?>
When a form gets submitted it redirects you to the PHP page (ie when you click submit in index.php you will get redirected to opening_case_handler.php ) and then the PHP page will send you back to the index page with the new info. Thus, your javascript code gets printed in the opening_case_handler.php which is why your javascript did not get executed. Also, your javascript code will always be visible unless if you do something really creative so if you are trying to handle any sensitive information do it in PHP or any backend framework you are using.
There are ways to fix this issue but I would recommend a different approach to solve this issue. You can use an AJAX request which basically works in the following manner:
You send a request to your PHP server with the data you want to send.
Your PHP server will process the request and send it back to you
Your Javascript code will process the result and show the animations
or whatever you want to do.
This way your algorithm is not shown and your client ( the javascript side ) only handles information entered by the user and the results came from the server.
In your case, we can do that using the following changes
Index.php (which can be changed to index.html now)
<button type="submit" id="opening_case" name="opening_case" class="btn open-box-btn btn-openbox-font button"><img id="lock" src="graphics/iconos/Candado Cerrado Black.png">ABRIR CAJA</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#opening_case").on("click", ()=>{
// $.get( "opening_case_handler.php?opening_case=true", function( data ) {
// console.log(data.funds)
// });
$.ajax({
url: "opening_case_handler.php?opening_case=true",
success: (data)=>{
if(data.funds) {
alert("You DO have sufficient funds")
} else {
("You don't have sufficient funds")
}
},
dataType: "JSON"
});
})
</script>
opening_case_handler.php
<?php
if(isset($_GET['opening_case'])) {
$result = [
"funds" => true,
];
$ResultsInJSON= json_encode($result);
echo $ResultsInJSON;
}
?>
The index.php will send the request when the button is clicked using AJAX which you can read about it here https://api.jquery.com/jquery.get/ then your PHP will receive the request and response with a JSON code which can be processed using the data.whatever as shown in the example above.
Note: I am not a PHP expert but I believe this will be a better method to use in this case.
Note2: You don't need Jquery for Ajax but it's easier! Here is how you do it without Jquery https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
I am new to this forum. I have been developing a interface and have got stuck with PHP and Javascript.
My Site has 3 Buttons
<button id="ProjectSource" class="testbutton" onClick="AddNewProject(this.id);">Project Source</button>
<button id="SelfCons" class="testbutton" onclick="AddNewProject(this.id)">Self Cons</button>
<button id="Currency" class="testbutton" onclick="AddNewProject(this.id)">Currency</button>
These buttons are sent to a Javascript function on the same page which will store the button ID in a variable, which is later used in another PHP.
Now I have an Select Box in the same page and I get the data from the database using PHP.
<select size="10" id="Database" onClick="ClearAdd()" >
<?php
while($row = mysql_fetch_assoc($get))
{
?>
<option value = "<?php echo($row['ProjectSource'])?>" >
<?php echo($row['ProjectSource']) ?>
</option>
<?php
}
?>
</select>
My First Problem is
If you see I am currently using $row['ProjectSource']), But what I need is the ID of the buttons which corresponds to the field name in the database.
My Second Problem is
The Select functions loads when the page loads, I want that to refresh when I click on any buttons.
Thanks in Advance for your help!
use mysql fetch query
For example:
while ($row = mysql_fetch_assoc($query)){
$id = $row['id'];
}
For your second Problem you should implement ajax. Either using javascript or jquery.
Regarding first problem it is not clear What are the field names and how button Id is implemented? It would be better if you post some code
Can you implement some kind of mapping of your fieldName to your buttonId using associative array? like array("fieldName1"=>"id1",....)
I'm working on a hobby project (usually working as a designer, so not all that familiar to php – please have oversight with all or any redundant code), trying to learn new things. Now I've bumped into a problem that I don't quite seem to get the hang of.
I have an index.php used to display random sentences from data.php, this works fine – however I want to be able to sort out specific types of sentences for different people if necessary. This is done with a dropdown containing Designer, Illustrator and Developer.
If for example you choose Developer from the dropdown menu, the page reloads with index.php?yrke=developer in the URL as a result. This is all fine and as expected, and when i echo $_GET['yrke']; from data.php it displays the text "developer" fine the first load, but upon clicking the randomizerButton button (note that the content is loaded from data.php without refreshing the page in the browser when clicking this button) $_GET['yrke']; does not seem to be able to get a read on the value in the url (putting $_GET['yrke']; in index.php obviously works regardless, but I need to access the url variable in data.php).
If there's a way to do this while maintaining the "update-content-without-browser-refresh" function that'd be awesome, the other easiest solution would perhaps be to remove said "update-content-without-browser-refresh" and go for good old refreshes and thus solving the problem – but why make it that easy right?
index.php (excerpt)
<button data-href="data.php" class="randomizerButton">Randomize sentences</button>
<form action="index.php" method="get">
<select name="yrke" onchange="this.form.submit()">
<option value="designer"<?=$_GET['yrke'] == 'designer' ? ' selected="selected"' : '';?>>Designer</option>
<option value="illustrator"<?=$_GET['yrke'] == 'illustrator' ? ' selected="selected"' : '';?>>Illustrator</option>
<option value="developer"<?=$_GET['yrke'] == 'developer' ? ' selected="selected"' : '';?>>Developer</option>
</select>
</form>
<?php include('data.php'); ?>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('button.randomizerButton').click(function(){
scriptUrl = $(this).attr('data-href');
$.post(scriptUrl, function(response){
$('#results').html(response);
});
});
});
</script>
data.php (excerpt)
echo $_GET['yrke'];
If you want $_GET['yrke'] on data.php you would have to use $.get() and just use the full URL, like:
$.get('data.php?yrke='+encodeURIComponent($('[name=yrke]').val()), function(response){
$('#results').html(response);
}
I would use
$.post('data.php', {yrke:encodeURIComponent($('[name=yrke]').val())}, function(response){
$('#results').html(response);
}
with $_POST['yrke'] on data.php. Usually, I would not have a form that submits in the traditional manner. It's all about the AJAX.
Not sure if this will help but you could do something like this...
<div id ="content">
<?php
$pages_dir ='pages';
if(!empty($_GET['p'])){
$pages =scandir($pages_dir, 0);
unset($pages[0], $pages[1]);
$p = $_GET['p'];
if (in_array($p.'.inc.php', $pages)){
include($pages_dir.'/'.$p.'.inc.php');
}else {
echo'Page not found';
}
}else{
include($pages_dir.'/home.inc.php');
}
?>
HERE
</div>
Make a folder called pages then name the files within the folder "aboutus.inc.php" ect. the important part of the file extension is .inc.php , you can name anything before .inc.php anthing you like here is an example of how to write the navigation "About us"
IF need be I can send you a blank template
On my path of slowly learning PHP I've decided to work on a dynamic drop down box to create a little find-a-product application for the small company I work for. I took a day to read examples others have put out of their dynamic drop down boxes and decided the method posted on CSS-Tricks was clean and efficient enough.
The problem I'm having is that the Javascript I'm using doesn't seem to be parsing and returning what I want it to. The MySQL query its supposed to build works as expected when I query my database directly (through Heidi) as well as when I load the script directly (explained at the bottom), but using JQuery to pass options through the script doesn't seem to work.
This is the main page with dropdown I'm using to test/build the script
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$("#type").change(function() {
$("#range").load("dynoptions.php?type=" + $("#type").val());
}).trigger("change");
</script>
</head>
<body>
<select id="type">
<option selected value="base">Please Select</option>
<option value="FM800">FM800</option>
<option value="FS100">FS100</option>
</select>
<br>
<select id="range">
<option>Please choose from above</option>
</select>
</body>
When the state of my first dropdown changes the javascript should be sending information to my PHP and receiving html to inject into the second dropdown.
And this is the PHP:
<?php
//creates DB connection
$dbHost = 'localhost';
$dbUser = 'foxmeter';
$dbPass = 'foxmeter';
$dbDatabase = 'foxmeter';
$con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL Server. Error: " . mysql_error());
$result = array;
mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error());
//prevents injections
$choice = mysql_real_escape_string($_GET['type']);
//forms the query
$query = "SELECT DISTINCT sio FROM meters WHERE series='$choice' ORDER BY sio";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo "<option>" . $row{'sio'} . "</option>";
}
?>
You can test it live at new.foxmeter.com/dynamic.php
Also, new.foxmeter.com/dynoptionswithselect.php?type=FM800 is a version of the PHP script with
<select> and </select>
added before and after the script to test that the script is working (which it is).
Thanks!
The change() listener is never being called, probably because you're trying to register it before the DOM is ready.
What you need to do (and what is generally good practise with javascript) is make sure that the DOM is ready before you execute any script that relies on it.
There are a couple of ways of doing this - one is putting the script at the bottom of the page, but a better (safer) option is to use jQuery's document ready event handler:
$(document).ready(function(){
//your code here
});
The shorthand for which is:
$(
function(){
//your code here
}
);
So in your case:
<script>
$(function(){
$("#type").change(function() {
$("#range").load("dynoptions.php?type=" + $("#type").val());
}).trigger("change");
});
</script>
I'm trying to update the action property of the form tag by calling a JavaScript function when a user presses the submit button. The action property is updated depending on what is selected in the select box called "proceed". However the following script does not work and I don't know why.
Javascript:
<script type="text/javascript">
function updateAction() {
<?php
if (empty($errors) && isset($_POST['submit'])) {
echo 'document.newStudent.action = document.newStudent.proceed.value';
} else {
echo 'document.newStudent.action = "newStudent.php"';
}
?>
}
</script>
<form name="newStudent" method="POST" onsubmit="updateAction()">
Select box which is much further down in my code:
<?php //PROCEED
echo '<tr>';
echo '<td><p>Proceed To:</p></td>';
echo '<td>
<select name="proceed">
<option value="newSchedule.php">add student\'s schedule</option>
<option value="newStudent.php">add another student</option>
<option value="staff.php">staff page</option></td>';
echo '</tr>';
?>
You can not write PHP code inside a JavaScript method like that. You have to understand difference between server-side scripting and client-side scripting. In your scenario write a JS code which accomplish your task. Read this Client side vs server side basics, PHP vs JavaScript For Dynamic HTML Pages
Javascript and PHP allow website developers to create dynamic Web pages. Javascript is a client-side language, so it runs on the reader's computer. PHP is a server-side language, so it runs on the Web server. These two languages are combined to create interactive website's for readers. Each of these languages are combined, but they interact with the Web browser differently.
There are situation you can write PHP inside a Javascript function but not in your scenario.
Read More