How to Post Data to the Same Page with JQuery - javascript

Basically all I am trying to do is send the form data to the same location of the form.
The code should:
Get the #submit click action
Extract #email, #selection1, and #selection2's data
Hide the form #form
Display #email, #selection1, and #selection2 inside paragraph #preview
I have no JQuery experience so I am lost. I tried looking around and trying different codes but nothing would work for me.
My form code is:
<form method="post" id="form">
<div class="form-group col-lg-10 col-lg-offset-1">
<input type="email" id="email" class="form-control" name="email" placeholder="Email" />
</div>
<div class="form-group col-lg-10 col-lg-offset-1">
<select class="form-control" id="selection1">
<option>Option 1</option>
<option>Option 2</option>
</select>
</div>
<div class="form-group col-lg-10 col-lg-offset-1">
<select class="form-control" id="selection2">
<option selected="selected">Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>
</select>
</div>
<div class="form-group col-lg-offset-1 col-lg-10">
<button type="button" id="submit" class="btn btn-primary btn-lg">Sign in</button>
</div>
</form>
<p id="preview"></p>
Here is the JQUery I tried.
<script type="text/javascript">
$("#submit").click(function () {
var FormVal = {
datafield1: $('#email').val(),
datafield2: $('#field2').val()
};
$.ajax({
type: "POST",
dataType: "json",
data: FormVal,
async: false,
success: function (response) {
$('#preview').html($('#email').val() + '<br />' + $('#selection1').val()) + '<br />' + $('#selection2').val());
}
});
});
</script>

You don't have to go through all those AJAX stuffs to accomplish what you need. You can simply hide the form and then set the value to the paragraph #preview
$("#submit").click(function () {
//get value like this..
var datafield1 = $("#email").val();
//hiding the form
$("#form").hide(function () {
//setting the text to #preview
$('#preview').html(
$('#email').val() + '<br />' + $('#selection1').val() + '<br />' + $('#selection2').val());
});
});
Here is a jsfiddle link of the working code.

$('#preview').html($('#email').val() + '<br />' + $('#selection1').val()) + '<br />' + $('#selection2').val());
You have an extra parentheses in this code here: $('#selection1').val()). You can use the console of your browser to debug syntax errors.

Related

Form repeater with select option does not work with ajax response

I am trying to build the form repeater where ID and Datapoint are select tag. When I select ID than Datapoint will be taken from AJAX response and appended to option. In the picture you can see when I call for select for the first time the datapoint (select tag) is showing the values but when trying to add another the datapoint there is no response.
<form method="post" class="repeater" enctype="multipart/form-data">
<div data-repeater-list="samplernetwork">
<div data-repeater-item="data-repeater-item" class="row">
<div class="mb-3 col-lg-2">
<label for="id">ID</label>
<select class="form-control" name="id" id="id">
<option></option>
{% for id in id %}
<option value="{{id.id}}">{{id.id}}</option>
{% endfor %}
</select>
</div>
<div class="mb-3 col-lg-2">
<label for="datapoint">Datapoint</label>
<select class="form-control" name="datapoint" id="datapoint"></select>
</div>
<div class="col-lg-2 align-self-center">
<div class="d-grid">
<input data-repeater-delete="data-repeater-delete" type="button" class="btn btn-primary" value="Delete"/>
</div>
</div>
</div>
</div>
<input data-repeater-create="data-repeater-create" type="button" class="btn btn-success mt-3 mt-lg-0" value="Add"/>
</form>
<script src="/libs/jquery.repeater/jquery.repeater.min.js"></script>
<script src="/js/pages/form-repeater.int.js"></script>
<script>
$("#id").on('change', function (e) {
var consti = $(this).val()
console.log(consti)
if (consti === "") {
$('#datapoint').find('option').remove()
} else if (consti != null) {
var url = '{{path(' app_info ',{' id ':' ReplaceMeWithCorrectValue '})}}';
url = url.replace("ReplaceMeWithCorrectValue", consti);
var options = ""
$.ajax({
type: "POST",
url: url,
success: function (response) {
var information = JSON.parse(response)
for (let item in information) {
options += `<option value=${item}>${item}</option>`;
}
$("#datapoint").html(options);
}
});
}
});
</script>
<script src="/js/app.js"></script>
The solution of the code
<form id="repeater-form">
<div class="repeater">
<div data-repeater-list="group-a">
<div data-repeater-item>
<select name="field-1" class="field-1">
<option value="">Select an option</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<select name="field-2" class="field-2" disabled>
<option value="">Select an option</option>
</select>
<button data-repeater-delete type="button">Delete</button>
</div>
</div>
<button data-repeater-create type="button">Add</button>
</div>
<input type="submit" value="Submit" />
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.repeater/1.2.1/jquery.repeater.min.js"></script>
<script>
$(document).ready(function () {
$('.repeater').repeater({
initEmpty: false,
show: function () {
$(this).slideDown();
},
hide: function (deleteElement) {
if(confirm('Are you sure you want to delete this element?')) {
$(this).slideUp(deleteElement);
}
}
});
$(document).on('change', '.field-1', function() {
var selectedValue = $(this).val();
var $field2 = $(this).closest('div[data-repeater-item]').find('.field-2');
$.ajax({
type: 'GET',
url: 'options.php',
data: {'value': selectedValue},
success: function (response) {
var options = JSON.parse(response);
var select = $field2;
select.empty();
select.append('<option value="">Select an option</option>');
for (var i = 0; i < options.length; i++) {
select.append('<option value="' + options[i].value + '">' + options[i].text + '</option>');
}
select.prop('disabled', false);
}
});
});
$('#repeater-form').submit(function (e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: 'server-script.php',
data: formData,
success: function (response) {
alert(response);
}
});
});
});
</script>

How to get array id in ajax append?

i have an appended, there a selectbox with 2 textbox
first the selectbox will selecting an item, after on change, it will set all the textbox with data based on selected.
my select option calling data from database array $data.
this is my ajax code
function getBarang(val) {
$.ajax({
url: baseurl + "JSON/getBarang",
// url: baseurl + "JSON/getVal" + val,
type:"POST",
data:{"get_barang":val},
dataType:"JSON",
success:function(data){
$('#harga_jual').val((data[0].harga_jual));
$('#stock_sisa').val((data[0].stock_sisa));
}
});
}
this is my form
echo '<select name="barang[]" id="barang-'.$row.'" class="s2barang form-control" onchange="getBarang(this.value)">';
echo (isset($dBarang->id_barang)) ? '<option value="' . $dBarang->id_barang.'">' . $dBarang->nama_barang . '</option>' : '';
echo ' </select> ';
echo '
<input type="text" class="form-control" name="stock_sisa" id="stock_sisa">
<input type="text" class="form-control" name="harga_jual" id="harga_jual">
lets pass about query data, because its worked.
and this is my view as result
my second textbox not working, pls help me, thanks
Edited:
Let me explain more.
the target is textbox stock sisa, and textbox harga_jual
the $dBarang created like this, $row just like $i=0, for cheching last data on database
$dataBarang = $this->m_db->getDataWhere("v_pembelian_detail","id_pembelian","'$id_p' ORDER BY id_pembelian_detail");
$dataBarang = (empty($dataBarang)) ? [''] : $dataBarang;
foreach ($dataBarang as $dBarang)
{
You can pass this as well inside your function where this refer to current select-box where change has been taken place. Then , using this you can use $(el).closest('.outer').find('.harga_jual').. to add input values to required inputs only.
Demo Code :
//just for demo..
var data = [{
"harga_jual": "soemthing",
"stock_sisa": "soemthing1"
}]
function getBarang(val, el) {
/*$.ajax({
url: baseurl + "JSON/getBarang",
// url: baseurl + "JSON/getVal" + val,
type: "POST",
data: {
"get_barang": val
},
dataType: "JSON",
success: function(data) {*/
//get closest div > get input add value there..
$(el).closest('.outer').find('.harga_jual').val(data[0].harga_jual);
$(el).closest('.outer').find('.stock_sisa').val(data[0].stock_sisa);
/* }
});*/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--add sme outer div-->
<div class="outer">
<select name="barang[]" id="barang-'.$row.'" class="s2barang form-control" onchange="getBarang(this.value ,this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" class="form-control stock_sisa" name="stock_sisa">
<input type="text" class="form-control harga_jual" name="harga_jual">
</div>
<div class="outer">
<select name="barang[]" id="barang-'.$row.'" class="s2barang form-control" onchange="getBarang(this.value ,this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" class="form-control stock_sisa" name="stock_sisa">
<input type="text" class="form-control harga_jual" name="harga_jual">
</div>
<div class="outer">
<select name="barang[]" id="barang-'.$row.'" class="s2barang form-control" onchange="getBarang(this.value ,this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" class="form-control stock_sisa" name="stock_sisa">
<input type="text" class="form-control harga_jual" name="harga_jual">
</div>
this is what i get from changing my id to class
function getBarang(val) {
$.ajax({
url: baseurl + "JSON/getBarang",
// url: baseurl + "JSON/getVal" + val,
type:"POST",
data:{"get_barang":val},
dataType:"JSON",
success:function(data){
$('.harga_jual').val((data[0].harga_jual));//before #harga_jual
$('.stock_sisa').val((data[0].stock_sisa));//before #stock_sisa
}
});
}
but the data seem the last selected and change to all :(
i want it each selected

How to get two form input values to Javascript console.log

I have a form composed of two fields.
Once the form filled, I'd like to get the two fields in a console.log that would display 'Field 1 ' + field1 + 'Field 2 ' + field2.
I know how to make it to display the value of one field but I'm getting stuck on doing this in two fields..
How would it be possible to complete this ?
Here is the HTML part :
<form name="Test">
<div class="form-group col-md-9">
<label for="inputState">Field1</label>
<select id="sel-inv" name="sel-inv" class="form-control">
<option value=""></option>
<?php
while($data1 = pg_fetch_array($queryInv))
{
echo ("<option value=". $data1['gid'].">". $data1['gid']. "</option>");
}
?>
</select>
</div>
<div id="nom-dossier" class="form-group col-md-4">
<label for="exampleInputPassword1">Field2</label>
<input type="text" class="form-control" id="nom-dossier-sel" name="nom-dossier-sel">
</div>
</form>
And that's the JS part :
<script>
document.getElementById('sel-inv').addEventListener('input', function() {
var field1 = this.value;
console.log ('Field 1 ' + field1);
});
</script>
Thanks for the help !
The form element has all the values with their names.
document.getElementById("form").onchange = function(e){
var form = e.target.form;
console.log(form["sel-inv"].value, form["nom-dossier-sel"].value);
}
<form name="Test" id="form">
<div class="form-group col-md-9">
<label for="inputState">Field1</label>
<select id="sel-inv" name="sel-inv" class="form-control">
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div id="nom-dossier" class="form-group col-md-4">
<label for="exampleInputPassword1">Field2</label>
<input type="text" class="form-control" name="nom-dossier-sel">
</div>
</form>
This modified code will do as requested:
document.getElementById('sel-inv').addEventListener('input', function() {
var field1 = this.value;
let field2 = document.getElementById(‘nom-dossier-sel’).value;
console.log ('Field 1 ' + field1 + ' Field 2 ' + field2);
});
You can assign a custom data attribute to all field and on change of any field you can get the element by queryselector of data-field
OR
Recommended using actually id or class to get properties. You will have more control.
document.getElementById("sel-inv").addEventListener("change", function () {
const [f1, f2] = Array.from(
document.querySelector("form").querySelectorAll("[data-field='field']")
);
console.log(f1, f2);
});
<form name="Test">
<div class="form-group col-md-9">
<label for="inputState">Field1</label>
<select id="sel-inv" name="sel-inv" class="form-control" data-field="field">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div id="nom-dossier" class="form-group col-md-4">
<label for="exampleInputPassword1">Field2</label>
<input type="text" class="form-control" id="nom-dossier-sel" name="nom-dossier-sel" data-field="field">
</div>
</form>

Search data using select tags with multiple option in php using ajax

I was trying to search data from database using multiple select tags on onchange select tags, I have four select tags with multiple select option. here is form
<form method="GET" id="first_form" >
<div class="col-md-3">
<div class="form-group">
<label>Maintenance</label>
<select id="chkveg" name="maintenance[]" multiple="multiple">
<option value="21">Low</option>
<option value="23">Medium</option>
</select>
</div>
<input type="hidden" id="btnget" value="Get Selected Values" />
</div>
<div class="col-md-3">
<div class="form-group">
<label>Lighting </label>
<select id="chkveg1" name="lighting[]" multiple="multiple">
<option value="24">indoors: iow light</option>
<option value="25">indoors: medium light</option>
</select>
</div>
<input type="hidden" id="btnget1" value="Get Selected Values" />
</div>
<div class="col-md-3">
<div class="form-group">
<label>Shade </label><br/>
<select id="chkveg2" name="shade[]" multiple="multiple">
<option value="30">Low</option>
<option value="31">Medium</option>
</select>
</div>
<input type="hidden" id="btnget2" value="Get Selected Values" />
</div>
<div class="col-md-3">
<div class="form-group">
<label>Other</label><br/>
<select id="chkveg3" name="other[]" multiple="multiple">
<option value="40">Low</option>
<option value="41">Medium</option>
</select>
</div>
</div>
</form>
<div class="col-md-3" id="form-content">
</div>
and my database table structure is
search criteria is "If I select multiple options from one select tag, It should search using OR operator and If i select a option from second select tag, It should search using AND operator."
For example : In above form,If i select two option from maintenance tag, search using OR operator with one pl_maintenance_search column, If i select one option from lighting select tag, search using AND between pl_maintenance_search and pl_lighting_search. and same with other select tags.
I am submitting this form using this script
$("form select").on('change', function () {
var dataString = $("#chkveg, #chkveg1, #chkveg2, #chkveg3").serialize();
$.ajax({
url: 'ajax_file.php',
type: 'GET',
data: dataString,
dataType: 'html'
})
.done(function(data){
$('#form-content').html(data);
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
and here is my ajax_file.php code
$operator='OR';
$all_array = $_GET;
$unque_array = array();
$count=0;
foreach ($all_array as $main_key => $value )
{
if($main_key)
{
$count++;
}
if($count>1){ $operator='AND'; }
foreach ($value as $r_value)
{
$single = $r_value;
$query = "SELECT * FROM tbl_pl_details WHERE pl_maintenance_search LIKE ? $operator pl_lighting_search LIKE ? $operator pl_shade_search LIKE ? $operator pl_other_search LIKE ? ";
$params = array("%$single%", "%$single%", "%$single%", "%$single%" );
$select_maint_plants = $con->prepare($query);
$select_maint_plants->execute($params);
while($fetch_light_plants = $select_maint_plants->fetch(PDO::FETCH_ASSOC))
{
if(!in_array($fetch_light_plants['id'], $unque_array))
{
echo $fetch_light_plants['pl_name']; echo '<br/>';
}
$unque_array[]= $fetch_light_plants['id'];
}//End while loop
}//End foreach loop
}//End foreach loop
Above code is working with only single select tag, and not with others tag.
Please help me to solve this.

get jQuery form - text value by id

I have a simple html with jQuery form , and i want to:
1) get the value into a js var .
2)send it by JSON to a server .
here is the form :
<div data-role="main" class="ui-content">
<data=role "form" name="seekerForm" id="jobSeekerForm" >
<label for="basic">First name :</label>
<input type="text" name="seekerName" id="WfirstName" data-mini="true" />
<label for="basic">Last name :</label>
<input type="text" name="seekerLast" id="WlastName" data-mini="true" />
<label for="basic" id="WEmail">E-mail:</label>
<input type="text" name="seekerEmail" id="WEmail" data-mini="true" />
<div data-role="fieldcontain" >
<label for="select-choice-1" class="select" >Choose a field:</label>
<select name="select-choice-1" id="selectField" >
<option value="HI-TEC">Software Programming</option>
<option value="webPro">Web Programming</option>
<option value="QA">QA</option>
<option value="systemInfo">System Information</option>
<option value="DB">DBA</option>
<option value="java">JAVA</option>
<option value="c">c++</option>
<option value="pyt">pyton</option>
</select>
</div>
<div data-role="fieldcontain" >
<label for="select-choice-1" class="select" >Choose Experience level:</label>
<select name="select-choice-1" id="selectPro" >
<option value="junior">junior(0-2)</option>
<option value="senior">senior(2-5)</option>
<option value="exp">Expert(5-10)</option>
</select>
</div>
</form>
3) same thing to the option value .
Here is the way im sending :
// the object i want to send :
var jobsData = {
name: $name.val(),
lname: $WlastName.val(),
mail: $WEmail.val(),
userlocation: location,
field : $selectField.val(),
Pro: $selectPro.val(),
range: $sliderRange.val()
};
// ajax - data: how i want to send that
$.ajax({
type: 'GET',
dataType: 'JSON',
url:'http://localhost:8888',
data: jobsData,
success: function(jobs){
$.each(jobs,function(i,job){
$('.jobRes').html(jobs);
});
You can use .serialize() to get all the form values and send them to the server via ajax. Something like this would do:
$(function() {
$('form').on('submit', function( e ) {
e.preventDefault();
$.ajax( url:'http://localhost:8888/', data: $(this).serialize(), ..... );
});
});
Your page must be running on the same localhost same port 8888 for this to work.
You might want to checkout the jQuery .serialize() method for getting the form values.
http://api.jquery.com/serialize/

Categories