How to use onchange with serializeArray in jquery? - php

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"
});

Related

JQUERY & Select box not updating database

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.

Variable cannot fetch values from a Select Option even if name is correct

So I am making an assignment program wherein in my database, I have a set of documents and when I want to tag it to a person, I would choose who I will tag it to. Here is the code for assigning a person to a document.
<select name="staff" value="staff" align="left" onchange="senddocu(this)">
<option selected value="">Staff</option>
<option name='chief' value='chief'>Chief User</option>
<option name='user' value='user'>User 1</option>
</select>
Now, I have a problem with getting values from another file in my PHP code. Somehow, it doesn't fetch the values from my select options. Here are the parameters for my select options. And also, my code from earlier and this code is in one file only.
<select name="document" align="left">
<option selected disabled value="">Document Type</option>
<option value="A">A</option>
<option value="C">C</option>
<option value="CO">CO</option>
<option value="Curr">Curr</option>
<option value="Scholarship">Scholarship</option>
<option value="MIS">MIS</option>
<option value="Fax">Fax</option>
<option value="E-mail">E-mail</option></select>
<input type="text" name= "datenow" id = "copy" align="center">
<input type="text" name="application" align="center" size = "3%">
And here is the code to fetch the values from those. This is in another file.
<?php
$document_type= mysqli_real_escape_string($conn, $_POST['document']);
$application_no= mysqli_real_escape_string($conn, $_POST['application']);
$today = mysqli_real_escape_string($conn, $_POST['datenow']);
echo $document_type;
echo $application_no;
echo $today;
?>
The problem is, only the $today variable fetches its value. The rest doesn't get stored into the variables from another file.It doesn't make sense at all. All the names are correct, yet its not fetching it. I already have the ajax code on my first file which is:
function senddocu(sel)
{
$.ajax({
type: "POST",
data: {staff: $(sel).val()},
url: "send.php",
dataType: "html",
success: function(response)
{
$("#responsecontainer").html(response);
console.log(response);
}
});
}
how to fetch the values?
You're not using the correct way to fetch the value of the <select> in your AJAX request. You need to give the select an id, or a name, which you target in order to get the right element. You then ask it for the selected options value.
In order to get the input field variables, you can select them by name, or by id also. I'm just going to do it by name, since that's what you have in your example snippet.
Example using id:
function senddocu()
{
$.ajax({
type: "POST",
data: {
staff: $("#sel option:selected").val(),
datenow: $("input#datenow").val(),
application: $("input#application").val()
},
url: "send.php",
dataType: "html",
success: function(response)
{
$("#responsecontainer").html(response);
console.log(response);
}
});
}
This example takes the selected value of a select that has the id sel. In order to make this work, you simply have to give your select the proper id.
Like so:
<select name="document" id="sel" align="left" onchange="senddocu();">
<option selected disabled value="">Document Type</option>
<option value="A">A</option>
<option value="C">C</option>
<option value="CO">CO</option>
<option value="Curr">Curr</option>
<option value="Scholarship">Scholarship</option>
<option value="MIS">MIS</option>
<option value="Fax">Fax</option>
<option value="E-mail">E-mail</option>
</select>
<input type="text" name= "datenow" id = "copy" align="center">
<input type="text" name="application" align="center" size = "3%">
Example by using name to get the value:
function senddocu(sel)
{
$.ajax({
type: "POST",
data: {
staff: $("select[name=document] option:selected").val(),
datenow: $("input[name=datenow]").val(),
application: $("input[name=application]").val()
},
url: "send.php",
dataType: "html",
success: function(response)
{
$("#responsecontainer").html(response);
console.log(response);
}
});
}
If the input variables are in a completely different file, you'll have to reconsider what you're trying to achieve and maybe rework your logic around that, whether there's really a reason for that. You should also consider including more coherent code in your questions so that people can get the whole picture, as well as test the code. Makes it a lot easier that way.

Ajax get select tag id for passing through ajax

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);
});
});
});

get html dropdown array in jquery

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);
}
});
});

How to send a selected value of an option to a PHP function as a argument

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

Categories