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";}
}
?>
Related
I have a questions for which I need some help.
I have a page which, after it is finished loading, executes an AJAX, creates a table in PHP containing 2 buttons: 1 change password, the other is delete. Once the table is complete it is injected into a div in the main file. That works great so far. Now after that table is loaded, I want to be able to call another AJAX function linked in the JS file in the main page. So I have 3 components:
1. <div id="DbInfo"></div>
That is where I add the information from the users.
my php which executes the code and gets the information from my database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT LoginName FROM table";
$res = mysqli_query($conn, $sql);
if (mysqli_num_rows($res) > 0) {echo "<center>";
echo "<table border='1'>";
echo "<tr>";
echo "<td>User</td>";
echo "<td colspan=2 align=center>Available Functions</td>";
echo "</tr>";
while($row = mysqli_fetch_assoc($res)) {
echo "<tr>";
echo "<td>" . $row['User'] . "</td>";
echo "<td><button type='button' class='smallbutton' id='removeUser' value='" . $row['LoginName'] . "'>Delete User</button></td>";
echo "<td><button type='button' class='smallbutton' id='CPW' value='" . $row['LoginName'] . "'>Change Password</button></td>";
echo "</tr>";
}
echo "</table>";
echo "</center>";
} else {
echo "";
}
mysqli_close($conn);
And lastly the AJAX which does the injection of the created table into the HTML:
$(document).ready(function(){
$.ajax({
method: "POST",
url: "UserData.php",
success: function(data){
//document.getElementById("DbInfo").innerHTML = data;
document.getElementById("DbInfo").html(data);
}
});
});
Again, these functions are working fine. What I want to do after the page is done, be able to click one of these injected buttons and execute another AJAX. Unfortunately the standard declaration that I use for AJAX does not work.
$(document).ready(function(){
$("#removeUser").click(function(){
The question: How can I make sure after the table is injected, that I can call an AJAX function which is linked as an external source (<script src="script.js"></script>) in the main document?
Thanks for your help.
try :
$('#DbInfo').on('click', 'button[id="removeUser"]', function(i,e){
console.log('remove :' + $(this).val());
});
I am trying to update a MySQL database with checkboxes and PHP. I have read a lot of code examples online and read many questions on here but I seem to be stuck at the last hurdle.
My code first queries MySQL to bring back a list of users and then a checkbox (which is either 0 or 1 in MySQL) next to each one, indicating whether or not the user is completed.
What I am wanting to do is when the checkbox is checked, for that to update the MySQL database and update the column with 1, or if it is unchecked, for it to change the column to 2.
Here is my code so far:
HTML Snippet (Checkboxes):
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Firstname'] . "</td>";
echo "<td>" . $row['Surname'] . "</td>";
echo "<td>" . $row['Department'] . "</td>";
echo "<td>" . $row['RequestedBy'] . "</td>";
echo "<td>" . $row['StartDate'] . "</td>";
echo "<td class='tbl-chk'> <input type='checkbox' name='WSCompleted' value='"; echo $row['ID'] . "'" ; if ($row['WSCompleted']=='1') { echo "checked='checked'";} echo "/></td>";
Here is my jQuery that successfully retrieves the values and IDs and then posts them:
$(document).ready(function(){
$('input[name=WSCompleted]').click(function(){
var wsCompleted = $(this).is(':checked') ? 1 : 0;
var wsCompletedID = $(this).attr('value');
$.ajax({
type: "POST",
url: "/usr-handler.php",
data: {id: wsCompletedID, wsCompleted: wsCompleted},
success: function(){
$('div.success').fadeIn();
}
});
return true;
});
});
And finally here is a snippet of my PHP:
$wsCompleted = $_POST['wsCompleted'];
$id = $_POST['wsCompletedID'];
$query = "UPDATE newusers SET WSCompleted = '$wsCompleted' WHERE id = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
I am setting the value of the checkbox to what is actually the row ID in MySQL, then I can use the checkbox value to select the correct row in MySQL, and update it.
The problem I am having is that currently, how the code is, I get the following response from FireBug:
Unidentified index: WSCompletedID
After looking online it was suggested to change:
$id = $_POST['wsCompletedID'];
To:
$id = (ISSET($_POST['wsCompletedID']));
But doing so clears the error message, but then doesn't actually update the value on MySQL.
If I manually set the $id to something, the update works, but obviously that isn't right as it would only ever update the ID I have chosen it to.
I am completely stumped as to what is causing the problem. I have tried finding out online but cannot get anywhere with it.
Any help is greatly appreciated.
Thank you
You are loading data here in your javascript AJAX code
data: {id: wsCompletedID, wsCompleted: wsCompleted},
This will create the following $_POST array
id => whatever was in wsCompletedID
wsCompleted => whatever was in wsCompleted
So your PHP code should be looking for $_POST['id'] and $_POST['wsCompleted'] as these are the names you have given in your data:...
$wsCompleted = $_POST['wsCompleted'];
$id = $_POST['id'];
$query = "UPDATE newusers SET WSCompleted = '$wsCompleted' WHERE id = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
HOWEVER: Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared statement and parameterized statements
I have a problem with my website. I have a list of products that i get from database. These products have Image and Name camps.
Now i want that, when i click to someone of this products, into my webpage appears a new box where there is the description of the product, the price etc..
This is the code for the products list
<?php
include 'php/dbmanager.php';
$result = DBManager::getInstance()->getProducts();
if($result->num_rows > 0){
$i = 0;
while($row = $result->fetch_assoc()){
echo "<div class=\"wrap effect8 open\" onclick>";
echo "<h1>".$row['product_name']."</h1>";
echo "<div class=\"left\">";
echo "<img src=".$row['product_image']." width=150 height=150 >";
echo "</div>";
echo "<div class=\"right\">";
echo $row['product_description'];
echo "<div class=\"prodSelection\">";
echo '<a href="catalogo.php?prodID=';
echo $row[product_id];
echo '"';
echo 'class="button">Acquista</a>';
echo '<label>';
echo '<select class="selectBoxCat">';
echo '<option selected> 1 </option>';
echo '<option>2</option>';
echo '<option>3</option>';
echo '</select>';
echo '</label>';
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?>
How can i get the ProductID ($row[product_id]) from a single product that i click and use it for a new query for select the database's rows of this single product (and use this query for make another php like that)?
I dont want to refresh the page.
Could i use the pushstate method (HTML5)?
If you want to get additional data when the user clicks, you will need to make an ajax request to update your DOM without refreshing the page.
On the PHP side, you'll want to create a script that returns a json-encoded value.
On the JS side, you'll want to create a click event listener. Inside the listener, you'll want to make an ajax request to your PHP script.
When your data is successfully returned from your ajax call, you'll want to manipulate your DOM to display your product's details.
Example of a click listener:
$("#button").on("click", function(){
// make your ajax request here
});
Example of an ajax call:
$.ajax({
method: "POST",
url: "scriptThatReturnsProductDetails.php",
data:
{
productID: $("#myProduct").attr('id')
}
})
.done(function( msg ) {
// Do some DOM manipulation
});
I am using Codigniter to redo a website. I have the following controller code:
public function get_topics()
{
$topic = $this->input->post('input_data');
$topics = $this->firstcoast_model->get_topics_like($topic);
foreach ($topics as $val) {
echo "<pre id = \"pre_" . $val['id'] . "\">";
echo $val['formula'];
echo "<br />";
// generate a unique javascript file.
$f = "file_" . $val['id'] . ".js";
if (!file_exists($f));
{
$file = fopen($f,"w");
$js = "\$(\"#button_" . $val['id'] . "\").click(function(){\$(\"#pre_" . $val['id'] . "\").hide();});";
fwrite($file,$js);
fclose($file);
}
echo "<script src=\"file_" . $val['id'] . ".js\"></script>";
echo "<button id=\"button_" . $val['id'] . "\">Hide</button>";
echo "</pre>";
}
}
The basic idea to make an AJAX call to the function to retrieve a list of formulas.
The purpose of the javascript is to be able to hide any of the formulas by
hiding the <pre> </pre> tag that surrounds them The js file (i.e. file_1.js) I generate looks like:
$("#button_1").click(function(){$("#pre_1").hide();});
and the button code is:
<button id="button_1">Hide</button>
The problem is that it doesn't work. The files get generated, but clicking on the "Hide"
button does nothing. The puzzling part is that the exact same code works on the original website where I just make an AJAX call to a PHP file that generates the same code.
Any ideas what could be going on here?
Edit:
On my old website I used:
$query = "SELECT * FROM topics WHERE term LIKE '%" . $term . "%'";
$result = mysql_query($query);
while ($val = mysql_fetch_array($result))
{
echo "<pre id = \"pre_" . $val['id'] . "\">";
etc.
etc.
}
and everything works fine. If I now put the results of the while loop into to an array and then do a foreach loop on that, the results are very intermittent. I'm wondering if the foreach loop is the problem.
i think you can return list buttons in json response
public function get_topics()
{
$topic = $this->input->post('input_data');
$topics = $this->firstcoast_model->get_topics_like($topic);
$response = array('buttons' => $topics);
header('Content-Type: application/json');
echo json_encode( $arr );
}
so client can parse which button element to be hide.
<script type="text/javascript">
$(document).ready(function(){
$('somEL').on('submit', function() { // This event fires when a somEl loaded
$.ajax({
url: 'url to getTopics() controller',
type : "POST",
data: 'input_data=' + $(this).val(), // change this based on your input name
dataType: 'json', // Choosing a JSON datatype
success: function(data)
{
for (var btn in data.buttons) {
$(btn).hide();
}
}
});
return false; // prevent page from refreshing
});
});
</script>
Ok so I have:
A PHP file that queries a database and displays the results of the query,
a HTML file that displays the results using AJAX and
another PHP file that I need to send the data from the first PHP file to.
How can I do this?
My first PHP file displays:
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shopresult .= "<div class='result'><a id='shoplink' href='#shop'><strong><div id='hiddenid'>" .
$row['id'] . "</div>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div></a>";
}
So the AJAX brings this in and displays it in the HTML. Is there a way of sending the ID field when the link is clicked so that it can be used in another PHP file to display the data for that specific ID.
$( "#result" ).click(function() {
$.ajax({
type: "POST",
url: "external-data/shop.php",
data: $("#hiddenid"),
success: function (data) {
$("#individualshop").load("external-data/shop.php");
}
});
So that the data from the #hiddendiv ($row ['ID']) will be sent to the new PHP file. This isn't working.
shop.php has the code:
//get shop ID
$shopid = $_POST['ID'];
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE ID='$shopid'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<div class='searchresult'><strong>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div>";
}
But I'm not sure how to retrieve the ID?
Basically I need to be able to click on each search result and have another PHP file bring in specific data associated with the ID of the search result. Any suggestions??
Thanks in advance!
I'm not 100% sure this is what you want but this is one way.
This is your first php file. I've added an onclick listener to it so when a user clicks a row it will fire a JavaScript passing the $row['id'] variable.
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shopresult .= "<div onclick='someFunction(" . $row['id'] . ")' class='result'><div id='shoplink' href='#shop'><strong><div id='hiddenid'>" .
$row['id'] . "</div>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div></div>";
}
Then add this script to the header of the page.
<script>
function someFunction(d){
var response = httpGet("http://yourdomain.com/newphpfile.php?page_id=" +d);
document.getElementById('someResultArea').innerHTML = response;
}
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "POST", theUrl, false );
xmlHttp.send();
return xmlHttp.responseText;
}
</script>
Then your new php file should do something like this.
newphpfile.php
<?php
session_start();
$page_id = strip_tags($_GET['page_id']);
$processResult = 'handle your result';
echo $processResult;
?>
I hope this helps you out.
Use this;
$( "#result" ).click(function() {
$.ajax({
type: "POST",
url: "external-data/shop.php",
data: "ID=" + $("#hiddenid"),
success: function (data) {
$("#individualshop").html(data);
}
});
});
Note: Do not forget to return html in shop.php
You can fetch the clicked element id by using either javascript or jquery, and put it in the GET parameters on the php link
the ajax target would be ajax.php?id=test
Then get the value of id via $_GET['id']