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>
Related
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
}
I have a list of drop down.on click of button i am call one function.In this i need all the values which I selected how i can do this
The following is my code
HTML
<html ng-app="myapp">
<head>
<script src="angular/angular.js"></script>
</head>
<body>
<div ng-app ng-controller="MyCtrl">
<select class="form-control" ng-model="firstType" ng-change="onRegionChange(firstType)" ng-options="item.id as item.name for item in items">
</select>
<input type="submit" ng-click='resultView()'/>
</div>
</body>
</html>
script
<script>
var myapp = angular.module('myapp', []);
myapp.controller('MyCtrl', function ($scope,$http)
{
$scope.Data = {};
$scope.items = [{id:1, name:'First'}, {id:2, name:'Second'}, {id:3, name:'Third'}];
$scope.onRegionChange = function(firstType)
{
console.log(firstType);
}
$scope.resultView = function()
{
console.log(firstType);
}
});
</script>
Any advice or help is much appreciated.
while clicking the button its showing error in console
Thank you
this is the error screen shot
You can just add a parameter to resultView function. Like this:
<input type="submit" ng-click='resultView(firstType)'/>
And add here too.
$scope.resultView = function(firstType)
{
console.log(firstType);
}
$scope.resultView = function(firstType)
{
console.log(this.firstType);
}
just you have to add 'this.firstType' then its working after a long day I found out this
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"] ;
}
I am posting a form in an expressionengine (1.6.8) template. I'm doing it using jquery but have tried an HTML form too - same result. The PHP superglobal $_POST is empty after posting the form, even though I have PHP enabled on my templates (on input for the template containing the form and output on the processing template) and can see the POST variables in firebug.
Can anyone suggest what might cause this?
<html>
<head>
<script type="text/javascript" src="/_scripts/jquery-1.6.1.min.js"></script>
</head>
<body>
<form action="/select-locale/processing" method="POST">
<input type="text" name="test"/>
<input type="submit" name="submit" value="submit">
</form>
<a id="test" href="">link</a>
<script type="text/javascript">
$(function(){
$('#test').bind('click', function(e){
e.preventDefault();
var path = "/select-locale/processing"
var form = $('<form/>');
form.attr("method", "post");
form.attr("action", path);
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", 'locale');
field.attr("value", 'NZ');
form.append(field);
$('body').append(form);
form.submit();
});
});
</script>
</body>
</html>
server-side code (inherited, not my own) :
<?php
var_dump($_POST);
var_dump($_GET);exit;
if ( ! isset($_POST['locale']))
{
$locale = FALSE;
$returnPage = "/";
}
else
{
$locale = $_POST['locale'];
$returnPage = $_POST['returnPage'];
}
if (isset($_GET['locale'])) {
$locale = $_GET['locale'];
$returnPage = "/";
?>
{exp:cookie_plus:set name="cklocale" value="<?php echo $locale;?>" seconds="2678400"}
{exp:session_variables:set name="userLocale" value="<?php echo $locale;?>"} <?php
}
?>
{exp:cookie_plus:set name="cklocale" value="<?php echo $locale;?>" seconds="2678400"}
{exp:session_variables:set name="userLocale" value="<?php echo $locale;?>"}
{exp:session_variables:get name="testSession"}
{if '{exp:session_variables:get name="testSession"}'=='yes' }
{redirect="<?php echo $returnPage;?>"}
{if:else}
{redirect="/nocookies/"}
{/if}
check the network tab if the parameters you want are really sent out
check the url if it's correct
if you use any sort of routing mechanism or url rewrite, you might wanna review it also
check your validation and XSS rules (if any) as it may reject the whole array once hints of XSS is found.
happened to me a while ago (CI) and i was sending it to the wrong url
You might want to re-check the action attribute, are u sure you're sending the data to the right url? I doubt that anything could be filtered.
it seems like form is getting submitted twice because of either action attribute of form tag or oath value in jquery function
It may be useful
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body name="test">
<form action="/select-locale/processing" method="POST">
<input type="text" name="test"/>
<input type="submit" name="submit" value="submit">
</form>
<a id="test" href="">link</a>
</body>
</html>
<script type="text/javascript">
$(function(){
$('#test').bind('click', function(){
var form ='<form action="/select-locale/processing" name="newform" method="POST"><input type="hidden1" name="locale" value="NZ"></form>';
$('body').append(form);
alert('added');
document.newform.submit();
});
});
</script>`
So, I have a search form in a php page (top.php) which is an include for the site I'm working on, one php page where all the mySQL stuff happens and the results are stored in a variable and echoed (dosearch.php) and lastly a php page where the results are displayed in a div through jQuery (search.php). This is the javascript code:
$(document).ready(function(){
$('#search_button').click(function(e) {
e.preventDefault();
var searchVal = $('#search_term').attr('value');
var categoryVal = $('#category').attr('value');
$.ajax({
type: 'POST',
url: 'dosearch.php',
data: "search_term=" + searchVal + "&category=" + categoryVal,
beforeSend: function() {
$('#results_cont').html('');
$('#loader').html('<img src="layout/ajax-loader.gif" alt="Searching..." />');
if(!searchVal[0]) {
$('#loader').html('');
$('#results_cont').html('No input...');
return false;
}
},
success: function(response) {
$('#loader').html('');
$('#results_cont').html(response);
}
});
});
});
The #search_term and #category fields are in top.php, the other divs (#loader and #results_cont) are in search.php. How would I go by in order to make the form submit and display the results in search.php from the top.php without problems? It works perfectly if the form and javascript are in search.php but I can't seem to separate those and make it work. What am I doing wrong?
PS. Sorry if I'm not clear enough, am at work, really tired. :(
SPLITTING:
<? include('functions-or-classes.php'); ?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<? include('js-script.php'); ?>
</head>
<body>
<? include('results-div.php'); ?>
<? include('search-form.php'); ?>
</body>
</html>
You should just respect this order then you can split the code in different pieces and include it into your main php file;
PS: peraphs your code should look like this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
$(function() {
$('#search-form').submit(function(e) {
e.preventDefault();
var searchVal = $('#search_term').val();
var query = $(this).serialize(); // search_term=lorem&category=foo
if (!searchVal) {
$('#results_cont').html('No input...');
} else {
$('#results_cont').html('<div id="loader">'+
'<img src="layout/ajax-loader.gif" alt="" /><div>');
$.ajax({
type: 'POST',
url: 'dosearch.php',
data: query,
success: function(response) {
$('#results_cont').html(response);
}
});
}
});
});
</script>
</head>
<body>
<form id="search-form">
<input type="text" id="search_term" name="search_term" />
<select id="category" name="category">
<option value="foo">foo</option>
<option value="bar">bar</option>
</select>
<input type="submit" name="search_button" />
</form>
<div id="results_cont"></div>
</body>
</html>
you can make your search_button redirect to your search.php an do the work when the pages is loaded instead of doing it on the click event.
and use $_GET['Search'] on the search page
and your url should look like this
/search.php?Search=1337