update a select box without page refresh - php

is it possible to add a new option dynamically to a select box and also can be added to the database using Ajax. i am looking for a button which appends new option to the select box as well as to add that field to the database. Thanks...
EDIT 2
is it possible to update the select box values without page refresh, The case is when i adds new data to database and not making use of .append here...

Try this
This is for add new option in select
$('select').append('<option value="0">--Select--</option>');
And after adding new option you can call ajax
$.ajax({
url:'url',
data:'data',
type:'post',
success:function(data){
}
});
In server side put code to save data in database.
Edit
$.ajax({
url:'url',
data:'data',
type:'post',
success:function(data){
//data will be list of values which you want in options and this sent from server side in json result
$(data).each(function(index,item){
$('select').append('<option value="'+item.val+'">'+item.name+'</option>');
});
}
});

Do you mean something like this?
JSFiddle: http://jsfiddle.net/s4yh3Lor/1/
HTML
<button id="pop-btn">Populate</button>
<select id="options-box">
<option value='1'>Option 1</option>
</select>
jQuery
$(document).ready(function(){
$("#pop-btn").on("click",function(){
value = "2";
name = "Option 2";
$("#options-box").append("<option value='"+value+"'>"+name+"</option>");
$.ajax({
url: "addtodb.php?value="+value+"&name="+name,
type: "GET",
success: function(data) {
alert(data);
}
});
});
});
PHP - While this is valid, make you sure sanitize your inputs into the query to avoid SQL Injection.
$value = $_GET["value"];
$name = $_GET["name"];
mysql_query("INSERT INTO tablename (name,value) VALUES ('$name','$value')");

Related

display data on selecting values from Dropdown without page refresh or button click using php mysql

I have a drop down on php form, I want to populate guest names in it, which has been done, now I want to load data from table on the basis of value from this drop down and without page refresh/ button submission. How do I do this? I want simple code that could achieve it in one page rather than doing it through multiple pages. The examples I have seen so far are too complicated and when I merge them in my code, they no longer work.
Here is the function which im using onchange of dropdown:
$("#guestname").change(function()
{
var id = $(this).find(":selected").val();
var dataString = 'action='+ id;
$.ajax
({
url: 'billing.php',
data: dataString,
cache: false,
success: function(r)
{
$("#display").html(r);
}
});
})
Here is my billing.php code, it loads values on the basis of first selected value, if I again select value from drop down,it doesn't show the updated record.
<?php
include('config.php');
$action = $_REQUEST['action'];
$stmt=$dbcon->prepare('SELECT discount FROM table_name WHERE name=:name
ORDER BY name');
$stmt->execute(array(':name'=>$action));
}
?>
<div class="row">
<?php
if($stmt->rowCount() > 0){
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
?>
You can do it without page refresh but you gonna need another php file, let's name it query.php to get you the result.
On your current page
<select>
<option value='bob'>Bob
<option value='jane'>Jane
</select>
<div id='output'></div>
<script>
$('select').change(function(){
let name = $(this).val();
$.ajax({
url: 'query.php',
method: 'POST',
data: {username: name},
success: function(response){
$('#output').html(response);
}
});
})
In query.php
$username = $_POST['username'];
//query database to get your result
echo json_encode($result);

filter Query data with var from html value input

if i have this input on html code
<input value="0001" name="call" id="call">
how i call that value in php script without submit? like event onBlur or anything ??
the php file have query something like this :
select * from table where field = (input html value)
you need to use Ajax for that.
<script>
$(document).ready(function()
{
var value = $("#call").val();
$.ajax({
url: "you file path where your php code is written to fetch value from database",
type:"POST",
data:{"call":value},
success:function(result){alert(result);}
})
});
</script>
and on php file.
<?php
write code for sql connection ;
$feild_value = $_POST["call"];
// you can use this $feild_value variable in query;
select * from table where field = $feild_value ;
//echo query result here
echo $query_result;
die;
?>
If you want to send this value to your PHP script when event Blur is triggered, then try this
<input value="0001" name="call" id="call">
<script type="text/javascript">
$('#call').on('blur',function(){
var value = $(this).val();
$.ajax({
url: "http://website.com/index.php",
type: "POST",
data: {"call": value},
success: function(data){
console.log(data);
}
});
});
</script>
To set input value to PHP session you will need to run ajax request anyway, see this question Set Session variable using javascript in PHP

get the value of <select> without submitting on the same page using php

Hope someone can help me..
i made my program more simpler so that everybody will understand..
i want my program to get the value of the without submitting, i know that this can only be done by javascript or jquery so I use the onChange, but what I want is when i select an option the value should be passed immediately on the same page but using php..
<select id="id_select" name="name" onChange="name_click()">
<option value="1">one</option>
<option value="2">two</option>
</select>
<script>
function name_click(){
value_select = document.getElementById("id_select").value;
}
</script>
and then i should pass the value_select into php in post method.. i dont know how i will do it.. please help me..
You cannot do this using PHP without submitting the page. PHP code executes on the server before the page is rendered in the browser. When a user then performs any action on the page (e.g. selects an item in a dropdown list), there is no PHP any more. The only way you can get this code into PHP is by submitting the page.
What you can do however is use javascript to get the value - and then fire off an AJAX request to a php script passing the selected value and then deal with the results, e.g.
$(document).ready(function() {
$('#my_select').on('change', do_something);
});
function do_something() {
var selected = $('#my_select').val();
$.ajax({
url: '/you/php/script.php',
type: 'POST',
dataType: 'json',
data: { value: selected },
success: function(data) {
$('#some_div').html(data);
}
});
}
With this code, whenever the selected option changes in the dropdown, a POST request will be fired off to your php script, passing the selected value to it. Then the returned HTML will be set into the div with ID some_div.
not sure ..but i guess ajax is what you need..
<script>
function name_click(){
value_select = $("#id_select").val();
$.post('path/to/your/page',{"value":value_select},function(data){
alert('done')
})
}
</script>
PHP
$value=$_POST['value']; //gives you the value_select data
Post with ajax as Alex G was telling you (+1) and then handle the post with PHP. You can define a callback in Javascript which will run when the page responds.
My suggestion go with jquery. Try with this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
<script>
$(document).ready(function(){
$("#id_select").change(function(){
var url = 'http:\\localhost\getdata.php'; //URL where you want to send data
var postData = {'value' : $(this).value};
$.ajax({
type: 'POST',
url: url,
data : postData,
dataType: 'json',
success: function(data) {
//
},
error: function(e) {
console.log(e.message);
}
});
})
})
</script>
In getdata.php
<?php
var $value = $_POST['value'];
// you can do your logic
?>

Jquery script not showing in firebug or firing

I'm trying to get a drop down box to alter a second drop down box through the use of a jquery/ajax script. Firebug is showing Jquery is working but my script isn't showing at all.
<script type="text/javascript">
function ajaxfunction(parent)
{
$.ajax({
url: '../functions/process.php?parent=' + parent;
success: function(data) {
$("#sub").html(data);
}
});
}
</script>
process.php is just a MySQL query (which works)
My initial drop down box is populated by a MySQL query
<select name="front-size" onchange="ajaxfunction(this.value)">
//Query
</select>
And then the second drop down box is just
<select name = "front-finish" id="sub">
</select>
How can I solve this?
calling inline function is not good at all... as web 2.0 standards suggest using unobtrusive JS rather than onevent attributes....check out why here..
other thigs..correct way to use ajax is by using type and data ajax option to send values in controller..
<script type="text/javascript">
$(function(){
$('select[name="front-size"').change(function()
{
$.ajax({
url: '../functions/process.php',
type:'get',
data:{'value' : $(this).val()},
dataType:"html", //<--- here this will take the response as html...
success: function(data) {
$("#sub").html(data);
}
});
});
});
</script>
and your proces.php should be..
<?php
//db query ...thn get the value u wanted..
//loop through it..
$optVal .= "<option value="someDbValue">some DDB values</option>";
// end loop
echo $optValue;exit;
updated
looks like you still have onchange="ajaxfunction(this.value)" this in your select remove that it is not needed and the ajaxfunction in javascript too...
<select name="front-size" >
//----^ here remove that
use jQuery.on() that will allow us to add events on dynamically loaded content.
$('select[name^="front-"]').on('change',function(e){
e.preventDefault();
var value = $(this).val();
ajaxfunction(value);
});
[name^="front-"] this will select all the SELECT box having name starts with front-.
In your process.php give like this
echo "<select name='front-finish' id='sub' onchange='ajaxfunction(this.value)'>";
like this you need to add the "onchange" function to the newly created select box through ajax
or you can remove onchange function and write like
$("select[name^='front-']").live('change',function(){
//Do your ajax call here
});

Form Validation when Input field is in HTML table and its type is "hidden"

I have a working code to change the colors of table cells when clicked on a colored button and when the mouse is dragged on table cell all the cells involved in the drag gets that color, here is the code http://jsfiddle.net/28SMv/76/ ,
Now i want to do form validation like when the first table cell gets a color i want to echo out value and send it to database, i am not able to set the table cell values to the selected color, please help!
Try it!
Show line and column id and value to store in your database.
Live demo
To save data use:
var Params = { identificador: identificador, color : color };
$.ajax({
url: 'pagetosave.php',
type: 'post',
data: Params,
success: function (data) {
alert('saved...');
}
});
Replace it on each command.
Will be triggered once for each ....
your php page will receive two parameters.... identificador e color.
You could try like this:
$('our_table td').click(function(){
$(this).css('background-color', selectedColor);
alert($(this).children("input").val());
$.ajax({
url: "add-product.php",
type: "post",
data: $(this).children("input").val().serialize(),
error: function(data){
alert("There was an error while inserting into the database. );
},
success: function(data) {
Display_Load();
$("#content").load("pagination_data.php?page=1", function() {
Hide_Load()
});
}
});
});
It doesn't seem to be letting me do the alert in Fiddle, but once you can get the variable, just do an AJAX call to update a database somewhere.
Let me know if you need more help.

Categories