Update checkbox and textarea value in mysql db using Jquery - php

I have textarea and three checkboxs in my mysql db by default textarea value as null and checkboxs values as zero(0).
when i enter some text in textarea i'm updating text value in my mysql db but i gotta stuck in checkbox things can some one suggest how to update checkbox checked value in mysql db
say for example if checkbox is checked/clicked i should be able to update my mysql db with value '1' if not the value will be '0'
https://jsfiddle.net/07wmpjqf/1/
db structure
ID TEXT ABC XYZ LMN
1 NULL 0 0 0
Thanks!
html
<div>
<textarea class="lb_text" rows="6" cols="50" placeholder="Add text here..."></textarea>
</div>
<div>
<label>
<input type='checkbox'>ABC
</label>
</div>
<div>
<label>
<input type='checkbox'>XYZ
</label>
</div>
<div>
<label>
<input type='checkbox'>LMN
</label>
</div>
<div>
<input type="submit" class="lb_save" value="submit">
</div>
php
if(isset($_POST['lb_text']))
{
$live_blog = mysqli_real_escape_string($_POST['lb_text']);
$sql = "update demo set text='".$live_blog."'";
$result = mysqli_query($con, $sql);
}
}
jquery
$(function(){
$(".lb_save").click(function(){
var lb_text = $('.lb_text').val();
if(lb_text == '')
{
alert("Enter Some Text...");
$('.lb_text').focus();
}
else
{
$.ajax({
type: "POST",
url: "index.php",
data:{
lb_text:lb_text,
},
success:function(response){
alert('successfully updated');
}
});
}
return false;
});
});

add id to your check box and capture th value in jquery.
<div>
<label>
<input type='checkbox' id="abc">ABC
</label>
</div>
<div>
<label>
<input type='checkbox' id="xyz">XYZ
</label>
</div>
<div>
<label>
<input type='checkbox' id="lmn">LMN
</label>
</div>
and change your ajax data like this,
data: {
lb_text: lb_text,
abc: $("#abc").is(':checked') ? 1 : 0,
xyz: $("#xyz").is(':checked') ? 1 : 0,
lmn: $("#lmn").is(':checked') ? 1 : 0,
},
and your query like this,
$live_blog = mysqli_real_escape_string($_POST['lb_text']);
$abc = $_POST['abc']
$xyz = $_POST['xyz']
$lmn = $_POST['lmn']
$sql = "update demo set text='".$live_blog."',ABC='".$abc."',XYZ='".$xyz."',LMN='".$lmn."'";

Related

select option to fetch other inputs

What Im trying to do is select item name where is ID and if item selected it automatically adds that item serial number to serial number input.
I think it should be used ajax maybe but I dont know how exactly.
Item Name:<br />
<div class="select-holder">
<i class="fa fa-caret-down"></i>
<?php
if($_items->count_items() == 0)
echo '<select name="item-name" disabled><option value="no">You need to add a item first</option></select>';
else{
echo '<select name="item-name" id="change-item">';
$items = $_items->get_items_dropdown();
while($item = $items->fetch_object()) {
echo "<option value=\"{$item->id}\">{$item->name} - {$item->serialnumber}</option>";
}
echo '</select>';
}
?>
</div>
Serial Number:<br />
<div class="ni-cont">
<input type="text" name="item-serialnumber" class="ni" disabled/>
</div>
I have also other inputs like description, price and etc.. to fetch these inputs with these values.
example: i need get data to my field from select option id (value)
<input type="text" name="item-serialnumber" value="<?php echo $_items->get_item_serialnumber($id); ?>" class="ni" disabled/>
<input type="text" name="item-serialnumber" value="<?php echo $_items->get_item_description($id); ?>" class="ni" disabled/>
That value is already shown inside your select-box you can simply use onchange event and then use $(this).find("option:selected").text().split('-')[1] this will give serial no then put it inside your input-box using $('[name=item-serialnumber]').val(somevalue) .Also ,you can send id via ajax to your server page and fetch result.
Demo Code :
$("#change-item").on("change", function() {
var value = $(this).find("option:selected").text().trim().split('-')[1]
$("[name='item-serialnumber']").val(value)
var id = $(this).val();
//use ajax :
$.ajax({
url: "somepgaename.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {
id: id //send id as well
},
success: function(data) {
console.log(data.yourfieldname);
//put inside your input fields values like :
// $("[name='item-serialnumber']").val(data.serialno)
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Item Name:<br />
<div class="select-holder">
<i class="fa fa-caret-down"></i>
<select name="item-name" id="change-item">
<option value="1">Abc-123</option>
<option value="2">Abc2-122</option>
<option value="3">Abc2-132</option>
</select>
</div>
Serial Number:<br />
<div class="ni-cont">
<input type="text" name="item-serialnumber" class="ni" disabled/>
</div>
Then , at your server end get the id pass via ajax using $_POST['id'] then fetch result using select query and send them back to ajax using echo json_encode($somearray); i.e:
$id = $_POST['id'];
$stmt = $pdo->prepare("SELECT * FROM tablename WHERE id=:id");
$stmt->execute(['id' => $id]);
//put fetch result inside array..send back to ajax
//echo json_encode($somevalue);

Ajax insert data into DB even if php statement return false

index.php
<form action="../inc/q_camp.php" method="POST" class="modalForm">
<h3>Campaign</h3><br>
<label>Name</label><br>
<input type="text" name="campName" required><br>
<label>Customer</label><br>
<select name="client" required>
<option value="1">Abc</option>
</select><br>
<label>Start in</label><br>
<input type="date" name="campStart" id="cStrt" required><br>
<label>End in</label><br>
<input type="date" name="campStop" required><br>
<input type="button" name="toStore" value="Next">
</form>
ajax.js
/*This function submit ".modalForm"*/
function submitForm1(){
return $.ajax({
type: "POST",
url: "../inc/q_camp.php",
data: $(".modalForm").serialize()
});
}
/*When the button with name "toStore" is pressed, call submitForm1*/
$("input[name=toStore]").click(function(){
submitForm1();
});
q_camp.php
/*Submit the campaign*/
if(!empty($_POST['campName']) || !empty($_POST['client']) ||
!empty($_POST['campStart']) || !empty($_POST['campStop']))
{
$sql = "INSERT INTO campaigns(cmp_name, customer_id, cmp_start, cmp_stop) VALUES (:cName,:cId,:cStr,:cStp)";
$query = $db->prepare($sql);
$query->bindParam('cName', $_POST['campName']);
$query->bindParam('cId', $_POST['client']);
$query->bindParam('cStr', $_POST['campStart']);
$query->bindParam('cStp', $_POST['campStop']);
$query->execute();
}else print_r("Failed");
The ajax function insert in the database even if the php if statement is not satisfied... If I let the "campName" input empty, I get "Failed" but the row is inserted in the database like "cmp_id 1, cmp_name NOTHING, customer_id 1, cmp_start 00-00-0000, cmp_stop 00-00-0000".
In the database, all field are setted to NOT NULL.
I want to understand how AJAX can access the SQL Query even if the if statement from PHP isn't satisfied, how a row can be inserted even if the column is setted to null and what I'm doing wrong.

Angular - storing checkbox values, and displaying them

Suppose that, you have 27 checkboxes, let's call them 'categories'. These checkboxes are in one section, you can select them multiple, and save.
The eseence is: if you save the form, the categories will be added to your profile, in MySQL.
My question is:
How I should name the models,
How I should store de values after sending the form
I had a solution for this, I saved the nth of the categories, then clicked them back at loading, but that's not the best.
Here is the code:
$scope.getSelectedCats = function() //Returning array: [1,4,5,6]
{
$return_array = [];
$i = 0;
if($scope.whoareu.develop){ $return_array[$i] = 1; $i++;}
if($scope.whoareu.design){ $return_array[$i] = 2; $i++;}
if($scope.whoareu.produce){ $return_array[$i] = 3; $i++;}
if($scope.whoareu.repair){ $return_array[$i] = 4; $i++;}
[...]
return $return_array;
}
HTML
<p>
<input ng-model="whoareu.develop" type="checkbox" value=1 id="WAY8" name="whoareu" />
<label for="WAY8">Develop</label>
</p>
<p>
<input ng-model="whoareu.design" type="checkbox" value=2 id="WAY9" name="whoareu" />
<label for="WAY9">Design</label>
</p>
<p>
<input ng-model="whoareu.produce" type="checkbox" value=3 id="WAY10" name="whoareu" />
<label for="WAY10">Produce</label>
</p>
<p>
<input ng-model="whoareu.repair" type="checkbox" value=4 id="WAY11" name="whoareu" />
<label for="WAY11">Repair</label>
</p>
[...]
And last, a very ugly solution for loading checks:
<?php
//$dbData = Data row from mysql, in object, by Wordpress
echo "setTimeout(function(){";
foreach(explode(',', $dbData->interested_in) as $val)
{
//echo "$('input:checkbox[name=whatareu]').filter('[value=$val]').click();";
echo "$('input:checkbox[name=whatareu]').eq($val-1).click();";
}
echo "}, 1000);";
?>
I don't know if I understand your problem well, see my snippet. If you want, you could create some mapping function setDefaultState(basedOn) which set checked in model checkboxs.
If the problem is that data is lost after you leave the controller, you should use some singleton storage like Angular's factories, and storage the checked categories there.
angular.module('app', [])
.controller('FrameController', ['$injector',
function($injector) {
var vm = this;
vm.checkboxs = [{
id: 'WAY8',
label: 'Develop',
checked: true
}, {
id: 'WAY9',
label: 'Design'
}]
angular.extend(vm, {
save: save
})
function save() {
// API call
console.log('checked: ', vm.checkboxs.filter(function(c) {
return c.checked
}).map(function(c) {
return {
id: c.id
}
}));
}
}
]);
setTimeout(function() {
angular.bootstrap(document.getElementById('body'), ['app']);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="body">
<div ng-controller="FrameController as vm">
<ul>
<li ng-repeat="checkbox in vm.checkboxs">
<input ng-model="checkbox.checked" type="checkbox" id="{{checkbox.id}}" name="whoareu" />
<label for="{{checkbox.id}}">{{checkbox.label}}</label>
</li>
</ul>
<button ng-click="vm.save()">
Save
</button>
</div>
</div>

Radio option selected so post to this page

i have been trying to find my way around this issue, I have used
$(function(){
$('form').submit(function(event){
event.preventDefault();
window.location = $('input[type=radio]:checked').val();
});
});
but all that does is redirect me to the page, I want to have a radio button that is selected redirect me to a page and then submit the form data to the div on that page and that page only, heres the form
<form name = "quoted" method="get">
<input id = "poster" type="text" name="poster" required="required" placeholder = "Credited Individual."> <br>
<textarea class = "actual_quote" name = "actual_quote" required="required" placeholder = "Write the question here!"></textarea><br><br><br>
<div class = "checkboxes" required="required">
<h3 style = "margin-top:-20px;">Please select one catagory that the quote falls into.</h3>
<label for="x"><input type="radio" name="x" value="stupid.php" id = "x" checked="checked" /> <span>stupid</span></label><br>
<label for="x"><input type="radio" name="x" value="stupider.php" id = "x" /> <span>stupider</span> </label><br>
<label for="x"><input type="radio" name="x" value="stupidest.php" id = "x"/> <span>stupidest</span></label>
</div>
<input id = "submit1" type="submit"><br>
</form>
and heres the div where we $_GET the data from the form and post it in the div
<div class="top-submit"><?php echo '“' . (!empty($_GET['actual_quote']) ? $_GET['actual_quote'] : '') . '”'; $actual_quote = $_GET['actual_quote'];?>
</div>
<div class="poster"><?php echo "-" . (!empty($_GET['poster']) ? $_GET['poster'] :''); $poster = $_GET['poster'];?>
<div class = "like">
Like
<p id = "like" style = "color:green;">0</p>
</div>
<div class = "dislike">
Dislike
<p id = "dis" style = "color:red;">0</p>
</div>
</div>
<?php
"INSERT INTO submissions(top-submit, poster)
VALUES ($actual_quote, $poster)";
?>
</div>
</div>
I have been stuck on this issue for a day, and I can't get out, please help!
if it's TL; DR
I want to be able to have one radio option selected, and when the user presses submit I want them to be redirected to the page of the radio option and then i want the data to be posted there and no where else. Please help! Thanks in advance -Connor
You are redirecting but not including the posted data.
It sounds like you should create a hidden form that the users don't see, and when they submit the form you have now, dynamically fill in the needed inputs and then trigger that form, posting the data to the correct page.
See the second answer here: pass post data with window.location.href

jquery not sending button choice to php

I have a search function that will accept a search string and send it to a php file for parsing a database column. I'd also like users to choose which aspect of the website they'd like to search (comics, artwork, or both). Comic and Artwork or stored in two separate tables.
This is a function that will accept an input search string from the html below and send it to a php file.
<script type="text/javascript">
function search(searchString) {
//var site = $("#site").val();
$.get("./scripts/search.php", {_input : searchString},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
And this is javascript to accept a choice to search "comics", "artwork" or "all".
function searchChoice(choice) {
alert("Choice: " + choice);
$.get("./scripts/search.php", {_choice : choice}
);
}
</script>
HTML:
<!--Search filtering for comics, artwork, or both-->
<span class="search"><b>Search for: </b> </span>
<div class="btn-group" data-toggle="buttons-radio">
<span class="search">
<button type="button" class="btn" id="comics" onclick="searchChoice(this.id)">Comics</button>
<button type="button" class="btn" id="artwork" onclick="searchChoice(this.id)">Artwork</button>
<button type="button" class="btn" id="all" onclick="searchChoice(this.id)">All</button>
</span>
</div>
<br/>
<br/>
<!--Search functionality-->
<span class="search">
<input type="text" onkeyup="search(this.value)" name="input" value="" />
</span>
<br />
<span id="output"><span class="sidebarimages"> </span></span>
PHP excerpt:
$input = (isset($_GET['_input']) ? ($_GET['_input']) : 0);
$siteChoice = (isset($_GET['_choice']) ? ($_GET['_choice']) : "all");
You can see the javascript correctly alerting out "Choice: comics" when comics button is selected, but the php side, echo "</br>Choice: " . $siteChoice;, is echo'ing out "all", which is incorrect.
Any ideas would be greatly appreciated!
As mentioned #E_p, that is the problem ... another option is to create a variable and store the data there ... try this: you don't need change the html
var mySearchString = 0;
var myChoice = 'all';
function search(searchString) {
mySearchString = searchString;
GetSearch();
}
function searchChoice(choice) {
myChoice = choice;
GetSearch();
}
function GetSearch(){
$.get("./scripts/search.php", {_input : mySearchString, _choice : myChoice},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
You do not keep state for _choice.
When search is called it does not pass it to a server.
You need to change buttons to option and in search function pass both. to a server at the same time
Replace the buttons with radio buttons and use form.Serialize()
<form id="searchform">
<input type="radio" name="_choice" value="comics" />Comics<br/>
<input type="radio" name="_choice" value="artwork" />Artwork<br/>
<input type="radio" name="_choice" value="all" />All<br/>
<input type="text" onkeyup="search()" name="_input" value="" />
</form>
Javascript
function search() {
//var site = $("#site").val();
$.get("./scripts/search.php", $('#searchform').serialize(),
function(returned_data) {
$("#output").html(returned_data);
}
);
}
The .serialize() function converts form input to JSON so you don't have to type manually, No more parameter, and no two functions, just one to do them all

Categories