I have a dropdown list where users can select multiple options. I stored the selected options in a String variable in this format : [value of first selected option],[value of second selected option]...
Now i want to pass the value of this variable from my Javascript in file 1 to PHP variable in file 2 using Ajax. Here is my code
<!DOCTYPE html>
<head>
<title>test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="http://querybuilder.js.org/dist/selectize/dist/css/selectize.bootstrap3.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.js"></script>
</head>
<body>
<div class="container">
<form method="post" action="displayData.php" id="multiple_select_form">
<select name="columns" id="columns" class="form-control selectpicker" multiple>
<option value="Country">Country</option>
<option value="Customer Name">Customer Name</option>
<option value="Order Date">Order Date</option>
<option value="Address">Address</option>
</select>
</form>
<br>
<button class="btn btn-info center-block" id="btn-get">Submit</button>
</div>
</body>
</html>
<script>
$('#btn-get').on('click', function() {
var selectedOptions = [];
$.each($(".selectpicker option:selected"), function(){
selectedOptions.push("[" + $(this).val() + "]");
});
var myVar = selectedOptions.join(",");
$.ajax({
type: "POST",
url: 'displayData.php',
data: { testVariable : myVar },
success: function(data)
{alert(data);}
});
$("#multiple_select_form").submit();
});
</script>
I added alert(data) on success in my Ajax to see if the variable got the correct value. It's working but when form is submited and the displayData.php is loaded I get error Undefined index: testVariable
displayData.php is a simple test file
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$variable = $_POST['testVariable'];
print_r($variable);
?>
Can anyone explain me what can be the issue ? I believe that the Ajax is written correctly. Thank you for your help.
Try this
<!DOCTYPE html>
<head>
<title>test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="http://querybuilder.js.org/dist/selectize/dist/css/selectize.bootstrap3.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.js"></script>
</head>
<body>
<div class="container">
<form method="post" action="displayData.php" id="multiple_select_form">
<select name="columns" id="columns" class="form-control selectpicker" multiple>
<option value="Country">Country</option>
<option value="Customer Name">Customer Name</option>
<option value="Order Date">Order Date</option>
<option value="Address">Address</option>
</select>
<input type="hidden" name="testVariable" id="testVariable">
</form>
<br>
<button class="btn btn-info center-block" id="btn-get">Submit</button>
</div>
</body>
</html>
<script>
$('#btn-get').on('click', function() {
var selectedOptions = [];
$.each($(".selectpicker option:selected"), function(){
selectedOptions.push("[" + $(this).val() + "]");
});
$("#testVariable").val(selectedOptions.join(","));
$("#multiple_select_form").submit();
});
</script>
You're making two requests to displayData.php. One is an AJAX request, with the value set in a field called testVariable, and one is a normal form submit with the value set in a field called columns. The error is happening on the second request.
If your intent is to use AJAX, then remove the following code:
$("#multiple_select_form").submit();
You might even remove the <form> wrapper entirely, since you're identifying the elements directly and not really using the form itself for serialization or anything. (If you ever put a button inside the form it will automatically submit unless you explicitly handle the event to cancel that behavior.)
Conversely, if you do want to submit the form, then you can remove the JavaScript code entirely and move the submit button to be inside the <form> wrapper. And, of course, rename the form element to what your server-side code expects:
<select name="testVariable" ...
Related
Code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="/style.css">
</head>
<body>
<div class="container mt-4">
<h1 class="text-left" style="margin-bottom: 50px">Daily Fridge & Freezer Monitoring Record</h1>
<form action="/auth/21-TEMP-01b" method="post" id="form">
<div class="form-group">
<label>Select Fridge Or Freezer</label>
<select class="form-control" id="fridgeFreezer" name="fridge">
<option value="Fridge-1">Fridge 1</option>
<option value="Fridge-2">Fridge 2</option>
</select>
</div>
<div class="form-group fridges Fridge-1">
<h4>Fridge 1</h4>
<label>Temperature °C</label>
<input class="form-control" type="number" id="temperature-1" name="temperature-1">
<label>Comments</label>
<textarea class="form-control" rows="3" id="comments-1" name="comments-1"></textarea>
</div>
<div class="form-group fridges Fridge-2">
<h4>Fridge 2</h4>
<label>Temperature °C</label>
<input class="form-control" type="number" id="temperature-2" name="temperature-2">
<label>Comments</label>
<textarea class="form-control" rows="3" id="comments-2" name="comments-2"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select").change(function(){
$(this).find("option:selected").each(function(){
if($(this).attr("value")=="Fridge-1"){
$(".fridges").not(".Fridge-1").hide();
$(".Fridge-1").show();
}
else if($(this).attr("value")=="Fridge-2"){
$(".fridges").not(".Fridge-2").hide();
$(".Fridge-2").show();
}
else{
$(".fridges").hide();
}
});
})
.change();
var temp1 = document.getElementById('temperature-1');
var form = document.getElementById('form');
form.addEventListener('submit', function(e) {
if(temp1.value === '' || temp1.value == null) {
e.preventDefault()
document.querySelector('#fridgeFreezer [value="Fridge-1"]').selected = true;
alert("temp1 not fully filled")
}
})
});
</script>
</body>
</html>
Idea
I am trying to create form validation.
Running the above code details
You will see when you change the option in the drop down menu - different div element loads up. This is done through the jQuery code in the script.
Option 1
Option 2
Next, Javascript
I will be using Javascript to validate the form.
I only have started out validating the first div element of fridge 1. If value is empty I have an alert saying which input has not been filled.
In this scenario I have cleared out all data from Fridge 1 to run the if statement for the error.
Notice this line of code:
document.querySelector('#fridgeFreezer [value="Fridge-1"]').selected = true;
This re-selects the option to the one has the error.
But when I run it - this happens.
Div element of fridge-2 is still showing? How come is the jQuery not executing ?
You have to trigger a change event if you want the change event listener to execute.
form.addEventListener('submit', function(e) {
if(temp1.value === '' || temp1.value == null) {
e.preventDefault()
$('#fridgeFreezer').val("Fridge-1"); // can be simplified like this
$('#fridgeFreezer').trigger("change"); // important line
alert("temp1 not fully filled")
}
})
Here is a short form for selecting language for a webpage, There are two languages one is marathi and another is english actually what I want is like: when a user select english language and submit the form english.html page should open and
when user select marathi language marathi.html page should open.
<html>
<head>
<title>Select Language</title>
<link rel="icon" href="hen.png">
<form>
<center>
<p id="p1">
Language:<select>
<option id="English" >English</option>
<option id="Marathi" >Marathi</option>
</select>
</p>
<input type="submit" id="button" value="Open" >
</center>
</form>
</html>
You can use this as a reference, considering english.html and marathi.html as your targeting pages, you can change them accordingly
<html>
<head>
<title>Select Language</title>
<link rel="icon" href="hen.png">
<script>
$('#button').click(function() {
var selected = $('#language option:selected');
window.location.href = selected + ".html"
})
</script>
</head>
<body>
<form>
<center>
<p id="p1">
Language:
<select id="language">
<option id="English">English</option>
<option id="Marathi">Marathi</option>
</select>
</p>
<input type="submit" id="button" value="Open">
</center>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
I think its obviously, but please do not repeat it at production:
<input type="submit" id="button" onclick="window.locaton.href='lol/'+$('select').val()+'.html'" value="Open" >
Here is easy way;
<select name="forma" onchange="location = this.value;">
<option value="english.html">English</option>
<option value="marathi.html">Marathi</option>
</select>
if you want to create this using simple Javascript then use location.href = "yourPageAddress";
here is the sample code i have written for the same:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<script type="text/javascript">
function MyFunction(){
var getValue = document.getElementById("language");
//console.log(getValue);
var getIndexValue = getValue.options[getValue.selectedIndex].value;
//console.log(getValue.selectedIndex);
//console.log(getIndexValue);
if(getValue.selectedIndex == 1){
//console.log("English")
location.href = "http://www.google.com";
}
else if(getValue.selectedIndex == 2){
//console.log("Marathi");
location.href = "http://www.yahoo.com";
}
else{
console.log("Wrong Option Selected.");
}
}
</script>
</head>
<body>
Language:
<select name="language" id="language">
<option>Select..</option>
<option value="https://www.google.com" id="english">English</option>
<option value="https://www.yahoo.com" id="marathi">Marathi</option>
</select>
<br>
<button name="submit" id="submit" onclick="MyFunction()">Submit</button>
</body>
</html>
This is just the one way where you can redirect the user to selected page, there are many different ways also to execute the same operation.
You may find some console.log statement marked comment, which was just used for debugging purpose.
Script for date
<link href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#ui-datepicker').datepicker();
});
</script>
View
<form method="post" action="">
<select class='form-control' name='route_to' id='member' onchange='selectPackage()'>
<option value='packageSelect'>SELECT PACKAGE OPTION ....</option>
<option value='manakamanaPackage'>Mana</option>
</select>
<div id="displayForm3">
</div>
<script type="text/javascript">
function selectPackage() {
if (document.getElementById("member").value == "manakamanaPackage") {
document.getElementById("displayForm3").innerHTML = "<input type='text' id='ui-datepicker' class='form-control' />";
}
}
</script>
Explanation
If we use type="date" in the input field then it works only in google chrome browsers.
That's why to display calendar for all browsers we defined the script with id='ui-datepicker' , it works fine if we use for input field which will be normal input tag (such as :: < input type="date" />.
But it does not work for input field which is displayed inside of javascript function {selectPackage() as displayForm3}
The issue is because you're appending the element after the DOM loads. You need to instantiate the datepicker library on the new element, right after you create it. Try this:
<form method="post" action="">
<select class="form-control" name="route_to" id="member">
<option value="packageSelect">SELECT PACKAGE OPTION ....</option>
<option value="manakamanaPackage">Mana</option>
</select>
<div id="displayForm3"></div>
</form>
<script type="text/javascript">
$(function() {
$('#member').change(function() {
if (this.value == 'manakamanaPackage') {
$('#displayForm3').html('<input type="text" id="ui-datepicker" class="form-control" />');
$('#ui-datepicker').datepicker();
}
});
});
</script>
Note that I also amended your code to use an unobtrusive event handler as the on* event attributes are now considered outdated.
<!DOCTYPE HTML>
<html>
<head>
<title>Test</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<form>
<label>Seleziona l'ente</label>
<select name="data" id="data">
<option value="PRO - 011142764">COMUNE DI AGLIE'</option>
<option value="PRO - 011120674">COMUNE DI AGRATE CONTURBIA</option>
</select>
<input type="text" name="textfield" id="textfield" />
</form>
<script>
$('#data').change(function() {
$.post("richiesta.php", { value: this.value });
$('#textfield').val(this.value);
});
</script>
</body>
</html>
Here's my simple web page with 2 options. The input tag is just for testing the POST data.
Here's richiesta.php, that receives the POST data on change event (I followed this thread):
<?php
list($comparto, $ente) = explode("-", $_POST['data'], 2);
echo "comparto: $comparto, ente: $ente";
?>
Here's what happens when I trigger the change event (from Firebug).
POST is ok:
Unfortunately the response has empty variables ($comparto and $ente):
What's the problem with the explode/list function?
$_POST['data'] doesn't exist you send 'value' param, so use $_POST['value']
I'm not overly familiar with javascript, so I tend to lean towards my own ways of solving this. That said, I think this would accomplish what you are trying to do (without the need for your script near the bottom of your code):
<!DOCTYPE HTML>
<html>
<head>
<title>Test</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<form action="richiesta.php" method = "post">
<label>Seleziona l'ente</label>
<select name="data" id="data" onchange = "this.form.submit()" >
<option value="PRO - 011142764">COMUNE DI AGLIE'</option>
<option value="PRO - 011120674">COMUNE DI AGRATE CONTURBIA</option>
</select>
<input type="text" name="textfield" id="textfield" onchange="this.form.submit()" />
</form>
</body>
</html>
Note that this will cause the form to submit if either the select is changed or if text is entered. If you want to give someone the opportunity to alter both of them and THEN submit, you'll need to change this up a bit (probably best to just add a submit button).
Then, richiesta.php could simply get the data from $_POST['data'] and explode it from there.
I have my code with a form.
I validate this with a javascript function sub().
When validation successful inside the javascript function i post to a php file by $.POST.
I can fetch the name field by its id name.
But I cant fetch the Cities as it has multiple value.
I am using jquery asmselect for multiple selection.
Can any one help me to fetch the multiple values of cities.
I tried by its id but failed to do.
Plz help me.............
My javascript code
<link rel="stylesheet" type="text/css" href="../jquery.asmselect.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.ui.js"></script>
<script type="text/javascript" src="jquery.asmselect.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("select[multiple]").asmSelect({
addItemTarget: 'bottom',
animate: true,
highlight: true,
sortable: true
});
});
</script>
<script type="text/javascript">
function sub(){
var udt;
var name = document.getElementById('name').value;
var cities = document.getElementById('cities').value;
if(name!=""&&cities!=""){
udt ="name="+name+"&cities="+cities;
$.post( "submit.php", udt, function( data ) {
window.location.href = "/";
});
return false;
} else {
alert("Please, Complete the Registration Form...");
return false;
}
}
</script>
My html code is below
<form action="" onsubmit="return sub()" method="post">
<input type="text" id="name" name="name"/>
<select id="cities" multiple="multiple" name="cities[]" title="Select City">
<option>Paris</option>
<option>San Diego</option>
<option>San Francisco</option>
<option>Vancouver</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
Plz help me to solve my problem.
I can not find any solution. So I post this question here, thanks.
Try this (add whatever delimiter you want):
cities = '';
$("select[multiple] option:selected").each(function(){
cities += $(this).val() + '|';
});