$_POST Not Showing Current Option - javascript

My code is meant to take input text and generate an output for it using PHP via AJAX. While $_POST["inputText"] is set $_POST["style"] isn't set. How can I modify my code to set $_POST["style"] to the current option (a, b or c)?
functions01.php is any generic PHP file that takes $_POST["inputText"] and $_POST["style"] echos out an appropriate output.
foo1.php
<!DOCTYPE html>
<html>
<body>
<!-- Input -->
<div class="form">
<form onsubmit="makeRequest(); return false">
<input type="text" id="inputText" name="inputText">
<select name="style">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
<input type="submit">
</form>
</div>
<br>
<!-- Output -->
<div class="txtBox">
<textarea id="txtBox">
</textarea>
</div>
<!-- AJAX to create output using function01.php file-->
<script>
function makeRequest() {
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
document.getElementById("txtBox").innerHTML = httpRequest.responseText;
};
httpRequest.open("POST", "functions01.php", true);
httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
httpRequest.send("inputText=" + document.getElementById("inputText").value);
}
//function
</script>
</body>
</html>

HTML
<select name="style" id="ddlStyle">
JS
var inputVal = document.getElementById("inputText").value;
var e = document.getElementById("ddlStyle");
var styleVal = e.options[e.selectedIndex].value;
...
httpRequest.send("inputText=" + inputVal + "&style=" + styleVal );

Related

Transfer data between JavaScript and PHP through JSON

index.html:
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method="post" class="set-currency">
<div class="usd">
<label for="usd">USD</label>
<input type="number" name="usd" id="usd">
</div>
<div class="eur">
<label for="eur">EUR</label>
<input type="number" name="eur" id="eur">
</div>
<div class="gbr">
<label for="gbr">GBR</label>
<input type="number" name="gbr" id="gbr">
</div>
<button type="sumbit" class="submit-rates" name="submit-rates">Set Rates</button>
</form>
<br>
<form method="post" name="exchange-currency">
<div class="needed-currency">
<label for="needed">Needed currency</label>
<select name="needed" id="needed">
<option value="usd">USD</option>
<option value="eur">EUR</option>
<option value="gbr">GBR</option>
<option value="uan">UAN</option>
</select>
</div>
<div class="base-currency">
<label for="base">Base currency</label>
<select name="base" id="base">
<option value="usd">USD</option>
<option value="eur">EUR</option>
<option value="gbr">GBR</option>
<option selected="selected" value="uan">UAN</option>
</select>
</div>
<div class="converted-currency">
<label for="amount">Amount:</label>
<input type="number" id="amount" name="amount">
<label for="calculated">Converted</label>
<input type="number" id="calculated" name="calculated">
<button type="sumbit" name="convert">Convert</button>
</div>
</form>
<script src="script.js"></script>
</body>
</html>`
script.js:
window.addEventListener("load", function () {
console.log("php es una mierda");
let rates = {};
// document.querySelector(".submit-rates").addEventListener("click", function () {
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
rates = JSON.parse(this.response);
}
};
xmlhttp.open("GET", "converter.php", true);
xmlhttp.send();
// })
})
converter.php:
<?php
if (isset($_POST['submit-rates'])):
$usdRate = (int)$_POST['usd'];
$eurRate = (int)$_POST['eur'];
$gbrRate = (int)$_POST['gbr'];
// echo "$usdRate $eurRate $gbrRate";
endif;
$rates = [
"usd" => $usdRate,
"eur" => $eurRate,
"gbr" => $gbrRate];
echo json_encode($rates);
file_put_contents("./rates.json", json_encode($rates));
?>
I have to do a currency converter where a user sets the rates, using JavaScript and PHP.
I decided to transfer data through JSON, and it works like this:
the whole thing console logs: {"usd":null,"eur":null,"gbr":null} and when I press "Set Rates" button, nothing changes.
how can I transfer the data with rates properly?
no estas usando json para usar json debes adicionar la libreria jquery
you are not using Json, if you wanna use Json, you should add jquery library
html
<!-- change your button -->
<button type="button" onclick="registroModificacion()">Convert</button>><
<!-- add at the end of yout page. you have to use jquery library -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js" ></script>
<script>
function registroModificacion(){
//get values of your form by id
const needed = $('#needed').val();
const usd= $('#usd').val();
$.ajax({
url:'paginaEn.php',
type:"POST",
data: {needed:needed,usd:usd},
success:function(r){
alert(r);
},
})
}
</script>
paginaEn.php
<?php
$usd= $_POST['usd'];
$needed= $_POST['needed'];
echo $needed." ".$usd;
?>

I cannot get CallBack / Javascript Api

Currently I am working on Translate App ( Via Yandex Api );
I have one problem that I could not understand...
If Someone would help me with it;
I'd be very happy.
So Here is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Translator App</title>
<link rel="stylesheet" type="text/css" href="style.css">
<!--jQuery CDN-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<section class="main">
<div class="header">
<h1>Welcome to Translator</h1>
<h2>Translate in English,Spanish,German,Turkish</h2>
<div class="language">
<div class="languageto">
<select class="firstlanguages" name="languages" id="langs">
<option value="en">English</option>
<option value="tr">Turkish</option>
<option value="de">German</option>
<option value="sp">Spanish</option>
</select>
</div>
<div class="tolanguage">
<select id="tolanguage" name="tolanguage">
<option value="toeng">Turkish</option>
<option value="totr">English</option>
<option value="tode">German</option>
<option value="tosp">Spanish</option>
</select>
</div>
</div>
<form id="translate-form">
<div class="translate">
<textarea class="firstmsj" name="word" placeholder="Maximum 500 Character" id="word" value="Nasılsın"></textarea>
<textarea class="secondmsj" name="message" disabled placeholder="Your Translate"></textarea>
</div>
<input class="translatebtn" type="submit" value="Translate">
</form>
</div>
</section>
<script src="js/translate.js"></script>
<script src="js/app.js"></script>
</body>
</html>
And I have 2 Different JS files ;
First is App.js
eventListeners();
function eventListeners(){
let form = document.getElementById("translate-form");
form.addEventListener("submit", translateWord);
document.querySelector('.firstlanguages').onchange = function(){
//Arayüz işlemleri
}
}
let word = document.getElementById("word").value;
let lang = document.getElementById("langs").value;
const translate = new Translate(word,lang);
function translateWord(e){
translate.translateWord();
e.preventDefault();
}
Second javascript file is Translate.js
function Translate(word,language){
this.apikey = "trnsl.1.1.20200430T094119Z.fcb3cffaccaa7301.9f383b774f2aaea42d9be57e8799a3310f7074c1";
this.word = word;
this.language = language;
// XHR Object
this.xhr = new XMLHttpRequest();
}
Translate.prototype.translateWord = function(){
// Ajax Works
const endpoint = `https://translate.yandex.net/api/v1.5/tr.json/translate?key=${this.apikey}&text=${this.word}&lang=${this.language}`;
this.xhr.open("GET",endpoint);
this.xhr.onload = () =>{
if(this.xhr.status === 200){
console.log(this.xhr.responseText);
}else{
console.log("Hata");
}
}
this.xhr.send();
};
The mistake is , whenever I submit it;
The error message is ;
translate.js:28 GET https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20200430T094119Z.fcb3cffaccaa7301.9f383b774f2aaea42d9be57e8799a3310f7074c1&text=&lang=en 400 (Bad Request)
and when we see the link we cannot see ${this.word} is placed in my URL.
When I check the code after submit, also xhr.send() has been red...
this.xhr.send();
Except that everything works perfectly so far.
What could be the issue?
Thank you for your help!
You are getting an empty this.word because you are instantiating the Translate object out of the event handler:
const translate = new Translate(word,lang);
Initially, the input is empty, hence the blank space in this.word.
Solution: move the variables and instantiate inside the translateWord handler, so that they get updated on each search.
function translateWord(e){
let word = document.getElementById("word").value;
let lang = document.getElementById("langs").value;
const translate = new Translate(word,lang);
translate.translateWord();
e.preventDefault();
}
You will see, now it responds with 200 and the corresponding JSON data.

Showing Div Not Working On Select Using Javascript

I am trying to show the FILE DIV if the user selects the doctor value in the select statement. I know the if statement works because I also print the value in the console which works perfectly fine. I toggle my divs in the same exact manner in my other webpages so I'm not understanding what's going on with this one in particular.
function viewFile(){
var file = document.getElementById("doclicense");
var type = document.getElementById('accountType').value;
if(type === 'doctor') {
file.style.display = "block";
console.log(type);
}
}
.hidden{
display : none;
}
<div>
<select id="accountType" name="type" class="form-control" onchange="viewFile()">
<option required>Account Type</option>
<option value="doctor" name="doctor" id="doctor">Doctor</option>
<option value="regular" name="regular" id="reg">Regular Account</option>
</select>
</div>
<div class="hidden file" id="doclicense">
<input type="file" name="license" />
<input type="submit"/>
</div>
****************************************EDIT-WORKAROUND**********************
Since my code refused to work, I added a line of code with 'head' being the title and not a real value. Thanks to everyone who contributed. I took out the hidden class altogether but when I add it, it still doesn't work correctly.
function viewDocFile() {
var file = document.getElementById("doclicense");
var type = document.getElementById('accountType').value;
if (type === 'regular' || type === 'head') {
file.style.display = "none";
console.log(type);
} else {
file.style.display = "block";
console.log(type);
}
}
***************************FINAL-EDIT************************
Kept the original code, but added the CSS inline.
<div class="form-group col-md-6" id="doclicense" style="display:none;">
Works perfectly now.
Here is an example of how this code should be written (even if there are still horrors)
// declare them here and not in a function where they will be redone each time the function is called
const
file_IHM = document.querySelector('#doclicense')
,
type_IHM = document.querySelector('#accountType') // and not with .value ...!
;
type_IHM.onchange = function()
{
file_IHM.style.display = (this.value==='doctor')?"block":"none";
console.log('type_IHM.value', this.value );
}
#doclicense { display : none; }
<div>
<select id="accountType" name="type" class="form-control" > <!-- let the js in the js part -->
<option required>Account Type</option>
<option value="doctor" id="doctor" >Doctor</option>
<option value="regular" id="regular" >Regular Account</option>
</select>
</div>
<div class="file-class" id="doclicense"> <!-- do not use class="hidden... -->
<input type="file" name="license" />
<input type="submit" /> <!-- there is no form anywhere... why don't you use <button> ?? -->
</div>
If that what your code really looks like, did you add your js in a <script></script> tag?
Or do you want to toggle the hide and show of the div?
if so this answer may help
<select id="accountType" name="type" class="form-control" onchange="viewFile()"><option required>Account Type</option>
<option value="doctor" name="doctor" id="doctor">Doctor</option>
<option value="regular" name="regular" id="reg">Regular Account</option>
</select>
</div>
<div class="hidden file" id="doclicense">
<input type="file" name="license" />
<input type="submit"/>
</div>
<script>
function viewFile(){
var file = document.getElementById("doclicense");
var type = document.getElementById('accountType').value;
if(type === 'doctor') {
file.style.display = "block";
console.log(type);
}else{
file.style.display = "none";
console.log(type);
}
}
</script>

How to Show selected value on textbox using javascript?

How can I show the value of the selected items in the textbox using javascript?
// MY LIST
<select id="list" class="form-control" multiple="">
<option value="2014">Your Cute</option>
<option value="2013">Your Ugly</option>
<option value="2011">Your Awesome</option>
</select>
// BUTTON and TEXTBOX
<button onclick="show_value();" type="button" value="Get Value">Get Value</button>
<input type="text" id="selectedvalue" class="text" name="selectedvalue" />
I came up with this javascript code
function showgroup_id () {
$('#selectedvalue').val(selectedvalue);
var myList = document.getElementById('list');
var selected-value = selectedItem;
var selectedGroupIds = [];
for (var i = 0; i < myList.length; i++) {
if (myList[i].selected) {
selectedselectedItem.push(myList[i].value);
}
}
}
When I tried, it doesn't work.. anyone can help me please?
You can use onchange event to change the textbox content with changing select element.
HTML :
<select id="selectBox">
<option>A</option>
<option>B</option>
</select>
<input type="text" id="messageTextBox" />
javaScript :
var selectBox = document.getElementById("selectBox");
selectBox.onchange = function(){
var textbox = document.getElementById("messageTextBox");
textbox.value = this.value;
};
jsFiddle
Your Solution :
HTMl :
<select id="list" class="form-control" multiple="">
<option value="2014">Your Cute</option>
<option value="2013">Your Ugly</option>
<option value="2011">Your Awesome</option>
</select>
// BUTTON and TEXTBOX
<button onclick="showgroup_id();" type="button" value="Get Value">Get Value</button>
<input type="text" id="selectedvalue" class="text" name="selectedvalue" style="width: 55%;" />
javaScript/jQuery :
function showgroup_id () {
var result = "";
var selectedItem = $('#selectedvalue').val(selectedvalue);
var myList = document.getElementById('list');
var selectedValues = selectedItem;
var selectedGroupIds = [];
for (var i = 0; i < myList.length; i++) {
if (myList[i].selected) {
//selectedselectedItem.push(myList[i].value);
//alert(myList[i].text);
result = result + " " + myList[i].text;
$("#selectedvalue").val(result);
}
}
}
jsFiddle
Try this :
give some id to button and remove onclick
<button id="getValue" type="button" value="Get Value">Get Value</button>
bind onclick event to button as shown below
$('#getValue').click(function(){
var text = $('#list option:selected').text();
$('#selectedvalue').val(text);
});
Try this,
<html lang="us">
<head>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.js"></script>
<script>
function show_value()
{
$("#selectedvalue").val($("#list").val());
}
</script>
</head>
<body>
<select id="list" class="form-control" multiple="">
<option value="2014">Your Cute</option>
<option value="2013">Your Ugly</option>
<option value="2011">Your Awesome</option>
</select>
// BUTTON and TEXTBOX
<button onclick="show_value();" type="button" value="Get Value">Get Value</button>
<input type="text" id="selectedvalue" class="text" name="selectedvalue" style="width: 55%;" />
</body>
replace your javascript code with the following:
function show_value() {
document.getElementById("selectedvalue").value = document.getElementById( "list" )[ (document.getElementById( "list" )).selectedIndex ].text;
}
The show_value() function will be called when the button is clicked. Inside the function, I have set the value of the textbox with the value of the select list.
function show_value()
{
$("#selectedvalue").val($("#list").val());
}

Create a link based on values from a Html form and redirect them to it

What I'm trying to do is to redirect people to a link depending of what they have summited on the form (the link is built using the values from the form fields)
This is the Form:
<form id="form">
<div class="formbox">
<div class="radio-toolbar">
<input type="radio" id="iconapp1" name="department" value="1250"/>
<label for="iconapp1">PP</label><br>
<input type="radio" id="iconapp2" name="department" value="944"/>
<label for="iconapp2">EP</label><br>
</div>
<div class="radio-bar1">
<input type="radio" id="enginemake1" name="enginemake" value="6"/>
<label for="enginemake1"> Chevrolet</label><br>
<input type="radio" id="enginemake2" name="enginemake" value="8"/>
<label for="enginemake2"> Chrysler</label><br>
</div>
<div class="bodyvertdivision1"></div>
<div class="radio-bar3">
<select name="powerrange">
<option id="powerrange1" value="28">100</option>
<option id="powerrange2" value="128">200</option>
<option id="powerrange3" value="228" selected>300</option>
</select>
</div>
<div class="bodyvertdivision1"></div>
<div class="radio-bar4">
<input type="radio" id="location1" name="location" value="store"/>
<label for="location1"> America (NT - ST)</label><br>
<input type="radio" id="location2" name="location" value="store.au"/>
<label for="location2"> Australia and Oceania</label><br>
</div>
<div class="radio-bar2">
<input onclick="goToPage();" type="button" class="buttonmyapp" value="Submit" />
</div>
</div>
</form>
The link I'm trying to build using the values selected will look like this:
http://{location}.mydomain.com/product-catalog.aspx?section=-{department}-{enginemake}-{powerrange}-
Each bracketed section needs to be replaced by the value of the select with the corresponding name.
First include the jquery library link or download js and link
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
function goToPage(){
var location = $('input[name=location]:checked').val();
var department = $('input[name=department]:checked').val();
var enginemake = $('input[name=enginemake]:checked').val();
var powerrange = $('select[name=powerrange]').val();
window.location.href = "http://"+location+".mydomain.com/product-catalog.aspx?section=-"+department+"-"+enginemake+"-"+powerrange+"-";
}
</script>
After the goToPage function on the submit button validates the response change the src attribute of the form should work fine.
So in jQuery it should look something like
var location = $('input[name=location]:checked', '.radio-bar4').val();
var dept = $('input[name=location]:checked', '.radio-bar4').val();
var engine = $('input[name=enginemake]:checked', '.radio-bar1').val();
var power = $('powerrange').val() ;
var domain = "http://"+ location+".mydomain.com/product-catalog.aspx?section=-"+dept+"-"+engine+"-"+power+"-";
$("#form").attr("action", domain);
you can try this
HTML
<select id="powerrange" name="powerrange">
JAVASCRIPT
function goToPage()
{
var location;
var department;
var enginemake;
var powerrange;
pName = document.getElementById('powerrange');
powerrange = pName.options[pName.selectedIndex].value;
var form = document.getElementById('form');
var ele = form.getElementsByTagName('input');
for(var i=0;i<ele.length;i++)
{
if(ele[i].getAttribute('type')=='checkbox')
{
if(ele[i].getAttribute('name')=='department')
{
if(ele[i].checked)
department = ele[i].value;
}
else if(ele[i].getAttribute('name')=='enginemake')
{
if(ele[i].checked)
enginemake = ele[i].value;
}
else if(ele[i].getAttribute('name')=='location')
{
if(ele[i].checked)
location = ele[i].value;
}
else;
}
}
var url = "http://"+ location+".mydomain.com/product-catalog.aspx?section=-"+department+"-"+enginemake+"-"+powerrange+"-";
form.setAttribute('action',url);
form.submit();
}

Categories