How to update database thruogh dropdown without page reload - javascript

Please look at this code first:
$(document).ready(function() {
$("#alternatecolor [type=button]").each(function() {
$(this).on('click', function() {
btnObj = $(this);
rowId = $(this).attr("rowId");
changeStatus = $(this).attr("changeStatus");
$.get("changeStatus.php?rowId="+rowId+"&changeStatus="+changeStatus,function(data,status){
if(changeStatus == 0){
str ="Unverify";
btnText = "Verify";
newStatus = 1;
}
else{
str ="Verify";
btnText = "Unverify";
newStatus = 0;
}
if(data == 'success'){
alert("Status updated successfully to "+str+".");
btnObj.val(btnText);
btnObj.attr("changeStatus",newStatus);
}
else{
alert("some error");
}
});
});
});
});
</script>
Here is my change status page:
$dbhost = 'xxxxxx';
$dbuser = 'xxxxxxx';
$dbpass = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('xxxxxxxx');
$sql ="update experiment set verification=".$_GET['changeStatus']." where row=".$_GET['rowId'];
$retval = mysql_query( $sql, $conn );
if(!($retval))
{
die('error');
}
else{
echo "success";
}
mysql_close($conn);
I was using a button in this code to query my database with values 0,1. If pressed once, database queried with 1, if pressed again, database queried with 0.
Now, I have to put a dropdown in place of button with 3 values to query database with: 0,1,2. If selected first value, database row to be updated with value 0 and so on.
How would I do that?

remove button and add select like this:
<select class="my-select">
<option value="0">update</option>
<option value="1">create</option>
<option value="2">delete</option>
</select>
you also need to add data-rowId attribute.
jquery:
$(document).ready(function() {
$(".my-select").change(function() {
btnObj = $(this);
rowId = $(this).attr("data-rowId");
changeStatus = $(this).val();
$.get("changeStatus.php?rowId="+rowId+"&changeStatus="+changeStatus,function(data,status){
if(data == 'success'){
alert("Status updated successfully to "+str+".");
}
else{
alert("some error");
}
});
});
});

update
create
delete
You can do using class name or ID. If it's id then do $("#id1").click(function () {... in below code.
Awlad has done using GET method, below is using POST method.
$(function () {
$(".my-select").click(function () {
var category = $(this).text();
//$('label').css('color', selText);
$.ajax({
url: "invite_db.php",
type: "POST",
data: {"category": category},
success: function(data) {
$(".articleContent").html(data);
//setInterval("messageDisable()", 5000);
}
});
});
});
I have used parameter name according to my code. Please you change it

Here is your HTML and Javascript code
<select onchange="getval(this);">
<option value="1">One</option>
<option value="2">Two</option>
</select>
<script type="text/javascript">
function getval(sel) {
$.ajax({
type: "POST",
url: url, // url is page where you want to process this post request
data: 'val=' + sel.value,
});
}
</script>
On PHP side
<?php
// Your database connection code
$val = $_POST['val'];
mysql_query("UPDATE 'tablename' SET 'column name' = $val 'Your WHere caluse'")
?>

Related

How to delete row using ajax php mysql

How to delete a record in php mysql using the AJAX.
here's the code:
delete_record.php
<?php
require_once "../include/connection.php";
if ($_REQUEST['rowid']) {
$sql = "DELETE FROM lesson1 WHERE id='".$_REQUEST['rowid']."'";
if (mysqli_query($conn, $sql) {
//echo "Success";
} else {
//echo "Error: $sql";
mysqli_error($conn);
}
}
myqli_close($conn);
?>
index.php
<script type="text/javascript">
var rowId = null;
$(document).ready(function() {
$(document).on('click', '#btnDel', function(e) {
e.preventDefault();
rowId = $(this).attr('data-id');
});
$('#accDelBtn').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'delete_record.php',
data: 'rowid=' + rowId,
success: function(data) {
alert('Records were deleted successfully');
$('#modalDelete').modal('hide');
}
});
})
});
</script>
what I'm trying to here is to delete a record.
when I'm clicking the delete. message is success but the data is not deleted.
You can try:
Print a message or rowid within:
if ($_REQUEST['rowid']) {}
Check the query in MySQL browser
Check the connection string

How can i call a php function on a dynamically created html element in .js file

This is my product.php file which include the following php function
<?php
function getOfferName($conn,$companyID){
$sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers`
WHERE `company_id`='$companyID'";
if ($result=mysqli_query($conn,$sql)) {
while ($row=mysqli_fetch_assoc($result)) {
?>
<option value="<?php echo $row['id'] ?>"><?php echo $row['offer_name'] ?></option>
<?php
}
}
}
?>
This product.php file include the custom-js.js file in which i am creating a html element dynamically (Select dropdown).
$('.offerCheckBox').on('change', function() {
var id=$(this).data('id');
if (!this.checked) {
var sure = confirm("Are you sure want to remove offer ?");
this.checked = !sure;
}else{
$(this).parent().parent().append('<select name="" id=""><?php getOfferName($conn,$companyID) ?></select>');
}
});
Here i call php function getOfferName but it is showing me output like this
enter image description here
<select name="" id=""><!--?php getOfferName($conn,$companyID) ?--></select>
You can do by below code
getdata.php
if($_POST['action'] == 1){
$companyID = $_POST['id'];
$sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers`
WHERE `company_id`='$companyID'";
if ($result=mysqli_query($conn,$sql)) {
$html = '';
while ($row=mysqli_fetch_assoc($result)) {
$html .= '<option value="'.$row['id'].'">'.$row['offer_name'].'</option>';
}
}
echo json_encode($html);
exit(0);
}
?>
Ajax Call to Get Data
$('.offerCheckBox').on('change', function() {
var id=$(this).data('id');
if (!this.checked) {
var sure = confirm("Are you sure want to remove offer ?");
this.checked = !sure;
}else{
$.ajax({
url: "getdata.php",
type: 'POST',
data: {id:id,action:1},
dataType: "json",
contentType: false,
cache: false,
processData: false,
success: function(response) {
if (response) {
$(this).parent().parent().append('<select name="" id="">'+response+'</select>');
} else {
//Error
}
return true;
}
});
}
});
the JavaScript file is on the client side writing code in this file will not will not create a server call that runs the PHP file.
if you want to combine JavaScript with a server call you should use ajax.
JavaScript:
$('.offerCheckBox').on('change', function() {
var id=$(this).data('id');
if (!this.checked) {
var sure = confirm("Are you sure want to remove offer ?");
this.checked = !sure;
} else {
let fd = new FormData();
let companyID = $(this).val();
fd.append('companyID', companyID);
$.ajax
({
url: "getOffer.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
complete: function (results) {
let response = JSON.parse(results.responseText);
my_function.call(this, response);
}
});
}
});
// in this function you will put the append of the select box that php has created
function my_function(response) {
console.log("response", response);
}
PHP code (the file name is : getOffer.php)
<?php
$companyID = $_REQUEST['companyID'];
$options = array[];
$sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers`
WHERE `company_id`='$companyID'";
if ($result=mysqli_query($conn,$sql)) {
while ($row=mysqli_fetch_assoc($result)) {
$options[$row['id']] = $row['offer_name'];
}
}
$resBack = (json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
echo ($resBack);
?>
Now in the callback function my_function as we wrote above you have an array of key value pair from the PHP.
iterate on this array in JavaScript build your option select items and append them to the select box.

php dopdown filter is not working

This is product filter page. I want to filter data by drop down. by php and mysqli database. I fetch data from database and put in dropdown. But it is not filtering after selecting value. trying from long time. did all possible way. please help me out in this code thank you.
var colour,brand,size,achievements ;
$(function(){
$('.item_filter').click(function(){
$('.product-data').html('<div id="loaderpro" style="" ></div>');
colour = multiple_values('colour');
brand = multiple_values('brand');
size = multiple_values('size');
achievements = multiple_values('achievements');
$.ajax({
url:"ajax.php",
type:'post',
data:{colour:colour,brand:brand,size:size,achievements:achievements,sprice:$(".price1" ).val(),eprice:$( ".price2" ).val()},
success:function(result){
$('.product-data').html(result);
}
});
});
});
function multiple_values(inputclass){
var val = new Array();
$("."+inputclass+":checked").each(function() {
val.push($(this).val());
});
return val;
}
<div class="list-group">
<select>
<option class="item_filter" value="showAll" selected="selected">Show All Products</option>
<?php
$query = "select your_achievements from info_user where user_status = '1'";
$rs = mysqli_query($con,$query) or die("Error : ".mysqli_error());
while($achievementsdata = mysqli_fetch_assoc($rs))
{
?>
<option selected="selected" class="item_filter" value="<?php echo $achievementsdata['your_achievements']; ?>"><?php echo $achievementsdata['your_achievements']; ?></option>
<?php
}
?>
</select>
</div>
try to use onchange event like this
$('select').on('change', function() {
alert( this.value );
})
and your data variable should be like this
data:{'colour':colour,'brand':brand,'size':size,'achievements':achievements,'sprice':$(".price1" ).val(),'eprice':$( ".price2" ).val()},
make sure your all variable's value are exist.
your ajax code should be like this
$(function(){
$('select').on('change', function() {
$('.product-data').html('<div id="loaderpro" style="" ></div>');
colour = multiple_values('colour');
brand = multiple_values('brand');
size = multiple_values('size');
achievements = multiple_values('achievements');
$.ajax({
url:"ajax.php",
type:'post',
data:{'colour':colour,'brand':brand,'size':size,'achievements':achievements,'sprice':$(".price1" ).val(),'eprice':$( ".price2" ).val()},
success:function(result){
$('.product-data').html(result);
}
});
});
});

Ajax not submitting $_Post

I have this section of code that is suppose to get the Values of the input fields and then add them to the database. The collection of the values works correctly and the insert into the database works correctly, I am having issue with the data posting. I have narrowed it down to the data: and $__POST area and im not sure what I have done wrong.
JS Script
$("#save_groups").click( function() {
var ids = [];
$.each($('input'), function() {
var id = $(this).attr('value');
//Put ID in array.
ids.push(id);
console.log('IDs'+ids);
});
$.ajax({
type: "POST",
url: "inc/insert.php",
data: {grouparray: ids },
success: function() {
$("#saved").fadeOut('slow');
console.log('Success on ' + ids);
}
});
});
PHP Section
<?php
include ('connect.php');
$grouparray = $_POST['grouparray'];
$user_ID = '9';
$sql = "INSERT INTO wp_fb_manager (user_id, group_id) VALUES ($user_ID, $grouparray)";
$result=mysql_query($sql);
if ($result === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error();
}
?>
You cannot send an array trough an ajax call.
First, use something like:
var idString = JSON.stringify(ids);
And use it: data: {grouparray: idString },
On the PHP side:
$array = json_decode($_POST['grouparray']);
print_r($array);

Set interval with AJAX

The purpose is to display a DIV when you click on a button and then display text inside that DIV that comes from my database. Thing is that data in databse changes, so text inside that div also. I would need a setInterval... with AJAX
I'm new in javascript and don't know the good way to go...
HTML:
<div onClick="showDiv();"> click </div>
<div style="display: none;" id="div">
Info from database:
<span style="display: hidden;" id="data1"> DATA 1 </span>
<span style="display: hidden;" id="data2"> DATA 2 </span>
</div>
javascript:
function showDiv()
{
document.querySelector("#div").style.display = "block";
setInterval(function () {getData()}, 1000);
}
function getData()
{
$.post(
'process.php',
{
},
function(data){
if(data == '1'){
document.querySelector("#data1").style.display = "inline";
}
else if(data == '2'){
document.querySelector("#data2").style.display = "inline";
}
},
'text'
);
return false;
}
//don't know how to just take data from database without sending by POST or GET.
php:
<?php
SELECT x FROM database
if(x == 1)
{echo '1';}
else if(x == 2)
{echo '2';}
?>
Get data using AJAX : Learn here. Your code to setInterval() is correct or you can do this : setInterval(getData,1000);
Display data in spans :
document.getElementById("data1").innerHTML = "your content from database";
document.getElementById("data2").innerHTML = "your content from database";
You're not giving a lot of info so I will give you a basic example of getting data from a mySQL database with jQuery, Ajax and PHP.
First you need to include jQuery to the head of your document
<script src="http://code.jquery.com/jquery-latest.js"></script>
And then use Ajax
function showDiv(){
document.getElementById("div").style.display = "";
setInterval(function (){ getData('something'); }, 1000);
}
jQuery.noConflict();
jQuery(document).ready(function($){
getData = function(variable){
var postVar = variable;
var postVar2 = "exemple";
$.ajax({
type: "POST",
url: "php/file.php",
data: 'variable=' + postVar + "&" +
'variable2=' + postVar2,
success: function(data){
data = $.trim(data);
var dataSplit = data.split("++==09s27d8fd350--b7d32n0-97bn235==++");
if(dataSplit[0] == "1"){
document.getElementById("data1").innerHTML = dataSplit[1];
}
if(dataSplit[0] == "2"){
document.getElementById("data2").innerHTML = dataSplit[1];
}
}
});
}
});
Finally, you need to create an external php file (in this example "file.php" in the folder "php") to get the data from your database with mysqli
<?php
// to prevent error, I check if the post variable is set and
// if it's not only full of spaces
if(isset($_POST['variable']) && preg_replace("/\s+/", "", $_POST['variable']) != ""){
$con = mysqli_connect("hostname", "username", "password", "database_name");
$query = mysqli_query($con, "SELECT * FROM `table_name` WHERE `column_name` = '".$_POST['variable']."'");
$results = array(); $row = 0;
while($info = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$results[$row] = array();
$results[$row]['column_name1'] = $info['column_name1'];
$results[$row]['column_name2'] = $info['column_name2'];
$row++;
}
foreach($results as $result => $data){
echo "1" . "++==09s27d8fd350--b7d32n0-97bn235==++" .
'<div>'.$data['column_name1'].'</div>'.
'<div>'.$data['column_name2'].'</div>';
}
}
?>
Hope it helps!

Categories

Resources