I need some help with MySQL, jquery and PHP.
Here is my code :
HTML
<label class="checkbox"><input type="checkbox" name="code_site1" class="code_site1" checked="checked">Code 1</label>
<label class="checkbox"><input type="checkbox" name="code_site2" class="code_site2" checked="checked">Code 2</label>
<label class="checkbox"><input type="checkbox" name="code_site3" class="code_site3" checked="checked">Code 3</label>
<label class="checkbox"><input type="checkbox" name="code_site4" class="code_site4" checked="checked">Code 4</label>
Jquery
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
});
</script>
Everything here is working. But, I have an SQL query:
SELECT * from site;
I'd like to change it to :
SELECT * from site WHERE codeSite=$theOneThatIsChecked;
Actually, all I want is to establish a sql query depending on what is checked or note. For example, if code_site1 is checked, I'd like to have my SQL query like :
SELECT * from site WHERE codeSite=1;
That's pretty much I'm trying to do but I really don't know how to do it in PHP without submitting...
Can you help me ?
Thanks a lot !
EDIT:
First, thank you for your answsers. I tried the different solutions, but I still have an issue.
Actually, what I do :
- On my main page index.php I have an ajax script that points to "do.php" when I click on a submit button,
- On the "do.php" page I store a query depending on which checkboxes I have checked,
- Finally, thanks to :
success:function(data){
alert(data);
}
I can print the query that I made on "do.php". I'd like to know if I can store it in a php variable on my main page, in order to execute the query on my main page.
Thank you !
so if the request is sent correctly and no problem with that
you may change the name of checkboxes to name="code_site[]"
form example:
form should be like this if you want submit
<form method="POST">
<input type="checkbox" name="code_site[]" value="1">
<input type="checkbox" name="code_site[]" value="2">
<input type="checkbox" name="code_site[]" value="3">
<input type="checkbox" name="code_site[]" value="4">
<input type="submit">
</form>
with no submit:
$(document).ready(function(){
$("#flip").click(function(){
var data = { 'code_site[]' : []};
$("input:checked").each(function() {
data['code_site[]'].push($(this).val());
});
$.post("do.php", data);
});
});
then on the query side you can do
and because you are using checkbox so I assume that user can check multiple values, so you need to use "IN"
$codeSites = [];
if($_POST['code_site'])
$text = $_POST['code_site'];
$query = "select * from codeSite where codeSite in (" . implode($codeSites, ',') . ")";
echo $query; // use it
sure you need to do some input sanitization
or you can do this:
$codeSites = [];
if($_POST['code_site'])
$text = $_POST['code_site'];
$query = "select * from codeSite where codeSite in ('" . implode($codeSites, '\',\'') . "')";
echo $query; // use it
Use Ajax
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
if($('input[name="checkbox"]').is(':checked')){
var checkedValue =$("input[type='checkbox']").val();
var data ={id: checkedValue};
//make ajax request with the checked value
$.ajax({
url: url,
data:data
success: function(response) {
//process response
},
type: 'POST'
});
});
});
}
</script>
If I am understanding you correctly you will need to store the post value to a variable and the use that variable in your sql query
Change the input name so that they are all the same and then just add a value
Like this
<label class="checkbox"><input type="checkbox" value="1" name="code_site" class="code_site1" checked="checked">Code 1</label>
<label class="checkbox"><input type="checkbox" value="2" name="code_site" class="code_site2" checked="checked">Code 2</label>
And then something like:
if (isset($_POST['btn-checkbox'])){
$var = $_POST['codesite']
}
Then your query will be
SELECT * from site WHERE codeSite=$var;
Related
I've been building a mail form that is supposed to pass the information into a php document that handles sanitization and mailing, but I didn't want it to refresh so i decided to use JQuery and AJAX. I'm fairly new to JQuery and haven't used any AJAX before so I am a bit of a rookie when it comes to this...
Even though I have the .submit(function(e){e.preventDefault();}); it still submits the ordinary way and gives an error when it can't find film_mail in the PHP. Which means that it isn't stopping the submit and isn't passing the code to the PHP.
I've tested with alerts and the JQuery works in to the if() but after that some thing goes wrong.
Here is the code that causes the issue (some of the classes and ids are in swedish but that shouldn't cause an error...)
HTML
<div id="film" class="hidden" >
<form id="film_form" action="formular-send.php" method="post">
<input id="film_mail" type="text" name="mail" placeholder="Mail adress">
<input id="film_nr" type="number" name="nr" min="1">
<input id="film_antal" type="number" name="antal" min="1">
<input id="film_namn" type="text" name="namn" placeholder="Namn">
<input id="film_adress" type="text" name="adress" placeholder="Adress">
<input id="film_ort" type="text" name="ort" placeholder="Ort">
<input id="film_postnr" type="text" name="postnr" placeholder="Postnummer">
<textarea id="film_medelande" name="medelande" placeholder="Medelande"></textarea>
<button id="film_submit" type="submit" name="submit">Skicka</button>
<div class="error-mesage" ></div>
</form>
</div>
JQuery
$(document).ready(() => {
var emne = $('#emneid').val();
if (emne == 'film') {
$('#film_form').submit(function(e) {
e.preventDefault();
var mail = $('#film_mail').val();
var nr = $('#film_nr').val();
var antal = $('#film_antal').val();
var namn = $('#film_namn').val();
var adress = $('#film_adress').val();
var ort = $('#film_ort').val();
var postnr = $('#film_postnr').val();
var medelande = $('#film_medelande').val();
var submit = $('#film_submit').val();
$.post('formular-send.php', {
film_mail: mail,
film_nr: nr,
film_antal: antal,
film_namn: namn,
film_adress: adress,
film_ort: ort,
film_postnr: postnr,
film_medelande: medelande,
film_submit: submit,
emne: emne
});
// I heard that .load() had been removed in 3.0 so i tried to use $.post() because I thougt that might work but it sadly didn't...
// but I kept the .load() incase it'd be useful
/*$('#film_form').load('formular-send.php', {
film_mail: mail,
film_nr: nr,
film_antal: antal,
film_namn: namn,
film_adress: adress,
film_ort: ort,
film_postnr: postnr,
film_medelande: medelande,
film_submit: submit,
emne: emne
});*/
});
} else {
}
})
PHP
<?php
$filmmail = $_POST['film_mail'];
?>
If there is anything else that is needed i'd be happy to post it to.
I think $('#emneid').val() returns something different than 'film' and your listener is never attached.
Can you please double check the returned value of $('#emneid').val();
In addition of other comments, I think you need to add the correct name for you button or your PHP form will not work.
<?php
$filmmail = $_POST['film_mail']; //for the moment your need to put $_POST['mail'] because your button is named mail instead of film_mail
?>
Please also take care in production / later use, don't use directly $_POST or your code will be vulnerable from some SQL injection and so on. Take a look at htmlspecialchars function.
Edit :
I think you can just use HTML form and php to post your data, without posting it via JS/Jquery. If you want to have some data validation before sending it, you can just call an event before submit like described in this post : (Validate form before submit jquery)
I think you maybe have a problem with your selector to trigger the function, I don't know the submit function but maybe try with on('submit') or at least it will work with on('click').
$(document).on('click', '#film_submit button[type=submit]', function(e) {
var isValid = $(e.target).parents('form').isValid();
if(!isValid) {
e.preventDefault(); //prevent the default action
}
});
<button> does not have attribute type, but <input> has, try change <button> to <input>
UPD
Where is the tag with id of #emneid?
Try this. Please replace your HTML with my HTML code.
<div id="film" class="hidden" >
<form id="film_form" action="formular-send.php" method="post">
<input id="film_mail" type="text" name="film_mail" placeholder="Mail adress">
<input id="film_nr" type="number" name="film_nr" min="1">
<input id="film_antal" type="number" name="film_antal" min="1">
<input id="film_namn" type="text" name="film_namn" placeholder="Namn">
<input id="film_adress" type="text" name="film_adress" placeholder="Adress">
<input id="film_ort" type="text" name="ort" placeholder="Ort">
<input id="film_postnr" type="text" name="film_ort" placeholder="Postnummer">
<textarea id="film_medelande" name="film_medelande" placeholder="Medelande"></textarea>
<button id="film_submit" type="submit" name="submit">Skicka</button>
<div class="error-mesage" ></div>
</form>
</div>
I want to Insert SELECT ALL values or SELECTED values into different columns in MySQL. On choosing SELECT ALL, all the values are inserting correctly in sql but on selecting some checkboxes data is not inserting in SQL data.
Jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#select_all").change(function(){
var status = this.checked;
$('.checkbox').each(function(){
this.checked = status;
});
});
$('.checkbox').change(function(){
if(this.checked == false){
$("#select_all")[0].checked = false;
}
if ($('.checkbox:checked').length == $('.checkbox').length ){
$("#select_all")[0].checked = true;
}
});
});
</script>
PHP
<?php
$addbook=$_POST['addbook'];
$memdet=$_POST['memdet'];
$vbookd=$_POST['vbookd'];
$modify=$_POST['modify'];
$result=mysqli_query($db,"insert into apanel(addbook,memdet,vbookd,modify)values('$addbook','$memdet','$vbookd','$modify')");
?>
HTML
<input type="checkbox" id="select_all"/> Selecct All<br>
<input class="checkbox" type="checkbox" value="1" name="addbook" />Add Book<br>
<input class="checkbox" type="checkbox" value="1" name="memdet" />View Member Details<br>
<input class="checkbox" type="checkbox" value="1" name="vbookd" />View Book Details<br>
<input class="checkbox" type="checkbox" value="1" name="modify" />Edit/Delete<br>
I want to insert selective checkboxes also in MYSQL database. Help required
Before inserting into mysql check if the value is exist in $_POST['addbook'] do this for all the checkboxes. You can also use array of checkbox.
<?php
// Do this for rest of the values also.
if (isset($_POST['addbook'])){
$addbook=$_POST['addbook'];
}else{
$addbook = "default value"
}
?>
I'm using PDO, foreach and echo to generate some form inputs with data from a database, the output for this example will look slimier to this:
<input type="checkbox" value="1" checked>Google
<input type="checkbox" value="2">Amazon
<input type="checkbox" value="3" checked>Microsoft
This is being used in a form which is posted to the same page.
I want to grab this data and store it in a database using a PHP variable so when the checkbox is checked the value is assigned to it like this:
// output
$data = '1,3';
please note, the checkbox is checked by the users and the data used here is just an example, i want the form to be able to collect the right data by user input.
Give name to checkbox as an array, so when you submit form you will get an array of checkbox values in the array which checkboxes are checked then you can implode that array with , comma separated.
<input type="checkbox" name="checkboxname[]" value="1" checked>Google
<input type="checkbox" name="checkboxname[]" value="2">Amazon
<input type="checkbox" name="checkboxname[]" value="3" checked>Microsoft
After submitting form you have to get values like below code.
$data = implode(",", $_POST['checkboxname']);
echo $data;
you can use jquery:
for example:
HTML:
<input type="checkbox" value="1">Google
<input type="checkbox" value="2">Amazon
<input type="checkbox" value="3">Microsoft
<button type="submit" id="btn">Submit</button>
JQUERY:
$(document).ready(function(){
$('#btn').on('click',function(){
var cboxVal = [];
$('input[type="checkbox"]:checked').each(function(i){
cboxVal[i] = $(this).val();
});
$.ajax({
url : 'insert_data.php',
method : 'POST',
data : {cval:cboxVal},
dataType: 'text',
async : false,
success : function(){
alert('data inserted!');
}
});
});
PHP:
<?php
if(isset($_POST['cval'])){
$cval_raw = $_POST['cval'];
for($i =0; $i<count($cval_raw);$i++){
$cval = $cval_raw[$i];
$sql = "INSERT INTO db_name(table_name) VALUES('$cval')" or die('cannot insert');
$query = mysqli_query($connect,$sql);
}
}
?>
i'm trying to do a system to check if the member attended to the meeting.
I will check it using his ID, so, i a form to input his ID(it will be read by a bar code reader that the id will be the bar code, everything will be in a card), but if the member forget his card, should have another way to find his ID, so i'm using a modal open a form, so can find his name and pass his ID to the form.
On the modal, i'm using ajax to get dinamically his name (and his id on a checkbox), it works properly, but i cant take the checkbox value and pass it into the ID FORM.
Thats my code.
<form method="post" enctype="multipart/form-data" id="attendedForm" name="formPresenca">
<fieldset>
<label>
<span>ID</span>
<input type="text" name="id" id="alvo" />
</label>
<input type="hidden" name="acao" value="enviar" />
Seach Manually </fieldset>
</form>
JS:
$(function(){
$("a#popup").click(function(){
$.modal('<form method="post" enctype="multipart/form-data"><fieldset><label><span>Name</span><input type="text" name="Name" id="id" /></label></fieldset><div id="recebe_dados"></div></form>', {
overlayId: 'contact-overlay'
});
$("#id").on('keyup', function(){
var nome = $(this).val();
$.post("../scripts/get-name.php",
{name:name},
function(value){
$("#get_data").html(value);
});
//Dont shows me anything on the console.
$("#Checkbox").click(function(){
console.log($('#Checkbox:checked').val());
});
});
});
});
Get-value.php
$get = $_POST['nome'];
$mysql = mysql_query("SELECT id, name FROM members WHERE name LIKE '%$get%'");
while($res = mysql_fetch_array($mysql)){
echo '<input type="checkbox" name="id" value="'.$res['id'].'" id="Checkbox">'.$res['nome'];
}
I'm using Simple modal.
Since your while loop could possibly create duplicate IDs -- invalid HTML -- use the following instead:
$(document).on("click", ".Checkbox", function(){
console.log( this.value );
});
And:
echo '<input type="checkbox" name="id" value="'.$res['id'].'" class="Checkbox">'.$res['nome'];
And, this should be outside the keyup callback but inside DOM ready.
hope everyone is enjoying their day coding so far :D. i'm relatively new to JQUERY and AJAX been trying to find my way around, i'm getting there though. I have one minor problem however. I have HTML content that was generated from a MYSQL database using PHP (so the values for the checkboxes vary); it's a simple internal messaging program that i am working on for my website. I have a single check box that i can click that will select all the other checkboxes on the page. However what i hope to achieve is when ever the user selects a specific amount of check boxes or even a few, then presses a picture it with then call on my php file which will be responsible for deleting the message which the user checked. This previous question helped alot: How to pass jQuery variables to PHP variable? but i have numerous check boxes
HTML/JS:
<body>
Check Box: <input type="checkbox" name="check" value="1">
Check Box: <input type="checkbox" name="check" value="4">
Check Box: <input type="checkbox" name="check" value="3">
Check Box: <input type="checkbox" name="check" value="4">
<img id = "delete" src="http://icons.iconarchive.com/icons/visualpharm/must-have/256/Delete-icon.png">
<script>
$("#delete").click(function () {
$.post('sql_delete.php', 'num=' + $(this).val(), function (response) {
alert(response);
});
});
</script>
</body>
PHP
<?php
require 'functions/init.php';
$messageid = "_$POST[num]";
$sql_statement = "DELETE FROM chj_messages WHERE message_ID = $messageid";
mysql_query($sql_statement);
?>
I suspect that i might need loops in both the JS and PHP not entirely sure though. All your beautiful suggestions are welcomed :D
$messageid = "_$POST[num]"; should be $messageid = $_POST['num'];
Your code will delete one by one checkbox, as the user clicks them. If you want to let users check as many as they want, and then click some button to delete them, you need to remove that click listener from the checkboxes and bind it to a submit button or the image you mentioned. You'll also need to change the way you make your ajax call - you'll have to serialize all the checked ids and send that. Also, the PHP code needs to unserialize that data and make a DELETE query for each received ID.
Also, probably the most important, read about SQL Injection before going live with any site that uses MySQL. And mysql_* functions are deprecated, like it says on php.net, so you better switch to mysqli_* or PDO.
jquery:
$('#your_form').submit(function() {
$.post('sql_delete.php', $("#your_form").serialize(), function (response) {
alert(response);
});
return false;
});
html:
<form id="your_form">
Check Box: <input type="checkbox" name="check[]" value="1">
Check Box: <input type="checkbox" name="check[]" value="6">
Check Box: <input type="checkbox" name="check[]" value="8">
Check Box: <input type="checkbox" name="check[]" value="4">
<input type="image" src="path/to/your/image">
</form>
php:
$messageid = $_POST['check'];
foreach($messageid as $id) {
$sql_statement = "DELETE FROM chj_messages WHERE message_ID = $id";
mysql_query($sql_statement);
}
the edited code above has been tested.
also, the php should probably be done without a loop
$messageid = $_POST['check']; // sql injection already discussed.
$in = implode(", ", $messageid);
$sql_statement = "DELETE FROM chj_messages WHERE message_ID IN ($in)";
mysql_query($sql_statement);