How do I output php code in a js innerhtml? - javascript

I have a dropdown field and a text field in my form.
Whenever a user presses a button, I want it to show both fields twice.
I'm doing the js part with an innerHTML and I want to output the php include to the file with the code for both fields. Now for some reason, I can't output php code with innerHTML.
Can someone explain why and how I can solve it. The file with the code for the fields has PHP and sql in it, so I can't just put the code in "" after the innerHTML.
function addInput()
{
var boxName='textBox'+countBox;
document.getElementById('stops').innerHTML+="<?php include'arrivalField.php;'?>";
countBox += 1;
}
When I press the button with the code like this, nothing happens. If I change the innerHTML="" thing to "Hello, world" it does work. It's specifically because it's PHP.
arrivalField.php contains
<div class='dropdown'><label for='pwd'>Vehicle:</label><select name='vehicle' id='vehicle' class='form-control'>
<?php
//For each car that user has, add it to the top of the dropdown.
$fetchCars = 'SELECT idCar, brandName, modelName FROM car WHERE idAcc = \''.$_SESSION[UserID].'\'';
$cars = $conn->query($fetchCars);
if(!empty($cars)){
$row = mysqli_fetch_array($cars);
foreach ($cars as $car) {
echo '<option class=\'dropdown-item\' value=\'Car\'.$car[idCar].\'>'.$car[brandName].' '.$car[modelName].'</option>';
}
}
?>
<option class='dropdown-item' value='Bicycle'>Bicycle</option>
<option class='dropdown-item' value='Long-distance bus'>Long-distance Bus</option>
<option class='dropdown-item' value='City bus'>City bus</option>
<option class='dropdown-item' value='Plane'>Plane</option>
<option class='dropdown-item' value='Train'>Train</option>
<option class='dropdown-item' value='Foot'>Foot</option>
<option class='dropdown-item' value='Subway'>Subway</option>
<option class='dropdown-item' value='Tram'>Tram</option>
</select>
</div>
<br>

First of all, I guess you not fully understand, that PHP executes strictly before javascript, and in your situation, you try to generate js code from PHP. Therefore it's very important to put this code in the right place. I mean, for example, if you put this code to the .js file it will not be preprocessed with PHP (with default server configuration). It may be essential.
Secondly, it's very important to understand, that the output of your PHP code must be specially prepared to will be compatible with js syntax. For example, if your PHP code outputs double quote (") it may be a problem, so you will get js syntax error. You can check this by using the client js debugger.

Related

is there a way to show command only after the option is selected in php

I can't figure out on how to put the selected code after it has selected the option.
I am using laravel, but i dont think it has to do with laravel framework...
<select id="idjenisuniform" name="idjenisuniform" style="width: 100%;">
<option value=""></option>
#foreach($idjenisuniform as $g)
<option value="{{$g->id}}" >{{$g->badanuniform}}</option>
#endforeach
</select>
(the idjenisuniform is from the controller, it works), but I just don't know how to do it after it has done choosing from the option.
Example
it chooses police -> the id is 1
I want to make:
if the option from it is 1, then it will display other option to show what group is he in. For example detective.
In conclusion I am trying to make a select option and after it has choose it, it will proceed to the next select option corresponding to the previous id from option.
please help.
Since you are wanting an effect that depends on user interaction, it would be better to use javascript for the effect you want. With php, the choice has to go all the way back to the web server to get processed, then the result is sent all the way back to the browser and the whole web page will refresh as a result. With javacript, everything happens in the browser.
But, you asked for a php solution, so here's the most simple way.
Say the first select element is named "select-one" and the second select element is named "select-two"
Create two forms. Notice that the second form has an ID.
[form action="/url/" method="whatever"]
[form id="other-form" action="/url/" method="post"]
In the main form (the one without an ID), place all your form elements. In addition, place another hidden element with the same name as the first select element ("select-one");
[form]
[input type="hidden" name="select-one"]
... all other elements
[/form]
Now when you add the first select element, give it a new attribute so that it is associated with "other-form" instead of the main form. Also, give it an ID.
[select id="select1" name="select-one" form="other-form"]
You DO have to add a bit of javascript, but it's not much. If you don't have any other javascript set up, just put this at the bottom of the web page, just above the [/body] tag.
[script]
const select1 = document.querySelector('#select1');
select1.addEventListener('change', (event) => event.target.form.submit());
[/script]
The javascript will submit the form which #select1 is associated with. Since we assigned the element to "other-form", that is the form that will get submitted.
For the php:
I haven't used Laravel in a very verly long time so I'll just give some vanilla php here.
$options_one = ['One', 'Two', 'Three'];
$options_two = [
'One' => ['Foo', 'Bar', 'Baz'],
'Two' => ['Boom', 'Bang', 'Bam'],
'Three' => ['Fee', 'Fie', 'Fo', 'Fum']
];
$select_one = (isset ($_POST['select-one']) ? $_POST['select_one'] : false;
// do some input validation
Now for the forms:
<form id="other-form" method="post" action = ""></form>
<form id="main-form" action="">
<input type="hidden" name="select-one" value="<?php echo $select_one ?>">
<!-- This element is assigned to "other-form" -->
<select form="other-form" name="select-one" id="select1">
<option value="">Select One...</option>
<?php foreach($options_one as $option) {
$option = ($select_one === $option) ? "<option selected>$option</option>" : "<option>$option</option>";
echo $option;
}?>
</select>
<select name="select-two">
<?php
$options = ["The first choice has not been selected"];
if (array_key_exists($select_one, $options_two)) {
$options = $options_two[$select_one];
}
foreach ($options as $option) {
echo "<option>$option</option>";
}
?>
</select>
<!-- other inputs in your form -->
</form>

Can anyone suggest some ideas for what I want to do here

I am quite well versed in developing in PHP, HTML5 and CSS3 however when it comes to Javascript and Jquery I'm totally lost.
What I'm looking at doing is on my site I want to place a custom page that allows the users to select certain options which will be specified by me.
pretty much along the lines of:-
Question1?
Select one of 2 options.
option 1 moves along to question 2
however where option 2 then moves to a different question.
what I would like to do instead is to use Javascript instead so it could be question 1 select answer, then question 2 automatically populates underneath. and then depending on that answer and so on, until the end is reached.
I will include a little snippet below so it helps visualise the end goal that I am looking for:-
<?php
$q1 = $_POST['q1'] ?? '';
$q2 = $_POST['q2'] ?? '';
?>
<?php
if(isset($_POST['q1] {
echo 'q2';
} else {
echo 'q20';
}
?>
The HTML would then be:-
<form name="script_path.ext" method="POST">
<span>Question 1?</span></br>
<select id="q1" name="q1">
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
<input type="submit" name="submit"
value="Next">
obviously it would be better to use Jquery to do this as the amount of variables are going to grow as questions get added and could become an infinite loop of if_statements.

PHP Javascript cant access echoed element id outside php mode

Humble appologies if this is a stupid question but I cant for the life of me figure out what is wrong here.
I have an echoed element inside php mode:
echo'<select name="picks" id="winner">';
echo'<option value="'.$row['team1'].'">'.$team1.'</option>';
echo'<option value="'.$row['team2'].'">'.$team2.'</option>';
echo'</select>';
Now outside php
I try to do a basic javascript GET:
document.getElementById("winner");
However the elemnt is not accessible am I missing something here, is it not possible to get echoed elements Ids?
You should make sure your DOM has at least loaded before performing element selects. If you can use jQuery, then this is as easy as the following, and you can place this script in the head section, or anywhere in the body:
$(document).ready(function() {
// Perform any selects on the DOM
});
JS
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
// The DOM is loaded and ready to be selected
var select = document.getElementById("winner");
var optionText = select.options[select.selectedIndex].text;
var optionValue = select.options[select.selectedIndex].value;
});
</script>
Of course you can also perform DOM selects using jQuery:
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
// The DOM is loaded and ready to be selected
var optionText = $("#winner option:selected").text();
var optionValue = $("#winner option:selected").val();
});
</script>
Another possibility
If $row, $team1 or $team2 are not defined and you have PHP errors and notices turned on, then the HTML will render like so:
<select name="picks" id="winner"><b>E_NOTICE : </b> type 8 -- Undefined variable: row -- at line 4<br /><b>E_NOTICE : </b> type 8 -- Undefined variable: team1 -- at line 4<br />
<option value=""></option><b>E_NOTICE : </b> type 8 -- Undefined variable: row -- at line 5<br /><b>E_NOTICE : </b> type 8 -- Undefined variable: team2 -- at line 5<br />
<option value="" selected="selected"></option>
</select>
However, if you have PHP errors and warnings turned off, you would see something like this instead:
<select name="picks" id="winner">
<option value=""></option>
<option value="" selected></option>
</select>
If you are unable to access the value of options in your select HTML (because they are empty), this would be a good pace to start investigating.
Using JQUERY you can try following:
// I have used mouse down event for demo purpose.
$(document).delegate('#winner', 'mousedown', function ()
{
alert('hi');
});
Try accessing the value of the selected id
I am giving a demo fiddle
Demo fiddle
document.getElementById("winner").value;
Echoing JS codes is common but there are these possibilities:
1-You put document.getElementById("winner"); before php creating that element.
2-There is a syntax error in script tag which cause error and there for your select does not work.
since the php part will be available before page load you can simply do like this:
<?php
$row['team1']=1;$team1='India';$row['team2']=2; $team2='SA';
echo'<select name="picks" id="winner">';
echo'<option value="'.$row['team1'].'">'.$team1.'</option>';
echo'<option value="'.$row['team2'].'">'.$team2.'</option>';
echo'</select>';
?>
<script>
console.log(document.getElementById("winner"));//see this in console.
</script>

can't get values form html select to php

i can't get values from the HTML select menu to js and from there to sql... the problem is in the JS code - it's probably caused by bad syntax... or misplace values.....
here is the varibles from the JS file
var select = $('select.select').val();
here is the varibles from the PHP file
$select = filter_var($_POST['select.value'],FILTER_SANITIZE_STRING);
here is the SELECT menu from the HTML file
<select name ="select" class="select">
<option disabled selected id="none"> -- select an option -- </option>
<option value="roy">roy</option>
here is the FULL code , the PHP code is in the Console area - because i didn't manage to upload the code correctly...
code
Thanks Ahead !
$_POST uses name="select", so:
$select = filter_var($_POST['select'],FILTER_SANITIZE_STRING);

Passing variable to a PHP page with Spaces

I have a select element as shown below.I am passing the value of the selected option to a PHP page as a variable with javascript as shown below :
<script>
var area1=document.getElementById("area").value;
$("#list").load("selectcity.php?city1="+city1+"&area1="+area1);
<script>
<select id="areas" name="areas">
<option value="Queens Town">Queens Town</option>
<option value="QueensTown">QueensTown</option>
</select>
Now the thing is , In the PHP page I am able to echo $_GET['area1']; when QueensTown is selected but whenever I am trying to pass Queens Town ,its now working.Can anybody help.
You have to escape the values properly, otherwise you would end up with a URL like this:
selectcity.php?city1=xyz&area1=Queens Town
Which is unlikely to work the way you want. Use this instead:
var data = {
city1: city1,
area1: $('#areas').val()
};
$('#list').load('selectcity.php?' + $.param(data));
See also: jQuery.param()

Categories

Resources