Getting value of select element using jquery - php

I have the following HTML
<div class="question-set">
<div class="row question">
<div class="col-md-2">
<select class="form-control" name="type[]">
<option value="Teacher feedback">Teacher feedback</option>
<option value="Genral Question">Genral Question</option>
<option value="Informative Question">Informative Question</option>
</select>
</div>
<div class="col-md-8">
<input type="text" class="form-control" name="questions[]" placeholder="Enter the question here" />
</div>
</div>
<div class="row question">
<div class="col-md-2">
<select class="form-control" name="type[]">
<option value="Teacher feedback">Teacher feedback</option>
<option value="Genral Question">Genral Question</option>
<option value="Informative Question">Informative Question</option>
</select>
</div>
<div class="col-md-8">
<input type="text" class="form-control" name="questions[]" placeholder="Enter the question here" />
</div>
</div>
</div>
In short there is a select tag with name type[] and a text input field names questions[]. I need to pass the values to a php page as an ajax call to insert into the database. I have the following AJAX code..
$.ajax({
method: "POST",
url: "feedback_create_form_process.php",
data: {"questions": $("input[name='questions[]']").val(), "type": $("select option:selected").val()},
success: function(data){
alert(data);
}
});
Here is my PHP code
<?php
include 'con.php';
if (isset($_POST) && sizeof($_POST)) {
$question = $_POST['questions'];
$type = $_POST['type'];
echo count($question);
foreach( $question as $key => $n ) {
$result = $con->query("insert into form question(null, ".$question[$key].", ".$n.")");
}
}
?>
The count is returned as 1. It sends only the first question and not the array. I want the values in an array so i can do an insert in a loop.

As Documented in JQuery .Val()
Description: Get the current value of the first element in the set of matched elements.
You can use
var values = $("input[name='questions[]']").map(function(){return $(this).val();}).get();
or
var values = [];
$("input[name='questions[]']").each(function() {
values.push($(this).val());
});

You can make use of jQuery's map() function to return the values as an array, like so:
var questions = $("input[name='questions[]']").map(function() {return $(this).val()}).get();
var types = $("select[name='type[]']").map(function() {return $(this).val()}).get();
$.ajax({
method: "POST",
url: "feedback_create_form_process.php",
data: {"questions": questions, "type": types},
success: function(data){
alert(data);
}
});
EDIT: Realizing a similar solution was provided by ABDU_GO. I find my script to be a bit more readable, however if you find this to be your solution, I'd suggest accepting his answer.

Related

How to grab data and auto fill a form on change event using Ajax

What I need
I need when someone change my calendar, a php script should run in background and fetch some data and show it in the form fields accordingly. To do that, I have the following HTML code and Ajax script
$("#normalShiftDate").change(function() {
var FD = new FormData($('#dailyEditor')[0]);
$.ajax({
type: "POST",
url: "supervisorEditAjax.php",
processData: false,
contentType: false,
data: FD,
success: function(result) {
$('#normalShiftOperator').val(result["normalShiftOa"]);
$("#normalShiftOperatorDuration").val(result["normalShiftOperatorDuration"]);
$("#normalShiftPinCount").val(result["normalShiftPinCount"]);
},
error: function() {
alert('Some error occurred!');
}
});
});
<div class="form-group">
<div class="row">
<div class="col-sm text-center" id="normalShiftOaDiv" class="">
<label for="currentOa">Current OA?</label><br>
<input type="radio" name="currentOa" id="normalShiftOa" value="normalShiftOa">
</div>
<div class="col-sm" id="normalShiftOperatorNameDiv">
<label for="normalShiftOperator">Normal Shift</label>
<select class="form-control" id="normalShiftOperator" name="normalShiftOperator">
<option></option>
<option>A</option>
<option>B</option>
</select>
</div>
<div class="col-sm" id="normalShiftOperatorDurationDiv">
<label for="normalShiftOperatorDuration">Duration</label>
<select class="form-control" id="normalShiftOperatorDuration" name="normalShiftOperatorDuration">
<option></option>
<option>1</option>
<option>2</option>
</select>
</div>
<div class="col-sm">
<label for="normalShiftPinCount">Pin Count</label>
<input type="number" class="form-control" id="normalShiftPinCount" name="normalShiftPinCount" value="23">
</div>
<div class="col-sm">
<label for="normalShiftDate">Date</label>
<input type="date" class="form-control" id="normalShiftDate" name="normalShiftDate">
</div>
<div class="col-sm">
<button type="submit" class="btn btn-primary" style="margin-top: 30px;" id="normalShiftUpdate" name="normalShiftUpdate">Update</button>
</div>
</div>
</div>
I want to show the php variables $normalShiftOa, $normalShiftOperatorDuration and $normalShiftPinCount in the form fields with id normalShiftOperator, normalShiftOperatorDuration, normalShiftPinCount respectively when someone change calendar. Please see the contents of supervisorEditAjax.php. How can I show these three variables into the three id fields?
I only know how to show to one single field. But if there are multiple values to be shown in multiple fields, how can we do that?
Can someone please help?
Edit 1
Contents of supervisorEditAjax.php
<?php
$normalShiftOa = "A";
$normalShiftOperatorDuration = "2";
$normalShiftPinCount = "100";
$arr = array('normalShiftOa' => $normalShiftOa, 'normalShiftOperatorDuration' => $normalShiftOperatorDuration, 'normalShiftPinCount' => $normalShiftPinCount);
echo json_encode($arr);?>
I tried to use some Json method. But it is not working
After many trial and error, I am able to show it in the respective form fields. The issue was at the Ajax part. Basically I need to parse the Json object in order to get the specific values. Replace the AJAX code as below and it works fine
< script >
$("#normalShiftDate").change(function() {
var FD = new FormData($('#dailyEditor')[0]);
$.ajax({
type: "POST",
url: "supervisorEditAjax.php",
processData: false,
contentType: false,
data: FD,
success: function(result) {
var returnedData = JSON.parse(result); //This is the change done to the code
$('#normalShiftOperator').val(returnedData["normalShiftOa"]);
$("#normalShiftOperatorDuration").val(returnedData["normalShiftOperatorDuration"]);
$("#normalShiftPinCount").val(returnedData["normalShiftPinCount"]);
},
error: function() {
alert('Some error occurred!');
}
});
});
</script>
Please read more about JSON.parse here

POST variable is null when using AJAX call

I am trying to POST the value selected in a dropdown list using AJAX call. But the POST variable remains blank when the value is selected from the dropdown.
I have used the ECHO method to check whether it is returning the POST value. But it is empty.
Here is the code for reference:
Javascript (Jquery and Ajax):
<script>
$(document).ready(function(){
$("#booking_date").change(function(){ //listen when the option change
var optionValue = $("#booking_date").val(); //get the new value
$.ajax({
url: "doctordetails.php", //php file which recive the new value and save it to the database
data: { optionValue: optionValue }, //send the new value
type: "POST" , //use POST method
success: function(data) {
console.log(optionValue);
}
});
});
});
</script>
HTML:
<div class="row">
<div class="col-6">
<div class="form-group">
<input class="form-control" type="text" id="booking_date" name="booking_date" data-lang="en" data-min-year="2017" data-max-year="2020" data-disabled-days="10/17/2017,11/18/2017">
</div>
</div>
<div class="col-6">
<div class="form-group">
<select class="form-control">
<option value="">Select slot</option>>
<?php
require_once("dblogin.php");
?>
<option value="<?php echo $_POST[" optionValue "]; ?>">
<?php echo $_POST["optionValue"]; ?>
</option>
</select>
</div>
</div>
</div>
Expected result:
$_POST should return the selected value from booking_date and the $_POST value will be used in a SQL Query.
If this is dropdown list, then id must be on select box. You set id booking_date on textbox other than select box. write as:
<select id="booking_date" class="form-control">
</select>
If you want to value from select(dropdown) so you have to set id on <select> rather than textbox <input>
<select id="booking_date" class="form-control">
<option value="">Select slot</option>>
<?php require_once("dblogin.php"); ?>
<option value="<?php echo $_POST["optionValue"]; ?>">
<?php echo $_POST["optionValue"]; ?>
</option>
</select>
On Script:
<script>
$(document).ready(function(){
$("#booking_date").change(function(){ //listen when the option change
var optionValue = $(this).val(); //get the new value
$.ajax({
url: "doctordetails.php", //php file which recive the new value and save it to the database
data: { getValue: optionValue }, //send the new value
type: "POST" , //use POST method
success: function(data) {
console.log(data);
}
});
});
});
</script>

PHP Ajax dependent dropdown not working

I am trying to implement dependent dropdown using ajax and php. But anyhow the response from second dropdown is not coming. after checking in console, I am able to see the id of first dropdown but no response from second dropdown. So, When i click on first dropdown, I just get a blank value in Second dropdown.
HTML Code
<div class="col-md-6">
<?php
require_once('db.php');
$varient_result = $conn->query('select * from tv_varient');
?>
<select name="varient" id="varient-list" class="form-control c-square c-theme" required>
<option value="">Select Varient</option>
<?php
if ($varient_result->num_rows > 0) {
// output data of each row
while($row = $varient_result->fetch_assoc()) {
?>
<option value="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></option>
<?php
}
}
?>
</select>
</div>
</br></br>
<label for="inputPassword3" class="col-md-4 control-label" style="margin-left: 15px;">Price:</label>
<div class="col-md-6">
<select name="price" id="price-list" class="form-control c-square c-theme" required>
<option value=''>Select Price *</option>
</select>
<div>
</div>
</div>
</div>
</div>
</div>
AJAX Code
<script>
$('#varient-list').on('change', function(){
var varient_id = this.value;
$.ajax({
type: "POST",
url: "get_price.php",
data:'varient_id='+varient_id,
success: function(result){
$("#price-list").html(result);
}
});
});
</script>
get_price.php
?php
require_once('db.php');
//$country_id = mysqli_real_escape_string($_POST['country_id']);
//var_dump($country_id);
//var_dump($_POST['country_id']);
$varient_id = $_POST['veriant_id'];
echo $varient_id;
//var_dump($varient_id);
var_dump($_POST['varient_id']);
if($varient_id!='')
{
$states_result = $conn->query('select * from tv_price where veriant_id='.$varient_id.'');
$options = "<option value=''>Select Price</option>";
while($row = $states_result->fetch_assoc()) {
$options .= "<option value='".$row['price']."'>".$row['price']."</option>";
}
echo $options;
}
?>
Try below code,
$(document).on('change', '#varient-list', function(e)
{
var varient_id = this.value;
$.ajax({
type: "POST",
url: "get_price.php",
data:'varient_id='+varient_id,
success: function(result){
$("#price-list").html(result);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
varient_id & veriant_id on the POST is wrong (the e & a difference).
$varient_id = $_POST['veriant_id']; should be $varient_id = $_POST['varient_id'];

jQuery ReferenceError: function is not defined

I have a simple jquery function that reflects the selected value of a dropdown to textbox but the problem is that the console says that my function was undefined. I put the function inside the onchange event of the dropdown. Please note that all of my jquery functions was on the bottom of the page..
and here is the dropdown:
<div class="form-group">
<label class="control-label">Operation</label>
<select class="form-control" id="operationName" name="operationName">
<option value="">-SELECT-</option>
<?php
foreach($operation as $val)
{
?>
<option value="<?php echo $val['OperationName'];?>"><?php echo $val['OperationName'];?></option>
<?php
}
?>
</select>
<span class="text-danger"><?php echo form_error('operation');?></span>
<input type="text" class="form-control" id="deldays" name="deldays"
value="" />
this is the operation array model
function getDeliveryDays($str)
{
$this->db->select('DeliveryDays');
$this->db->from('operation');
$this->db->where('OperationName',$str);
return $this->db->get()->result();
}
this is the controller:
public function getDays()
{
$id = $this->input->post('q');
$data['days'] = $this->wip_model->getDeliveryDays($id);
echo json_encode($data);
}
I took the working in my other project and use it in my current project but still the same result and when I inspect it in the dev tools, the said script is missing in view source but it's present in IDE:
this is the code:
function showDeliveryDay(operation)
{
$.ajax({
type: "POST",
url: "<?php echo site_url('wip/getDays/');?>",
data: {q:operation},
success: function(data){
console.log(data);
},
});
}
Thanks in advance....
Does you put the function inside domready? If so, remove that and placed it outside like so :
<script>
function showDays() {
var x = document.getElementById("operationName").value;
document.getElementById("deldays").innerHTML = x;
}
// domready here
$(function(){...}); // or $(document).ready(function(){...});
</script>
Make sure you are including your jquery in your code. try this:
jQuery( document ).ready(function() {
jQuery( "#operationName" ).change(function() {
var pVal = jQuery("#operationName").val();
jQuery("#deldays").val(pVal);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label">Operation</label>
<select class="form-control" id="operationName" name="operationName">
<option value="">-SELECT-</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<span class="text-danger"></span>
<input type="text" class="form-control" id="deldays" name="deldays"
value="" />
</div>
You can refer this code
Html
<div class="form-group">
<label class="control-label">Operation</label>
<select class="form-control" id="operationName" name="operationName">
<option value="">-SELECT-</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<span class="text-danger"></span>
<input type="text" class="form-control" id="deldays" name="deldays"
value="" />
Js code
jQuery( document ).ready(function() {
jQuery('#operationName').on('change', function(){
var p=jQuery(this).val();
jQuery("#deldays").val(p);
});
});
You can view demo here

Removing dynamic dropdown options after JQuery AJAX request

I have a form that includes a dropdown box. This dropdown's options are filled dynamically, using PHP, from my database. When my form is submitted, the row containing the ticketId selected in the dropdown is removed from the database. What I would like is for, after the AJAX call is successful, have this list repopulate without the row that was just removed.
my form:
<form name="transferTicketForm" id="transferTicketForm">
<div class='form-group'>
<label for="ticket_number">Choose ticket:</label>
<select name="ticket_number" id="ticket_number" class="form-control">
<?php foreach ($assigned_tickets as $ticket): ?>
<option value="<?php echo($ticket->ticketId); ?>"><?php echo ($ticket->ticketId . " - " . $ticket->headline); ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="assignTo">Transfer to:</label>
<select name="assignTo" id="assignedTo" class="form-control">
<?php foreach($employees as $employee): ?>
<option value='<?php echo($employee->userId); ?>'><?php echo ($employee->firstName . " " . $employee->lastName);?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="transferComment">Comment:</label>
<textarea name="transferComment" id="transferComment" class="form-control"></textarea>
</div>
<div class="text-center">
<input class="btn btn-primary" type="button" id="doTransferTicketButton" value="Transfer Ticket">
</div>
</form>
my Ajax call:
$('#doTransferTicketButton').click(function(){
$.ajax({
type:'POST',
url:'<?php echo site_url();?>ticket_system/transfer_and_comment_ticket',
data:{
'assigned': $('#assignedTo').val(),
'comment': $('#transferComment').val(),
'ticketId': $('#ticket_number').val()
},
success: function(data){
$target_ticket = $('#ticket_number').val();
$('#ticket_' + $target_ticket).remove();
$('#assigned').empty();
$('#transferTicketOptions').slideToggle();
}
});
});
Things I have tried:
success: function(data){
$target_ticket = $('#ticket_number').val();
$('#ticket_' + $target_ticket).remove();
$('#ticket_number').empty();
$('#transferTicketOptions').slideToggle();
}
and
success: function(data){
$target_ticket = $('#ticket_number').val();
$('#ticket_' + $target_ticket).remove();
$('#ticket_number')[0].reset();
$('#transferTicketOptions').slideToggle();
}
Neither of which work for what I'm trying to do.
Any help would be greatly appreciated. Thank you!
First make your AJAX-file echo the ticket ID when removed. This ID will be passed to the success function. And on successs run:
success: function(data){
$("#ticket_number option[value=data]").remove();
}
The code is not testet, but i think it would work.

Categories