You can’t use $_POST without using form, and if you don’t want to use form you can achieve by javascript check below code it will help you.
<script>
function viewRecipe(el)
{
var e = document.getElementById(el);
var strSel = e.options[e.selectedIndex].text;
alert(strSel);
}
</script>
<div id="result" class = "hide">
<select id = "selectIngredients">
<option>Choose a recipe</option>
<option value="Carrot">Carrot</option>
<option value="Cabbage">Cabbage</option>
<option value="Broccoli">Broccoli</option>
</select>
<button onClick="viewRecipe('selectIngredients');">Get Selected Item</button>
</div>
You cannot send a post request without a form in html but you can do it in
javascript/ajax.
here is $_POST
example:
function viewRecipe(){
var e = document.getElementById('selectIngredients');
var strSel = e.options[e.selectedIndex].text;
var req = new XMLHttpRequest();
req.open('POST', "pageName.php", true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send('selectIngredients='+strSel);
req.onload = function() {
var res=req.response;
alert(res);
}
}
PHP code:
if(isset($_POST['selectIngredients'])){
$selected_val = $_POST['selectIngredients'];
echo "You have selected :" .$selected_val;
}
if you are sending request to same page here is $_GET
Method example.
function viewRecipe(){
var e = document.getElementById('selectIngredients');
var strSel = e.options[e.selectedIndex].text;
window.location.href = window.location.pathname+"?selectIngredients="+strSel;
}
Let me know if you face any error. 😀
I have the following snippet from HTML:
<div id="result" class = "hide">
<select id = "selectIngredients">
<option>Choose a recipe</option>
<option value="Carrot">Carrot</option>
<option value="Cabbage">Cabbage</option>
<option value="Broccoli">Broccoli</option>
</select>
<button class="btn" onClick="viewRecipe()"> View Recipe</button>
</div>
I am trying to use some PHP to get the value chosen when the button is clicked. Is this possible without having it in a form?
When I do the following it isn’t working.
$selected_val = $_POST['selectIngredients']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val; // Displaying Selected Value
}
I want to use this value to go into a string I’m using in PHP so would this work with jquery? Example: “` $newString = “StringOne”.$selected_val.”StringTwo”;“`
@beingprabhu its just a function which is showing a recipe which works fine.
To display the selected option from the select box you can use the JS on change event.
I want to get the selected value but then I want to assign it to a PHP variable to have it be in a request to an API with a URL in PHP