POST something using editable dropdown - php

I made an editable dropdown menu :
<html>
<body>
<div style="position:relative;width:200px;height:25px;border:0;padding:0;margin:0;">
<select style="position:absolute;top:0px;left:0px;width:200px; height:25px;line-height:20px;margin:0;padding:0;" onchange="document.getElementById('displayValue').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;">
<option></option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
<input type="text" name="displayValue" placeholder="add/select a value" id="displayValue" style="position:absolute;top:0px;left:0px;width:183px;width:180px\9;#width:180px;height:23px; height:21px\9;#height:18px;border:1px solid #556;" onfocus="this.select()">
<input type="hidden" name="idValue" id="idValue">
</div>
</body>
</html>
I want to POST the value that was added, so as to include it in drop down for the next round.

I suggest you use jQuery for easy implementation. You can wrap them in a form and do the POSTing via jQuery Ajax then store that value somewhere for future use then append it to the next as the new option item.
POST via aJax
$(function() {
$('#form').on('submit', function(e) {
// do not reload the page
e.preventDefault();
// do the posting
var newValue = $('#displayValue').val();
$.post('http://MYURL.com/post.php', {
new_field: newValue
}, function(data) {
// success callback
$('#form > select').append('<option value="'+newValue+'">'+newValue+'</option>');
})
});
})
Basically, you post newValue to http://MYURL.com/post.php and handle that new data then the success callback will handle the inserting of the new value to your select.
the code is not tested, let me know if it did not work
Learn more about jquery.post() here and more about jquery here

Related

Ajax does not work in jquery for redirecting to php page

Problem with ajax, when clicking the Properties button, it does not go to the desired page in any way. I tried to add a link jquery in the head and in the body.
I have two inputs and a button Save.
When the button Save is clicked, the input values are added to tags, and create button Properties. Then when clicked Properties button, ajax should work, but it does not work.
search.php
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<div>
<input type="search" name='search1' list="doc" id="inp1">
<datalist id='doc'>
<option value="virgil">Virgil</option>
<option value="alistair">Alistair</option>
</datalist>
</div>
<div>
<input type="search" name='search2' list="doc2" id="inp2">
<datalist id='doc2'>
<option value="sherman">Sherman</option>
<option value="dejesus">Dejesus</option>
</datalist>
</div>
<div>
<button name='btn' id='btn'>Save</button>
</div>
<div id='div1'></div>
<div id='div2'></div>
<div id='div3'></div>
<script src="scripts.js"></script>
</body>
</html>
scripts.js
$(function() {
$('#btn').click(function() {
let inp1 = $('#inp1').val(); // the value of the first input
let inp2 = $('#inp2').val(); // the value of the second input
let div1 = $('#div1');
let div2 = $('#div2');
let div3 = $('#div3');
div1.html(inp1)
div2.html(inp2);
if(inp1 && inp2) { // if there are both values create button
let btn = $('<button>Properties</button>');
div3.html(btn);
btn.click(function() {
console.log('hello') // It work's
$.ajax({ // when the button is clicked, it should redirect to another page, but it does not work
url: 'new.php',
method: 'post',
data: inp1, inp2,
action: 'prop'
})
})
}
})
})
Thank you.
You shouldn't use Ajax to redirect pages.
Ajax is more like background threading.
In your situation, you should build a form with js and POST data to new.php via php.

How to apply the jQuery classes to HTML elements generated through AJAX response so that the jQuery functionality should be workable?

I'm using PHP, jQuery for my website. I've following HTML elements which are present on the page when the page loads.
//Date picker controls
<input class="form-control date_control" placeholder="yyyy-mm-dd" type="date" name="rebate_start_date[1]" id="rebate_start_date_1" value="">
<input class="form-control date_control" placeholder="yyyy-mm-dd" type="date" name="rebate_expiry_date[1]" id="rebate_expiry_date_1" value="">
//Select control
<select class="states" multiple="multiple" name="applicable_states[1]" id="applicable_states_1">
<option value="1">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
<option value="4">Arkansas</option>
<option value="5">California</option>
</select>
In the above code, I've added jQuery classes to the HTML controls to make the jQuery functionality workable.
.date_control for two date picker controls
.states for select control
The jQuery code for above HTML elements with the above specified classes is as follows:
$(document).ready(function() {
//code for datepicker
$(".date_control").datepicker({
dateFormat: "yy-mm-dd"
});
//code for states
$('.states').multiselect({
includeSelectAllOption: true,
maxHeight: 150
});
});
Now on click of a button present on a page I'm calling AJAX function as follows.
<button style="float:right" class="add_new_rebate" type="button" class="btn btn-default" onclick="add_rebate_by_product(); return false;"><i class="icon-plus"></i> Add New Rebate</button>
Then in AJAX function I'm giving call to a PHP file. In PHP file I'm making the response and sending it back to the AJAX request. Till here everything works fine. But the issue I'm facing is the non-working of jQuery functionality on the HTML controls I added through AJAX response. I've taken care of adding the same classes as above while preparing the PHP response. Even if I check the source HTML by inspecting the respective HTML elements, the jQuery classes are present over there but functionality is still not working. For your reference I'm giving below the AJAX request code and the response preparation code from PHP file:
//AJAX request code
function add_rebate_by_product() {
var manufacturer_id = $("#company_id").val();
var next_rebate_no = $('.rebate_block').length + 1;
var rebate_no = $('.rebate_block').length + 1;
if ($('.rebate_block').length>0) {
rebate_no = rebate_no+1;
}
$('.add_new_rebate').attr('disabled','disabled');
$.ajax({
type: "POST",
url: "add_rebate_by_product.php",
data: {'request_type':'ajax', 'op':'create_rebate', 'next_rebate_no':next_rebate_no, 'rebate_no':rebate_no, 'manufacturer_id':manufacturer_id},
beforeSend: function() {
$('.table-responsive').after("<img src='http://localhost/smart-rebate-web/web/img/ajax-loader.gif' class='load' alt='Loading...'>");
},
success: function(data) {
if(jQuery.trim(data)=="session_time_out") {
window.location.href = site_url+'admin/login.php?timeout=1';
} else {
$('.rebate_block').append(data);
$('.add_new_rebate').removeAttr('disabled');
}
$('.load').remove();
}
});
}
//PHP code snippet to prepare response
<?php
$op = $_REQUEST['op'];
switch( $op ) {
case "create_rebate":
echo "<input class='form-control date_control' placeholder='yyyy-mm-dd' type='date' name='rebate_start_date[$rebate_no]' id='rebate_start_date_$rebate_no' value=''><input class='form-control date_control' placeholder='yyyy-mm-dd' type='date' name='rebate_expiry_date[$rebate_no]' id='rebate_expiry_date_$rebate_no' value=''>
<select class='states' multiple='multiple' name='applicable_states[$reabate_no]' id='applicable_states_$reabate_no'>
<option value='1'>Alabama</option>
<option value='2'>Alaska</option>
<option value='3'>Arizona</option>
<option value='4'>Arkansas</option>
<option value='5'>California</option>
</select>";
exit;
}
?>
I googled a lot about this but still couldn't get the perfect solution which could make the jQuery functionality workable for HTML controls added using AJAX. So can anyone please help me in this regard? Thanks for spending some of your valuable time in understanding my issue. If you need any kind of information regarding the question I can provide you the same. Any kind of help, comments, suggestions, answers will be highly appreciated. Waiting for your precious replies.
Wrap the initialization code in a function:
function initializeControls(){
//code for datepicker
$(".date_control").datepicker({
dateFormat: "yy-mm-dd"
});
//code for states
$('.states').multiselect({
includeSelectAllOption: true,
maxHeight: 150
});
}
Then call it in your ajax callback:
success: function(data) {
if(jQuery.trim(data)=="session_time_out") {
window.location.href = site_url+'admin/login.php?timeout=1';
} else {
$('.rebate_block').append(data);
$('.add_new_rebate').removeAttr('disabled');
initializeControls();
}
$('.load').remove();
}

Populate a PHP variable from a listbox value with AJAX

I retrieve the value of a select box in this way which goes to populate a input field:
<script>
$(document).ready( function ()
{
$('#dropdown_selector').change(function()
{
var option = $(this).find('option:selected').val();
$('#showoption').val(option);
});
});
</script>
<select id="dropdown_selector">
<option value="Option1">Option1</option>
<option value="Option2">Option2</option>
<option value="Option3">Option3</option>
</select>
<label>Value</label>
<input type="text" name="name" id="showoption" disabled="disabled" />
</label>
But my problem is how to retrieve that value and use it directly in a PHP variable,instead of populating the input field(with id showoption).
Something similar as:
$variable=(var selected in select box)
Thanks for your help!!!
This jQuery code is triggered when an option is selected and then stores the value of the option into variable valu. After that it sends the variable to your php document via Ajax post.
$('select').change(function(){
var valu=$( "select option:selected" ).attr('value');
$.ajax({
type:"POST",
url:"yourphpscript.php",
data: {values:valu}
});
});
http://jsfiddle.net/joey6978/peq74/ :this fiddle shows the select choosing trigger.
In your php script you should have the post method with the name values to recieve your data.
$myvariable=$_POST['values'];

Load <select> options via a MySQL table, and allow the user to add to it via jQuery

I have a MySQL table which looks like this:
ID OPTION
1 First
2 Second
The user sees the following:
<div id="options">
<select>
<option value="1">First</option>
<option value="2">Second</option>
</select>
</div>
I would like the user to have the option to insert into the table, as follows:
<div id="add">
<input type="text" name="newOption" placeholder="Your own option">
<input type="button" value="Add">
</div>
It would then select their newly-added option:
<div id="options">
<select>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3" selected>Third</option>
</select>
</div>
As the above code is part of a page which contains other form elements the page can't be reloaded, otherwise the data they've already typed will disappear. So I'd like to use jQuery.
EDIT: I have tried the following but it adds rows twice, sometimes even four times, for reasons I cannot fathom!
$("#button").click(function(){
var test = $("#<?php echo $selectName; ?>").val();
var dataString = 'select=<?php echo $select; ?>&selectName='+ test;
$.ajax({
type: "POST",
url: "optionAdd.php",
data: dataString,
cache: false,
success: function(html){
$("#<?php echo $select; ?>List").load("optionList.php?select=<?php echo $select; if ($_GET[required] == "no") { echo "&required=no"; } ?>");
}
});
});
The reason for the PHP above is I want to use multiples of this code on the same form and so I'm using GET to select the options, as it were.
You would need to send an AJAX request to server with the new data and get an ID returned for this new option. Once the ID is received you can create the option with the new ID as value and the user defined text
$('#add button').click(function(){
/* get value from previous input*/
var newOpt=$(this).prev().val();
/* make AJAX "POST" request*/
$.post( 'path/to/server/file', { newOption: newOpt}, function( newId ){
/* ajax successfully completed, add new option*/
$('#options select').append('<option value="'+ newId +'">'+newOpt+'</option>');
});
return false; /* prevent browser default handling of button click*/
})
At server receive the data as you would a form field with name="newOption" ie $_POST['newOption'] and send back a new ID as text
Alternatively you could send back all the options as html in sort order you want and replace all the options in the select.
/* ajax to replace all options with html from server*/
$.post( 'path/to/server/file', { newOption: newOpt}, function( response ){
/* ajax successfully completed, add new option*/
$('#options select').html( response);
});
I would suggest using jQuery AJAX to call a PHP Script to store the new option to the database, that returns the new ID and the given option name on success and then add the new entry to the <select> using Javascript.

multi cloned select menu to submit form using Jquery?

im trying to make a simple form which have a select menu with clone and remove button and once any of those select menus changed it must post the form using .Ajax call .
its working but have some issues
HTML
<form action="action.php" method="post" id="LangForm" >
<div id="fileds">
<select name="lang[]" id="lang" class="lang">
<option value="">Select</option>
<option value="arabic">Arabic</option>
<option value="english">english</option>
</select>
</div>
</form>
<button class="clone">Clone</button>
<button class="remove">Remove</button>
<div id="content"></div>
JS
$(function(){
var counter = 1;
$(".clone").click(function(){
$('#lang').clone().appendTo('#fileds');
counter++ ;
});
$(".remove").click(function(){
if (counter > 1) {
$('#lang:last').remove();
counter-- ;
}
});
$('.lang').change(function(){
$.ajax({type:'POST',
url: 'action.php',
data:$('#LangForm').serialize(),
success: function(response) {
$('#content').html(response);
}
});
});
});
it have 2 issues
first one when i click the remove button it remove the original select menu first then the cloned one and keep the last cloned one what i need is to remove the cloned menus first and keep the original one
second issue its submit form only when original menu changed what i need is to submit form whenever any menu changed original or cloned.
below is the PHP code from the action PHP page its something simple just to show result
PHP
<?php
print_r ($_POST['lang']);
?>
Thanks
HTML:
<form action="action.php" method="post" id="LangForm" >
<div id="fileds">
<select name="lang[]" class="lang">
<option value="">Select</option>
<option value="arabic">Arabic</option>
<option value="english">english</option>
</select>
</div>
</form>
<button class="clone">Clone</button>
<button class="remove">Remove</button>
<div id="content"></div>​
Note: Id of the field has been removed.
JS:
$(function(){
$(".clone").click(function(){
// clone(true) will clone the element with event handlers intact.
$('.lang').last().clone(true).appendTo('#fileds');
});
$(".remove").click(function(){
var selects = $('.lang');
if (selects.length > 1) {
selects.last().remove()
}
});
$('.lang').change(function(e){
// console.log(e)
$.ajax({type:'POST',
url: 'action.php',
data:$('#LangForm').serialize(),
success: function(response) {
$('#content').html(response);
}
});
});
});​
Demo:
http://jsfiddle.net/kFB5j/1/

Categories