How can I save a DropDown into a Database with AJAX - javascript

I've looked really hard on this but I can't get my head around AJAX working with PHP.
This is what I have and when a user clicks on the dropdown I would like it to save into my database
<select>
<?php $taskStatus = "SELECT * FROM task_status WHERE used = 1 ORDER BY id ASC ";
$taskresults = $conn->query($taskStatus) or die(mysqli_error($conn));
while($taskStatusRow = mysqli_fetch_assoc($taskresults)) {
echo " <option value= ". $taskStatusRow['name'] ." >". $taskStatusRow['name'] ." </option>";
}
?>
</select>
And this is the query i'd like to run:
INSERT INTO snagging (taskstatus, updated_at)
WHERE ID = 1234
VALUES taskStatusRow['name'], $now);

I'll give you a overall flow of AJAX here. I tried to provide comments so as to show the control flow.
<select id="selectOption"> //******* Assign an ID
<?php $taskStatus = "SELECT * FROM task_status WHERE used = 1 ORDER BY id ASC ";
$taskresults = $conn->query($taskStatus) or die(mysqli_error($conn));
while($taskStatusRow = mysqli_fetch_assoc($taskresults)) {
echo " <option value= ". $taskStatusRow['name'] ." >". $taskStatusRow['name'] ." </option>";
}
?>
</select>
jQuery + AJAX
$(document).ready(function() {
$("#selectOption").change(function(){ //** on selecting an option based on ID you assigned
var optionVal = $("#selectOption option:selected").val(); //** get the selected option's value
$.ajax({
type: "POST", //**how data is send
url: "MYPROCESSPAGE.php", //** where to send the option data so that it can be saved in DB
data: {optionVal: optionVal }, //** send the selected option's value to above page
dataType: "json",
success: function(data){
//** what should do after value is saved to DB and returned from above URL page.
}
});
});
});
Inside your MYPROCESSPAGE.php, you can access the data passed via AJAX like:
<?php
$selectedOptionVal = $_POST['optionVal'];
//DB CONNECTION STEPS
.
.
.
// You are trying to "UPDATE" a table data based on some ID and not inserting. Included both operations
// If you are INSERTING A new table entry, use below code.
//INSERT INTO snagging (taskstatus, updated_at) VALUES ('$selectedOptionVal', 'Now()');
// If you are UPDATING an existing table entry, use below code.
//UPDATE snagging SET taskstatus = '$selectedOptionVal', updated_at = 'Now()' WHERE ID = 1234;
?>
Hope it's helpful.

Related

Delete Selected row of selected ID using PHP and Javascript

I am trying to delete a row of selected ID by passing a parameter into URL. let say, I have entryIDs 1 and 2, whenever I try to select and delete the content of entry 1, it successfully deletes the content of entryID 1 but the problem is when I choose to delete entryID 2 it still deletes entryID 1 instead of 2. I am thinking the content of a variable var row = '".$rows['Blog_ID']."'; doesn't change and only retains the value of entryID 1 even though I choose otherwise.
Here is what I tried so far..
<?php
include("../Connection.php");
$post_query="Select * from indexview order by Blog_ID Desc";
$postsql=mysqli_query($connect_db,$post_query) or die('Connection unsuccessful');
while($rows=mysqli_fetch_array($postsql,MYSQL_ASSOC)){
echo "<div id='posts'>";
echo" <select onchange = 'down(this.value)' id='downpng' name='downpng'>
<option value='void'></option>
<option value = 'edit'>Edit Blog</option>
<option value ='delete'>Delete</option>
</select>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​";
echo
"<script>
function down(temp) {
var row = ".$rows['Blog_ID'].";
var id = '".$_GET['id']."';
if(temp=='delete'){
var con = confirm('Are you sure?');
if(con){
window.location = 'google.php?entryID=' + row + '&id=' + id;
}else{
window.location = '../Blog/Blog.php?id=".$_GET['id']."';
}
}else{
window.location = '../Blog/edit.php';
}
}
</script>";
When I select <option value ='delete'>Delete</option> it is supposed to redirect me into deleteBlog.php page and delete the content of selected entryID.
deleteBlog.php code:
<?php
include("../Connection.php");
if(isset($_GET['entryID'])){
$user = $_GET['id'];
$entry = $_GET['entryID'];
mysqli_query($connect_db, "Delete from blog_tbl where Blog_ID=" .$entry);
header('Location: ../Blog/Blog.php?id='.$user);
}
?>
Any suggestions will be much appreciated. Thanks!
You need to do minimal php for this, especially when it comes to the javascript part. Just store the blog id (I am going to store it in the name of the select attribute) and extract via javascript. I am going to use jQuery to do the JS stuff.
<?php
# Include database
include("../Connection.php");
# Create a simple function that does not use id="downpng" (id values are
# supposed to be unique
function getOrderDropDown($con)
{
$query = "Select * from indexview order by Blog_ID Desc";
$postsql = mysqli_query($con,$query) or die('Connection unsuccessful');
$str = '';
while($rows=mysqli_fetch_array($postsql,MYSQL_ASSOC)){
$str .= "
<select name='downpng[".$rows['Blog_ID']."]' class='blog_select'>
<option value='void'></option>
<option value = 'edit'>Edit Blog</option>
<option value ='delete'>Delete</option>
</select>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​";
}
return $str;
}
# Write the selects to page
echo getOrderDropDown($connect_db);
?>
Javascript to extract the selection:
<script>
// I would only do php here, use a special chars, otherwise you will be easily hacked by user input
var id = <?php echo (!empty($_GET['id']))? '"'.htmlspecialchars($_GET['id'],ENT_QUOTES).'"' : 'false' ?>;
// On change of this class type
$('.blog_select').on('change',function(e) {
// Get the name (which contains the id)
var row = $(this).attr('name').replace(/[^0-9]/gi,'');
// This will be the action (delete, edit)
var action = $(this).val();
// On delete, assign the actions and send values
if(action == 'delete'){
var redirect;
var con = confirm('Are you sure?');
if(con){
redirect = 'google.php?entryID='+row+'&id='+id;
}else{
redirect = '../Blog/Blog.php?id='+id;
}
}else{
redirect = '../Blog/edit.php';
}
// Just do one redirect
window.location = redirect;
});
</script>

How can I have a PHP query select a certain table based on a drop down list selection?

I have a web program where the goal is plot data points for a certain Kiln that the user has selected. My problem is when a user wants to select a new Kiln, how can I update all the separate JSON pages to where the data is pulled from the new table they selected?
Here is my drop down list creater code.
<p class="navleft">
Kiln Number:<br>
<select name="kilns" id="kilns">
<?php
$sql = "SHOW TABLES FROM history";
$result = mysqli_query($con,$sql);
while($table = mysqli_fetch_array($result)) { // go through each row that was returned in $result
echo ("<option value='". $table[0] . "'>" . $table[0] . "</option>");
}
?>
</select>
</p>
And here is one of the php pages where I select all the data from a value in a table and turn it into a JSON file.
<?php
$con = mysqli_connect("localhost","KilnAdmin","KilnAdmin","history");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,"history") or die ("no database");
//Fetch Data
$query = "SELECT * FROM k1_history LIMIT 1000";
$result = mysqli_query($con,$query);
if ($result) {
$data = array();
while($row = mysqli_fetch_assoc($result)) {
//$data[] = $row;
$data[] = array(
"date" => $row[ 'Timestamp' ],
"value" => $row[ 'DryBulbFront' ]
);
}
echo json_encode($data);
}
else {
echo "Error";
}
?>
Where is says k1_history, how can I get that to be the selection from the user in the dropbox menu from the other page?
In this kind of scenario you have to strongly pay attention to avoid SQL injection. Use a whitelist approach as mentioned by Konstantinos Vytiniotis and check this out How can I prevent SQL injection in PHP?
If I understand correctly what you want, then what you need is Ajax.
You have to populate the select like you do and on each select, make an Ajax call to a .php where you will handle what the user has chosen. In your case this .php file is going to take the table name the user chose, run a query and return some results back to the html. For demonstration purposes, I'll explain with an example.
Let's say in your .html you have a select like this:
Select Value:
<select name="kilns" id="kilns">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
What defined in the value property of the option is what you are gonna pass to the .php file I mentioned. To do that, you use Ajax, so inside some script tags you have:
$('#kilns').on('change', function(e) {
var data = {'kilns': this.value};
$.ajax({
type: 'POST',
url: 'submit.php',
data: data,
dataType: 'json'
}).done(function(msg) {
alert(msg);
});
});
What this does is that every time a user selects something from the select, then this function is called, where the select's value (var data = {'kilns': this.value};) is being sent to a file named submit.php, via POST. The submit.php could look like this:
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$kilns_error = 0;
if (isset($_POST['kilns']) && !empty($_POST['kilns'])) {
$kilns = $_POST['kilns'];
} else {
$kilns = null;
$kilns_error = 1;
}
if ($kilns_error != 1) {
echo json_encode($kilns);
}
}
What happens here is after we check we have indeed a POST REQUEST, we check whether the value is undefined or empty. After this simple check, we proceed to echo json_encode($kilns); where we return the value that we initially sent to the .php script, which in fact is the value the user selected.
In your case, what you have to do it to actually do some things in the .php script and not just return the value that you called it with. Also, make sure to pass the value you take through a whitelist to ensure that the user selects an actual table and is not trying to create problems for your database, cause it would be really easy to just change the value of what he is going to select before actually selecting it. Have a look at the prepared statements of the mysqli and PDO.

How to auto fill a form with data from database based on drop menu selection

I'm working on a MySQL update form and struggle to make a drop down selectbox that will autofill the rest of the form with data from mysql. Basically its a table that consist of users and their credentials. When updating a second table with this form i want to be able to select the username from a drop menu and let that selection autofill the rest of the credentials before moving on to the rest of the form.
Here is some of the code for setting up the select and input:
<?php
//DB Connect
...
// Get array of users
$select_users = "SELECT * FROM users";
if (!mysql_query($select_users)) {
die('Error: ' . mysql_error());
} //all good so far
$select_users_result = mysql_query($select_users);
?>
<select id="selectbox" name="navn" onchange="populateData(this.value)">
<option>USER</option>
<?php
$klubb = array();
$klasse = array();
while ($row = mysql_fetch_array($select_users_result, MYSQL_ASSOC)) {
echo "<option value='" . $row['navn'] . "'>". $row['navn'] ."</option>";
//echoing these vars will output all rows for the column specified...
$klubb[] = $row['klubb'];
$klasse[] = $row['klasse'];
}
mysql_close();
?>
</select>
<tr>
<td>Klubb: </td>
<td><input id="klubb" type="text" name="klubb" class="cred_input" />
</td>
</tr>
<tr>
<td>Klasse: </td>
<td><input id="klasse" type="text" name="klasse" class="cred_input" /> </td>
</tr>
And then some javascript
<script>
function populateData()
{
//alert('in populateData');
y = document.getElementById("selectbox");
document.getElementById("klasse").value = [y.selectedIndex];
document.getElementById("klubb").value = [y.selectedIndex];
}
</script>
The result here is a number in the <td>klubb and <td>klasse based on my selection in the drop menu.
How can i connect the arrays with that index number in the javascript so that it will show the actual data from the array ?
I've been seeking an answers for a few days now but can't find anything that answers my question.
Thanks for any help!
Well you can use AJAX for that.
For a tutorial on how to use AJAX and PHP script with Mysql This can help you.
First you need to create a PHP script that will gather the data you need for filling up the forms.
Setup the AJAX to be triggered everytime you choose something in your Drop Down List and pass its value on the PHP script you created.
On your AJAX script configure it to call the PHP script you created for retrieving the data (a value will be thrown in this script based on your drop down list).
Once you receive a response from your AJAX call just use a simple Javascript to fill up the forms based on the data your received.
Another tip is to use JQuery since it is easier for you to setup your AJAX request.
Use AJAX here.
In the populateData() function, use ajax to send the request to retrieve the user credentials & through Javascript, populate your textboxes with the retrieved values.
You could echo the two php arrays as javascript objects, and then access those in your populate function (this is the quick solution). But a better way is to ajax in the actual data
<script>
var klasse = <?=json_encode($klasse)?>
var klubb = <?=json_encode($klubb)?>
</script>
Well you can use Ajax. Make this as your form.
<?php
//DB Connect
...
// Get array of users
$select_users = "SELECT * FROM users";
if (!mysql_query($select_users)) {
die('Error: ' . mysql_error());
} //all good so far
$select_users_result = mysql_query($select_users);
?>
<select id="selectbox" name="navn" onchange="populateData(this.value)">
<option>USER</option>
<?php
$klubb = array();
$klasse = array();
while ($row = mysql_fetch_array($select_users_result, MYSQL_ASSOC)) {
echo "<option value='" . $row['navn'] . "'>". $row['navn'] ."</option>";
//echoing these vars will output all rows for the column specified...
$klubb[] = $row['klubb'];
$klasse[] = $row['klasse'];
}
mysql_close();
?>
</select>
<div id="some_container">
</div>
Your AJAX request :-
<script type="text/javascript">
$('select').on('change', function() {
var selectedVal = this.value; // or $(this).val()
$(document).ready(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "file.php?selectedVal="+selectedVal,
dataType: "html", //expect html to be returned
success: function(response){
$("#some_container").html(response);
}
});
});
});
</script>
file.php
<?php
echo '
<tr>
<td>Klubb: </td>
<td><input id="klubb" type="text" name="klubb" class="cred_input" value="$phpValueHere"/>
</td>
</tr>
<tr>
<td>Klasse: </td>
<td><input id="klasse" type="text" name="klasse" class="cred_input" value="$phpValueHere> </td>
</tr>';
?>
In your file.php, get the value of selectedVal via $_GET['selectedVal'] and then extract data from table, after extracting echo the data in those input boxes.

How using ajax can update mysql database from dropdown menu

As the question suggest can you tell me how i can update mysql database using a dropdown menu with the help of ajax. I want to update my database with out reloading my whole webpage.When a user click edit button the selected option from the drop down list is updated. After searching a while i found some tutorials for this method and took ajax codes from there. But when i tried those in my database; it didn't worked out. Below is the sample code for my php script, parent file contains both ajax script and php code in a single php file called samefile.php. Below script only contains the problematic codes, some html and php codes are intentionally removed.
//THIS AJAX SCRIPT FETCHES VALUES FROM THE SELECTED DROPDOWN
<script>
function get_da(str){
$.ajax({
url: "samefile.php",
type: "POST",
async: true,
data: { dropdown1:$("#dropdown").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
}
);
</script>
///////////////////////////////FIRST BLOCK//////////////////
<?php
//THIS PHP SCRIPT GENERATES DROP DOWN VALUES FROM DATABASE
echo "<select name='dropdown' onChange='get_da(this.value)'>";
while ($row = mysql_fetch_array($result))
{
if($row['id']==$row['user'])
{
echo "<option value='" . $row['id'] . "' selected>" . $row['name'] . "</option>";
}
else{
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
}
echo "</select>";
/////////////////////////////SECOND BLOCK//////////////////////////////
//THIS PHP SCRIPT VALIDATES THE SELECTED DROPOWN VALUE AND PASS THOSE VALES FOR FURTHER PROCESSING.
if(isset($_REQUEST['dropdown1']))
{
$name=get_the_selected_dropdown_name; //i dont know how to fetch name from dropdown menu
$sql = "UPDATE table SET name = '$name' WHERE id =10";
mysql_real_escape_string($sql);
$result = mysql_query($sql) or die (mysql_error());
if ($result==1) {
echo "Success";
}
else { echo "Failed";}
}
//////////////////////////////THIRD BLOCK////////////////////////////////////
?>
I believe this is how my above script works. when a user select a particular option from the drop down menu this function onChange='get_da(this.value)' sends the value (both id and name) to ajax query. in ajax query the drop down values are collected (both id and name) and renames as dropdown1 (data: { dropdown1:$("#dropdown").val()}) and pass it to php script inside the same file. Php script confirms the request from ajax using this if(isset($_REQUEST['dropdown1'])) and the script inside will be executed.
Please forgive me if i made a mess of my code. I suck at java script and ajax so am not sure whether my coding is right for those scripts. if possible can you suggest any other scripts for updating mysql database using ajax drop down list.
EDITED
ID DROPDOWN VALUE
1 ROY
2 TOM
3 CHASE
4 THOMAS
5 GEORGE
6 MICHAEL
have tried by printing the value you are sending in ajax request. You are passing this.value to your function get_da(str). But I think you are using it anywhere , In ajax post you are sending the value like
data: {dropdown1:$('#dropdown').val()}
But this will not post your selected vaule from dropdown, Try like this:
<script>
function get_da(this){
var id = $("#dropdown option:selected").val();
var selectedName = $("#dropdown option:selected").text();
$.ajax({
url: "samefile.php",
type: "POST",
async: true,
data: { dropdown1:id, name:selectedName}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
//drawVisualization();
},
});
}
</script>
Hope this will work.
Your dropdown script should be like this:
<?php
echo "<select name="dropdown" onchange="get_da()" id="dropdown">";
while ($row = mysql_fetch_array($result))
{
if($row['id']==$row['user'])
{
echo "<option value='" . $row['id'] . "' selected>" . $row['name'] . "</option>";
}
else{
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
}
echo "</select>";
This will send your selected value from drop down to your samefile.php.And also you are not doing good with your php script it should be like:
if(isset($_REQUEST['dropdown1']))
{
$id=$_REQUEST['dropdown1'];
$name=$_REQUEST['name'];
$sql = "UPDATE table SET name = '$name' WHERE id ='$id'";
mysql_real_escape_string($sql);
$result = mysql_query($sql) or die (mysql_error());
if ($result==1) {
echo "Success";
}
else { echo "Failed";}
}
?>

Dropdown based on previous selection is not populating at all

I am trying to fill in a dropdown list from a mysql table based on the selection on a previous dropdown.
I have looked at many questions asking how to do this and came up wit the follwing, however nothing is happening to my second dropdown when I select something from the first.
I have newStock.php with the following script in the head.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
<script type="text/javascript">
$(function(){
$('#field').change(function(){ //on change event
var fieldVal = $('#field').val(); //<----- get the value from the parent select
$.ajax({
url : 'process.php', //the url you are sending datas to which will again send the result
type : 'GET', //type of request, GET or POST
data : { fieldValue: fieldVal}, //Data you are sending
success : function(data){$('#field2').html(data)}, // On success, it will populate the 2nd select
error : function(){alert('an error has occured')} //error message
})
})
})
</script>
With the two drop downs created in the body:
<?php
connect('final');//connect to DB
$sql = mysql_query("SELECT * FROM stockcata");
while ($row = mysql_fetch_array($sql)){
echo '<option value='.$row['id'].'>' .$row['Catagory']. '</option>';
}
?>
</Select> </label>
<input type="text" name="addCatagory" />
<label><span>Section</span>
<Select name="field2" id="field2">
</Select> </label>
And the following process.php used to query my database and provide the options to fill in the second drop down
<?php
require("header.php");
connect('final');
$temp = $_GET['fieldValue'];
$result = mysql_query("SELECT * FROM stocksection WHERE cataID = '$temp'");
while ($row = mysql_fetch_array($result)){
echo '<option value='.$row['id'].'>' .$row['section']. '</option>';
}
?>
Nothing happens in the second dropdown, I have no idea why.
Edit.........
I tried to debug it further. My database is set up with 2 tables;
Section: ID, title, Catagory_ID
and Catagory: ID, Title
When it queries the section table it is only returning data with a Catagory_ID of 0, no matter what option I chose from the drop down
The data in the success of your ajax call is not the string you think it is. You probably want something like this:
success : function(data){$('#field2').html(data.d)}, // On success,
Try a console.log(data.d); if that doesn't work to see what you are returning.

Categories

Resources