Pass value to PHP after HTML Select Change - php

My html form has a Select option. a Mysql query runs after i Change data from option and Submit the data . What i want is, After selecting the data from select it will reload and pass the value to php code.
Here is the html
<form action='a.php?'>
<SELECT name="client_id" ID="mySelect">
<OPTION value="artes>'">artes</OPTION>
<OPTION value="ingles">inglés</OPTION>
</SELECT>
<input type="submit" name="chooseclient" value="Select">
</form>
Here is the php that runs after submit
if(isset($_POST['chooseclient'])){
$clientid = mysqli_real_escape_string($mysqli, $_POST['client_id']);
MYSQL query here
}
I have tried this.form.submit() , but that doesnt send data. I understand that i need to Ajax . Is there any way to onChange reload the form and pass data to php ?

To achieve what you are expecting you will have to do a little javascript. From what I understand you don't need to send ajax request as you asked for your form to reload when it gets submitted. But I'll give you both approaches.
No AJAX
First we will add a id to your form. Here in my example it will be "my-form". And an onchange event to your select that will call myFunction();.
We must also tell to your form to post the data for your current PHP script to work or it will send it as a get
<form id="my-form" action='a.php?' method="post">
<SELECT onchange="myFunction()" name="client_id" ID="mySelect">
<OPTION value="artes>'">artes</OPTION>
<OPTION value="ingles">inglés</OPTION>
</SELECT>
<input type="submit" name="chooseclient" value="Select">
</form>
Now in a javascript file or between a script tag add your function :
<script>
function myFunction(){
document.getElementById("my-form").submit();
}
</script>
Now your form should submit itself when you change the value of your select. BUT you will have another problem.
if(isset($_POST['chooseclient'])){
$clientid = mysqli_real_escape_string($mysqli, $_POST['client_id']);
//MYSQL query here
}
When you submit a form via javascript, your submit button will not be sent with the rest of the data. so if(isset($_POST['chooseclient'])) will never be true. To tackle this you have a few options, I'll give you two :
You could change your PHP to check on client_id instead (If you do this you can remove your submit button completely) :
if(isset($_POST['client_id'])){
$clientid = mysqli_real_escape_string($mysqli, $_POST['client_id']);
//MYSQL query here
}
Or change your submit button to a hidden field :
<form id="my-form" action='a.php'>
<SELECT onchange="myFunction()" name="client_id" ID="mySelect">
<OPTION value="artes>'">artes</OPTION>
<OPTION value="ingles">inglés</OPTION>
</SELECT>
<input type="hidden" name="chooseclient" value="Select">
</form>
Ajax
Just like in the first method we will add a id to your form and an onchange event to your select you should also remove your submit button or change it for an hidden field, in this example I will remove it :
<form id="my-form" action='a.php'>
<SELECT onchange="myFunction()" name="client_id" ID="mySelect">
<OPTION value="artes>'">artes</OPTION>
<OPTION value="ingles">inglés</OPTION>
</SELECT>
</form>
And the script wich will be quite different to the first one :
<script>
function myFunction(){
var form = document.getElementById("my-form");
var action = form.getAttribute("action");
var data = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open("POST", action);
xhr.send(data);
}
</script>
Again you will have to fix your PHP not to condition on chooseclient (Unless you made it an hidden field) :
if(isset($_POST['client_id'])){
$clientid = mysqli_real_escape_string($mysqli, $_POST['client_id']);
//MYSQL query here
}
If you choose the ajax method you may want to do something with the response, there are plenty of threads on stackoverflow about this, here is one : How to get the response of XMLHttpRequest?

If you want to send the selected value automatically by Ajax to a.php when the field value is changed, you can use the following code :
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
<form action='a.php?'>
<SELECT name="client_id" ID="mySelect">
<option value="A1>'">A1</option>
<option value="A2">A2</option>
<option value="A3">A3</option>
</SELECT>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#mySelect").change(function(){
var value =$("#mySelect").val();
alert(value);
$.ajax({
url: 'a.php',
type: "POST",
data: ({chooseclient: value}),
success: function(){
location.reload();
}
});
});
});
</script>
</body>
If you do not want the page to be reloaded after sending information and saving to the database, ‍ comment it location.reload();
a.php :
<?php
if(isset($_POST['chooseclient'])){
$clientid = mysqli_real_escape_string($mysqli, $_POST['chooseclient']);
#MYSQL query here
# do something
}

Related

My Ajax output is disappearing after one sec

I am using Ajax with form in Ajax I have used a if condition for validation if my form is empty it should display a message that all fields are required and if fields are fill it should add data in dB and display a success message although everything is working perfectly except one thing which is that my output only display for a second and then automatically disappears can anyone help me in this regard:
`
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<script src="jquery.js"></script>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<h1>PHP & Ajax Seralize Form</h1>
<form id="form-data" method="post">
Name<br><input type="text" name="name" id="name" value=""><br><br>
Age<br><input type="number" name="number" id="age" value=""><br><br>
Gender<br>
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Fe-male<br><br>
<select name="country">
<option value="Kashmir">Kashmir</option>
<option value="Egypt">Egypt</option>
<option value="Norway">Norway</option>
<option value="Iceland">Iceland</option>
</select><br>
<br><input type="submit" id="submit" value="Save">
</form>
<div id="response">
</div>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var name = $('#name').val();
var age = $('#age').val();
if( name== "" || age== ""){
$('#response').fadeIn();
$('#response').removeClass('success-msg').addClass('error-msg').html("All fields are required");
}else{
$.ajax({
url: 'save-form.php',
type: 'POST',
data: $('#form-data').serialize(),
success: function(result){
$('#response').fadeIn();
$('#response').removeClass('error-msg').addClass('success-msg').html(result);
}
});
}
});
});
</script>
</body>
</html>
`
probably your page is refreshed, try to use preventDefault to prevent the refresh
$('#submit').click(function(event){
//your code here
event.preventDefault();
}
You have a button with type "submit".
<input type="submit" id="submit" value="Save">
As the click-event occurs on this button, your form will be send to the server. You have no action attribute defined on your form, so it redirects after submit to the same URL.
As Sterko stated, you could use a event-handler to prevent the submission of your form due to the submit button.

How $_post in PHP works [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am passing variable from jquery to php, and trying to submit my form through submit button also, but my variable is not visible in $_POST['submit'].
I have an html page with a list where I am choosing more than one value and concatenating it with ':' and passing it to PHP.
once I press the submit button on the form I want to insert that selected list in my database table.
Please, can someone explain.
HTML
<!doctype html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form action="new_page.php" method="post">
<select class= "sweet" name="sweets" multiple="multiple">
<option>Chocolate</option>
<option >Candy</option>
<option>Taffy</option>
<option>Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<input type="submit" name ="submit" value ="submit" />
<script>
$(function(){
var s_type="";
$('.sweet').click(function() {
if(s_type.length){
s_type+= " : " + $(this).val();
}else{
s_type+= $(this).val();
}
$.post('new_page.php', 'sweet=' +s_type, function (response){
alert(response);
});
});
});
</script>
</body>
</html>`
PHP Page new_page.php
<?php
if(isset($_POST['sweet'])){
$filename = $_POST['sweet'];
}
if(isset($_POST['submit'])) {
if(isset($_POST['sweet'])){
$filename = $_POST['sweet'];
echo '*****profile ' .$filename;
}
$id= 'A';
$db = new PDO("sqlite:test.db");
$q1 = $db->prepare('INSERT INTO test_sweet(id,sweets) values(?,?)');
$q1->execute(array($id,$filename));
}
?>
Edit: I'll add this remark here aswell:
If you want multiple values from your <select> change it into <select multiple> and you're done, this JS is a rather unintuitive workaround.
(Even moreso since you can't easily remove values you selected without reloading the whole page)
Might give this a try, mind you it's drycoded (untested):
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form id="sweetForm">
<select id="selSweets" name="sweets" multiple="multiple">
<option>Chocolate</option>
<option >Candy</option>
<option>Taffy</option>
<option>Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<input id="submit" type="submit" name="submit" value="submit" />
</form>
<script>
$(function() {
var sweets = [];
$('#selSweets').change(function() {
var val = $(this).val();
if (sweets.indexOf(val) == -1) // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Browser_compatibility for browser compatibility on indexOf()
sweets.push(val);
});
$("#sweetForm").submit(function(e)
{
$.post(
'new_page.php',
{
sweets: sweets
},
function(data, status, jqXHR)
{
console.log(data);
}
);
e.preventDefault();
});
});
</script>
</body>
</html>

POST something using editable dropdown

I made an editable dropdown menu :
<html>
<body>
<div style="position:relative;width:200px;height:25px;border:0;padding:0;margin:0;">
<select style="position:absolute;top:0px;left:0px;width:200px; height:25px;line-height:20px;margin:0;padding:0;" onchange="document.getElementById('displayValue').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;">
<option></option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
<input type="text" name="displayValue" placeholder="add/select a value" id="displayValue" style="position:absolute;top:0px;left:0px;width:183px;width:180px\9;#width:180px;height:23px; height:21px\9;#height:18px;border:1px solid #556;" onfocus="this.select()">
<input type="hidden" name="idValue" id="idValue">
</div>
</body>
</html>
I want to POST the value that was added, so as to include it in drop down for the next round.
I suggest you use jQuery for easy implementation. You can wrap them in a form and do the POSTing via jQuery Ajax then store that value somewhere for future use then append it to the next as the new option item.
POST via aJax
$(function() {
$('#form').on('submit', function(e) {
// do not reload the page
e.preventDefault();
// do the posting
var newValue = $('#displayValue').val();
$.post('http://MYURL.com/post.php', {
new_field: newValue
}, function(data) {
// success callback
$('#form > select').append('<option value="'+newValue+'">'+newValue+'</option>');
})
});
})
Basically, you post newValue to http://MYURL.com/post.php and handle that new data then the success callback will handle the inserting of the new value to your select.
the code is not tested, let me know if it did not work
Learn more about jquery.post() here and more about jquery here

How to pass the jquery hidden value to php

in my code i am creating a drop down box and storing the changed value of the drop down in hidden variable.
<!DOCTYPE html>
<html>
<head>
<style>
div { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<select id="sweets">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<input type="hidden" id="inputfield">
<div></div>
<script type="text/javascript">
$(document).ready(function() {
$("#sweets").change(function() {
var var_name = $(this).val();
$('input[id=inputfield]').val(theValue);
}
});
});
});
</script>
</body>
</html>
<?php
if(isset($_POST['form']))
echo $_POST['inputfield'];
?>
once the combo box is changed the php should get the hidden field value and i ve to perform db transaction. again i need to load another drop down box based on the selected value.. Can you guide me
You can bypass all the horse trading with the hidden field and send it to php directly via ajax.
$(document).ready(function() {
$("#sweets").change(function() {
$.post('myphpfile.php', {sweet : $(this).val() });
});
});
myphpfile.php will receive the value as a post with the name of 'sweet'
Unless I'm misunderstanding, shouldn't
$('input[id=inputfield]').val(theValue);
be
$('input[id=inputfield]').val(var_name);
?
You can wrap the select and hidden elements in form element adding a post method and action attribute. Give the hidden field a name as in name="hidden field"
this way you can access it in the post variable.
<form action="currentpage.php" method="post">
<select id="sweets">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<input type="hidden" id="inputfield" name="hiddenfield"/>
<input type="submit" value="Submit" name="submit"/>
</form>
When the change event executes to update the hidden field and you submit in php you can do
if(isset($_POST["submit"]))
{
$val = $_POST["hiddenfield"] ;
}

PHP/Javascript post js variable to php page

Though a novice in javascript, I need to take javascript variable (an array) reflecting what a user has done on client side and post it to a PHP server page on submit.
It was suggested that I include this as a value in a hidden field in a form to post to the php page. However, since the JS variable is dynamically created by the user, I can't write to the page for inclusion in the form unless I call a function that refreshes the page. To avoid a double page refresh, I'd prefer to have the submit function both grab the data and simultaneously post it to the php script. AJAX if I understand correctly, should not be needed because I'm okay reloading the page once on submit. I just don't want to reload twice.
The following uses the function suggested by Andrew to set the js variable and post. Th form posts as I get the other hidden variable in the form but I am not getting the variable set by js, possibly because there is a mistake with the naming of the variables.
<html>
<head>
<style type="text/css">
select
{
width:100px;
}
</style>
<script type="text/Javascript">
function moveToRightOrLeft(side)
{
if (side == 1)
{
var list1 = document.getElementById('selectLeft');
var list2 = document.getElementById('selectRight');
}
else
{
var list1 = document.getElementById('selectRight');
var list2 = document.getElementById('selectLeft');
}
if (list1.options.length == 0)
{
alert('The list is empty');
return false;
}
else
{
var selectedItem = list1.options[list1.selectedIndex];
move(list2, selectedItem.value, selectedItem.text);
list1.remove(list1.selectedIndex);
if (list1.options.length > 0)
list1.options[0].selected = true;
}
return true;
}
function move(listBoxTo, optionValue, optionDisplayText)
{
var newOption = document.createElement("option");
newOption.value = optionValue;
newOption.text = optionDisplayText;
listBoxTo.add(newOption, null);
return true;
}
function postData(listBoxID)
{
var options = document.getElementById(listBoxID).options;
for (var i = 0; i < options.length; i++)
window.location = "posttoserver.php?data="+options[i].value;
}
function setTheValue(val) {
var options = document.getElementById(listBoxID).options;
var form = document.forms['myForm'];
hiddenField = oFormObject.elements["data"];
hiddenField.value = "val";
}
</script>
</head>
<body>
<select id="selectLeft" multiple="multiple">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<button onclick="moveToRightOrLeft(2)"><</button>
<button onclick="moveToRightOrLeft(1)">></button>
<select id="selectRight" multiple="multiple">
</select>
<form id="myForm" action="getdata.php" method="get">
<input type="hidden" name="data" />
<input type="hidden" name="mode" value="savedit">
<button onclick="setTheValue(options)">Submit Data</button>
</form>
</body>
</html>
On the other end I have in getdata.php:
<?php
$mode = $_REQUEST['mode'];
$option = $_REQUEST['data'];
echo $mode;
echo $option;
print_r ($option);;
?>
Finally solved it days later with document.getElementById('varname').value
For newbs like me, document.getElementById does not merely retrieve data as you might think and most documentation mentions. It also sets data.
The key is to write the statement backwards and also (as you must do to retrieve a value) put id== into the element you want to set.
If you write var test = document.getElementById('text'); and you have put id="text" in some field, it will retrieve the value of text. That's what the usual documentation mentions. However, if you write:
document.getElementById('varname').value = "dog"
it will insert "dog" into the element that contains id=varname.
While that may be obvious to the more experienced, it certainly confused me.
Following code works.
<html>
<head>
<script>
function Post(data)
{
document.getElementById('varname').value = data
}
</script>
</head>
<body>
<form action = "" method="get">
<input id="varname" type="hidden" name="d">
<button onclick="Post('dog')">Post to Server</button>
</form>
</body>
</html>
You can go ahead and create a form like you normally would with an empty hidden field:
<form id="myForm" action="posttoserver.php" method="get">
<input type="hidden" name="data" />
...
<input type="submit" value="Submit" />
</form>
And you can use a JavaScript function to set the value of the hidden field:
function setTheValue(val) {
var form = document.forms['myForm'];
hiddenField = oFormObject.elements["data"];
hiddenField.value = "val";
}
You can then call the function setTheValue(val) when your button is clicked or whatever.
I hope this helps!
jQuery actually makes this very simple. You have the right idea but using window.location is going to change your page. What you are looking to do is make a async request to another url while you remain on your current page.
http://api.jquery.com/jQuery.ajax/

Categories