On my html page, I have a variable number of dropdown boxes, each with the following code:
<select name="gearquan[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
If using a regular form submit, it sends as a nested array. I'm trying to convert my forms over to using jquery and ajax. When I had a list of checkboxes I used the following code to get their values:
var gear = new Array();
$("input:checked").each(function() {
gear.push($(this).val());
});
What would I need to change in that, in order to get the values of the dropdown boxes? (Other than changing gear to gearquan)
It seems like you are trying to manually build arrays to send to your PHP through AJAX, you don't need to do all that. When using jQuery and AJAX all you need to do is use .submit() to handle your submit event and .serialize() to get all your current form's data to send thorough AJAX as such:
$('form').submit(function(e){
e.preventDefault();
var postdata = $(this).serialize();
$.ajax({
url: 'file.php',
type: 'post',
data: postdata,
success: function(response){
console.log(response);
}
});
});
Related
I have the following 3 checkboxes which are populated from a php database. I need assistance with JQUERY that once any select box is changed the value is posted to a php file and able to return a response through JQUERY.
Each select box should be standalone to only send that checkbox value & name to the PHP file.
I have the below JQUERY to start with to send the first checkbox but am getting no response back.
What amendments need to be made to the JQUERY to receive the input of the other checkboxes and then send the data correctly?
The php file will simply have echo "WHAT EVER THE RESPONSE IS" using if statements.
Any help grately appreciated with thanks.
$(document).ready(function() {
$('select.person-1').change(function() {
$.ajax({
type: 'POST',
url: 'lib/positionMarshalProcess.php',
data: {
selectFieldValue: $('select.person-1').val(),
changeCol1: $('input[name$="changeCol1"]').val()
},
dataType: "html",
},
success: function(data) {
var a = data.split('|***|');
if (a[1] == "update") {
$('#msg').html(a[0]);
}
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name='person-1' class='marshal-select'>
<option value='1'>John Smith</option>
</select>
<input type='hidden' name='changeCol1' value='person-1'>
<select name='qty' class='marshal-select'>
<option value='1'>1</option>
</select>
<input type='hidden' name='changeCol2' value='qty'>
<select name='person-2' class='marshal-select'>
<option value='1'>John Smith</option>
</select>
<input type='hidden' name='changeCol3' value='person-2'>
The selectors you've used are incorrect for the HTML displayed. .person-1 is a class selector, yet the select elements have that value in their name.
In addition your success property is outside the options object of the $.ajax call - it needs to be inside.
You can fix this issue and DRY up the code to make it more extensible by removing the hidden fields, hooking the change event handler to the common marshal-select class on all the select elements, and by using the name attribute of the select elements to fill the changeCol property of the data you send in the AJAX request. Try this:
$(document).ready(function() {
$('select.marshal-select').change(function() {
let $select = $(this);
// in your AJAX request...
let data = {
selectFieldValue: $select.val(),
changeCol: $select.prop('name')
};
console.log(data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="person-1" class="marshal-select">
<option value="1">John Smith</option>
<option value="2">Jane Doe</option>
</select>
<select name="qty" class="marshal-select">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="person-2" class="marshal-select">
<option value="1">John Smith</option>
<option value="2">Jane Doe</option>
</select>
As an aside, the logic in the success handler implies that you're returning plain text and then hacking the string around using split(). Do not do this. Return a serialised data structure, such as JSON instead. This is more extensible and makes the code far more robust.
Update:
With your code you have added could you just add an edit where how you would receive a response ideally I want a positive response to show the msg div and where you would call the php file?
Sure, here you go:
$(document).ready(function() {
$('select.marshal-select').change(function() {
let $select = $(this);
$.ajax({
type: 'POST',
url: 'lib/positionMarshalProcess.php',
data: {
selectFieldValue: $select.val(),
changeCol: $select.prop('name')
},
dataType: "html",
success: function(data) {
// assuming a JSON response:
if (data[1] === 'update') {
$('#msg').html(data[0]).show();
}
}
});
});
});
Note that I've not included the PHP which would generate the JSON response as I'm not a PHP dev. I'm sure there are lots of topics covering that if you search.
I tried to send a variable value from Jquery to php code,but it doesn't work although it appears successfully in console:
Ajax:
$('#commission').change(function(){
var coinval=$('select[name=cointype]').val();
$.ajax({
url: 'core_functions/parse_coins.php', //This is the current doc
type: "POST",
data: ({coinname: coinval}),
success: function(data){
console.log(data);
var recent_btc_price=<?php show_btc_price(); ?>; //10122.9
var com=$('#commission').val();
var com_amount_only=com * recent_btc_price /100;
var convert_comm_amount=Number(com_amount_only);
var totalpricewithcomm=recent_btc_price + convert_comm_amount;
var round_totalprice=totalpricewithcomm.toFixed(2);
$('#display').text("$"+round_totalprice);
}
});
})
PHP:
if(isset($_POST['coinname'])){
$coinname=$_POST['coinname'];
echo $_POST['coinname'];
}
HTML:
<select name="cointype" id="deal_options" class="form-control">
<option value="bitcoin" >Bitcoin (BTC)</option>
<option value="ethereum"selected >Ethereum (ETH)</option>
</select>
<select class="form-control" id="commission">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
why the data can't be handled by php?
i edited code to make it work by making the following changes:
//send data to php file
var coinval=$('select[name=cointype]').val();
function senddata(catchdata){
$.ajax({
url: 'core_functions/parse_coins.php', //This is the current doc
type: "POST",
data: ({coinname: coinval}),
success: function(data){
catchdata(data);
}
});
}
to recieve data:
//recieve data
senddata(function(output){
var recent_btc_price=Number(output); //10122.9
var com=$('#commission').val();
var com_amount_only=com * recent_btc_price /100;
var convert_comm_amount=Number(com_amount_only);
var totalpricewithcomm=recent_btc_price + convert_comm_amount;
//alert(recent_btc_price);
var round_totalprice=totalpricewithcomm.toFixed(2);
$('#display').html(coinval+"~$"+round_totalprice);
});
php code in Jquery must be enclosed by double quotes
var recent_btc_price="";
You have to declare show_btc_price() function first then implement code.
select id section
script section in head
So this is the situation.
I have this
<select name="users" onchange="showUser(this.value)" id="1">
<option value="">Select a person:</option>
<option value="'.$lectures[4][0].'">'.$lectures[4][0].'</option>
<option value="'.$lectures[5][0].'">'.$lectures[5][0].'</option>
<option value="'.$lectures[6][0].'">'.$lectures[6][0].'</option>
<option value="'.$lectures[7][0].'">'.$lectures[7][0].'</option>
</select>
Like this I have lots of select element in the page. I want to pass two value through ajax.
One is selected option value. Which I have done successfully.
Other is the I want to pass select tag id. In this case it is 1.
So Could you help me in the ajax part
xmlhttp.open("GET","optiondetails.php?q="+str,true);
xmlhttp.send();
How to pass this value through ajax. Please keep in mind that I have to do this for many select tag. So I cannot pass them directly by value.
Thanks for you help.
try this:
$(document).ready(function(){
$('select').change(function(){
var opt = $(this).find('option:selected');
console.log(opt.val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="1">
<option value="dog">dog</option>
<option value="cat">cat</option>
</select>
<select id="2">
<option value="chocolate">chocolate</option>
<option value="pizza">pizza</option>
</select>
I used jQuery selector to get the selected option inside the changed select element
I think this is more convenient way to do that:
$(document).ready(function(){
$(document).on('change', 'select', function(){
var optVal = $(this).val();
var id = $(this).attr('id');
$.ajax({
method: "GET",
url: "optiondetails.php",
data: {q:optval, tag_id:id},
cache: false
}).done(function(response){
console.log(response);
});
});
});
I've created a form with 3 select part and I tried to create an array with serializeArray. I want to use jquery ajax to post this array to my php file. But I don't want use submit. when I had just one select tag, I used this code
<form>
<select onchange="myfunction(str)">
<option value="">num</option>
<option value="123">123</option>
<option value="133">133</option>
</select>
</form>
In my ajax code, I used open("GET","myphpfile.php?q="+str,true) and send() without jquery. but now I have 3 select tag and I don't know how too use serializeArray()(or serialize()) with jquery.
this is my new form
<form>
<select name="num1">
<option value="">num1</option>
<option value="12">12</option>
<option value="13">13</option>
</select>
<select name="num2">
<option value="">num2</option>
<option value="123">123</option>
<option value="133">133</option>
</select>
<select name="num3">
<option value="">num3</option>
<option value="12345">12345</option>
<option value="12346">12346</option>
</select>
</form>
the second part of my question is how to write my php code to echo my array. I think it should be something like this
<?php
$myarr = array();
$myarr = $_GET["str"]//or $_POST['str']
echo $myarr[0];
?>
Thanks a lot! and by the way, English is not my native language; please excuse typing errors.
Okay, if I get your question correctly, here is what you're trying to do:
Hooking events on dynamically added fields
$("form").on("change", "select", function() {
var name = $(this).prop("name");
console.log("Select-Name: " + name);
// if you use the plugin I mentioned further down and you'll need to serialize
// all fields already here, you can use the plugin's .fieldSerialize method
})
Get detailed information here: https://api.jquery.com/on/
Serializing forms
Easiest thing here would be to work with this jQuery Form-Plugin:
http://malsup.com/jquery/form/
Create a json-dataset with almost no effort like this:
$("form").ajaxForm({
dataType: "json",
success: function(data) { sendToServer(data); }
});
Working with the data in the backend
The plugin also allows you to work on the server with the script you provided ($_POST["value"])
use
var arrayForm = $('form select').serializeArray();
and then
var paramForm = $.param(arrayForm);
like http://jsfiddle.net/LBKeQ/
then you can use
$.ajax({
type: 'POST',
async:true,
cache: false,
data: paramForm,
success:function (data, textStatus) {
console.log(data);
},
url:"myphpfile.php"
});
I want to send the value of selected index to a function, where all option values are coming through database.
<select onchange="get_api_key();" name="service">
<option value="">Select your Service</option>
<optgroup label="Apple Iphone">
<option value="53">Apple </option>
<option value="72">Ipad </option>
<option value="77">iPhone</option>
<option value="24">Iphone</option>
</optgroup>
</select>
for the selected index use this.selectedIndex instead of this.value
see http://jsfiddle.net/corinnekm/FZY2v/2/
UPDATE: You can't use a javascript variable inside a PHP function. However, you can use Ajax to change a javascript variable to a PHP variable and then use it for your purpose.
<script type="text/javascript">
$(function(){
var selVal = $('select[name="service"]').val();
// send selVal as a PHP variable using Ajax
$.ajax({
type:'post',
url:'getvalue.php',
data:'selVal='+selVal,
success:function(data){
//do something if you want to with returned data
}
});
});
</script>
Then in getvalue.php page,
$val = $_POST['selVal'];
// proceed to use $val for whatever purpose you want in this page