I'm trying to get selected option in php to save it in a database. I'm using Ajax and it sends data and a file all together with FormData. Everything goes ok but when I select an option and click on submit button, the php file does not get nothing and just saves input text data and file information.
HTML
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first"/>
<input type="file" name="image"/>
<select name="disp" id="dispnb" class="dispc">
<option value="0" selected>Select...</option>
<option value="2"><b>Option A</b></option>
<option value="3">Option B</option>
<option value="3">Option C</option>
</select>
</form>
jQuery
$(document).ready(function(){
$("form#data").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
PHP
<?php
echo $_POST['first'];
echo $_POST['disp'];
echo $_FILES['image']['name'];
?>
Try like this:
$("#dispnb").change(function(){
var your_selected_value = $('#dispnb').val();
$.ajax({
type: "POST",
url: 'upload.php',
data: {"selected": your_selected_value},
success: function(data) {
alert(data);
},
error: function(data) {
// Stuff
}
});
});
In upload.php
<?php
if (isset($_POST['selected'])){
$a = $_POST['selected'];
echo $a;
}
You can use $('form').serialize(); instead of var formData = new FormData($(this)[0]);
Using this code you will get all from data.
add id to your text fields
<input type="text" name="first" id="first"/>
<input type="file" name="image" id="image"/>
js
$(document).ready(function(){
$("form#data").submit(function(){
var data = array{}
data.disp = $('#dispnb').val();
data.first = $('#first').val();
data.image = $('#image').val();
$.ajax({
url: 'upload.php',
type: 'POST',
data: data,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Then in ur php file
<?php
echo $_POST['first'];
echo $_POST['disp'];
echo $_FILES['image']['name'];
?>
});