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);
Related
im kinda trying to get into programming in general and was wondering how to uncheck / check with updating the array-
like as soon as someone checks a 2nd checkbox it should uncheck the first option and update the search (w the new data)- im a mere beginner and kinda lost rn so would appreciate any form of help
<form action="index.php" id="form1" name="form1" method="get">
<?php $i = 0; foreach ($row_page_nav_kategorie as $row_page_nav_kategorie) { ?>
<label class="checkbox-container">
<input <?php if (strpos($url,$row_page_nav_kategorie['typ']) == true) {echo 'checked="checked"';}?>
type="checkbox"
class="checkmark"
name="hotelKategorie[]"
id="ckb5"
value="<?php echo $row_page_nav_kategorie['typ']; ?>"
onclick="kategorie(<?php echo $i ?>);"
onchange="submit()"/>
<?php echo $row_page_nav_kategorie['typ']; $i++;?>
</label>
<?php } ?>
</form>
You should use radio buttons, but if you want to overwrite checkbox functionality below code will take care of it, I have added a common class on your inputs:
function checkboxClick(obj) {
var cbs = document.getElementsByClassName("checkkbox-option");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
Demo
First of all welcome to the community!
As for your question, there is multiple ways to handle this, one of wich is as followed:
In HTML there's an attribute called radio wich you can add to your input by using type='radio'. In a set of radio buttons, only one can be checked at any time. If you then want to immedietely submit your form, you can use something like onChange='this.form.submit()'. This will submit your form when the value is changed, such as pressing on a different radio button.
Something to keep note of is that the attribute onChange is case sensitive as far as i'm aware. You were heading in the right direction with onchange="submit(), but your code doesn't know what to submit. this.form.submit() will submit the form that the element is in.
Use Radio Buttons or use JavaScript on your page to dynamically uncheck other checkboxes when you click on one.
If you want to dynamically update the page content with the new search results you should also look into AJAX which basically means you will call PHP functions from JavaScript code and those will return JSON arrays that you can exploit to modify your page's DOM.
Try THIS
HTML:
<label><input type="checkbox" name="check1" class="checkbox" /> CheckBox1</label>
<label><input type="checkbox" name="check2" class="checkbox" /> CheckBox2</label>
<label><input type="checkbox" name="check3" class="checkbox" /> CheckBox3</label>
<label><input type="checkbox" name="check4" class="checkbox" /> CheckBox4</label>
jQuery:
$(".checkbox").change(function() {
$(".checkbox").prop('checked', false);
$(this).prop('checked', true);
});
if you want to uncheck the selected checkbox
$(".checkbox").change(function() {
$(".checkbox").not(this).prop('checked', false);
});
hope this helps, thanks !!!
I'm working on a PHP self-evaluation form that has 5 question categories with 10 questions each. In the beginning of the application, I have 5 checkboxes to represent these categories, and they are automatically checked. The idea is that whenever user unchecks a category, the questions of that category instantly disappear from the form, and when they check it again, they come back. Something that should be achievable with the help of jQuery and AJAX.
I made the checkboxes with CodeIgniter's form_helper:
for($i = 1; $i<=5; $i++) {
$this->formapp_model->printCatName($i);
$data = array('name'=>'category$i', 'id'=>'category$i', 'value'=>'$i', 'checked'=>TRUE);
echo form_checkbox($data);
}
And I have a function to printing all 10 questions of the category from database after their category id, which works fine when I just post them as they are:
$this->formapp_model->printCategory(1);
$this->formapp_model->printCategory(2);
$this->formapp_model->printCategory(3);
$this->formapp_model->printCategory(4);
$this->formapp_model->printCategory(5);
Using the help of this:
Passing whether a checkbox is checked, via jQuery, to PHP
I was able to gather that for the jQuery, I need something like
var category1 = $('#category1:checked').val();
in order to check if the checkbox has been selected. I also tried
var category1 = $('#category1:checked').post();
as it seemed logical to use post in order to PHP to recognize it.
And for the print selection something like
if (isset($_POST['category 1'])) { $this->formapp_model->printCategory(1); } else { echo "This category is not selected."; }
I tried this, but PHP doesn't recognize the message that jQuery is giving it, meaning the category's questions disappeared permanently, whether the checkbox was checked or not. I checked with echo var_export($_POST); and noticed that all the jQuery is printing out is: array ( ). The question mentioned above was very informative, but missed some info that I would have needed to get it to work. The asker was also using an array instead of separate variables so I don't know how to edit it properly.
I'm a complete newbie with jQuery and AJAX so I have a hard time grasping what I need in order to get jQuery and PHP communicate dynamically the way I described. I have run around stackoverflow to find similar cases, but none of them have quite had what I need. However, I deeply apologize in case this is a repeativive question. Thank you to anyone who helps!
PHP is server side, you need the questions to appear/disappear client side meaning you want to make that happen using jQuery itself (or regular js but since you're already loading jQuery it's quicker just to use the library itself).
To be honest I'm not really following how your view is working so I'll just give some basic code to give you the idea. You create the checkboxes and the questions giving each a unique ID. Then in the on click method for the check boxes you determine which questions to show.
HTML:
<div id="checkboxes">
<input type="checkbox" id="box1" class="check" checked="checked"/>
<input type="checkbox" id="box2" class="check" checked="checked" />
<input type="checkbox" id="box3" class="check" checked="checked" />
<input type="checkbox" id="box4" class="check" checked="checked" />
<input type="checkbox" id="box5" class="check" checked="checked" />
</div>
<div id="question1" class="question">
<p>Question 1</p>
</div>
<div id="question2" class="question">
<p>Question 2</p>
</div>
<div id="question3" class="question">
<p>Question 3</p>
</div>
<div id="question4" class="question">
<p>Question 4</p>
</div>
<div id="question5" class="question">
<p>Question 5</p>
</div>
jQuery:
$(".check").on("click",function(){
var id = $(this).attr("id");
var id2 = id.substr(id.length -1);
var question = "question"+id2;
if($(this).is(":checked"))
{
$("#"+question).css("display","block");
} else {
$("#"+question).css("display","none");
}
});
Demo: http://jsfiddle.net/calder12/taSPX/1
I'm doing this one using PHP.
I'm doing some basic quiz application and it has a backend. On my backend, I am setting up a quiz for students to answer. One of my interface is like this.
If the user checked the box, it means 1950 is the answer. How would I process that one in my database to determine that 1950 has been the answer of the question.
My Database is like this.
tbl_choices
Id,Choice,isAnswer
so ideally, it would be stored like this.
tbl_choices
ID CHOICE isAnswer
001 1900 0
002 1800 0
003 1950 1
004 1850 0
My question here is how would I code it in a sense when a user will check the checkbox and the textinput right beside it will have a value of isAnswer as 1.
Just an additional info: When a user will click that + button it will add a new textinput and if user will click - button it will delete a textinput, but I got that all covered.
The choices are dynamic, it will changed, that above that I've shown you is just an example.
P.S: Sorry for the title, I don't know what's the title of this kind of question :-)
Your help would be greatly appreciated and rewarded!
you can try html like this :
<input type="checkbox" value="1900" name="answer1[]">
<input type="text" value="1900" name="answer2[]" />
<input type="checkbox" value="1800" name="answer1[]">
<input type="text" value="1800" name="answer2[]" />
<input type="checkbox" value="1950" name="answer1[]">
<input type="text" value="1950" name="answer2[]" />
<input type="checkbox" value="1850" name="answer1[]">
<input type="text" value="1850" name="answer2[]" />
and then use php code:
foreach($_POST['answer2'] as $v){
if(in_array($v, $_POST['answer1'])) {
$s = 1;
}else
$s = 0;
$sql = "INSERT INTO table VALUES(null, $v, $s)";
}
also on click plus update values of both check box and text field
in general you can use checkboxes as an array when submiting information, just name the checkboxes as an array like
<input type="checkbox" value="1900" name="answer1[]">
<input type="checkbox" value="1800" name="answer1[]">
<input type="checkbox" value="1950" name="answer1[]">
<input type="checkbox" value="1850" name="answer1[]">
then on the server side you handle $_POST["answer1"] as an array and cycle through the possible answers, something like this
if (is_array($_POST["answer1"]))
{
foreach($_POST["answer1"] as $answer)
{
// insert into database here
}
}
important: this will only show what a user actualy selected, if an option is not clicked then it will not be part of the array
I think it would make sense to have more than one table, one for the questions with their options and then one for the answers with the fields id, choice_id. Otherwise it is going to make generating the questions a lot more difficult especially when a number of students answer the same question?
One more thing, you could add up in the answers of your question, add row and delete row based on + and - button.
The code for that:
<script type="text/javascript">
$(document).ready(function() {
$("#plus").click(function() {
$('#mytable2 tbody>tr:last').clone(true).
insertAfter('#mytable2 tbody>tr:last');
$('#mytable2 tbody>tr:last #st').val('');
$('#mytable2 tbody>tr:last #newst').val('');
$('#mytable2 tbody>tr:last #plus').val('+');
return false;
});
});
for more detail, you may refer following link:
Add Row on Button click
I'm asking this question in regards to my friend, so I do not have code samples to post here at the moment. Hopefully I'm clear enough that someone can help.
So he has a simple contact form except it has multiple checkboxes that the user can choose to send their requests to multiple recipients... like so...
x I would like to know about flight school
x I'm interested in becoming a teacher
x I would like someone to contact me about your degrees
Name
Email
Comments
And so based on which checkboxes are selected it should add that recipient to the email function so that they receive the users comments and interest.
The form is validated by jquery and uses the $.ajax function to POST the Name, Email and Comments fields over to a process.php... we are validating that at least one of the checkboxes is selected, however, we haven't been able to figure out how to pass its boolean value to the process.php and in-turn add the relevant email address to the mail() function.
I do realize this is semi-vague without posting our code, but I don't have access to it right now... and I have been searching google for about 30 minutes trying to find something to work with. Any help would be appreciated. Thanks.
you can simply check if the value you got is true or not:
basic idea :
if(checkbox-1-ischecked)
//send email to first recipent
end if
if(checkbox-2-ischecked)
//send email to 2nd recipent
end if
if(checkbox-3-ischecked)
//send email to 3rd recipent
end if
if(checkbox-4-ischecked)
//send email to 4th recipent
end if
Etc
This would seem to answer you check box query. (http://stackoverflow.com/questions/908708/how-to-pass-multiple-checkboxes-using-jquery-ajax-post)
In basic terms it would post an array back to the php script which you could then parse and depending what was ticked / the vars passed back you could then append more email addresses to the 'to' part of the mail function.
For a simplier implimentation you could just keep your three check boxs seperate not in an array and ajax post them back individually.
HTML
<input type='checkbox' name='flight' value='1' id='flight' />
<input type='checkbox' name='teacher' value='1' id='teacher' />
Then simply on the server via PHP
$to="";
if($_POST['teacher'] == 1) {$to = $to."joe#email.com,"};//append email
if($_POST['flight'] == 1) {$to = $to."bob#email.com,"};//append email
$to = rtrim($to, ","); //remove trailing comma
NOTE as with all web to mail scripts make sure you sanitize all vars to prevent spam abuse!
Name your elements as an array like this:
<input type="checkbox" name="mybox[]" value="foo#example.com">Foo</input>
<input type="checkbox" name="mybox[]" value="bar#example.com">Bar</input>
<input type="checkbox" name="mybox[]" value="hello#example.com">Hello</input>
<input type="checkbox" name="mybox[]" value="world#example.com">World</input>
After POSTing the form to your PHP, $_POST['mybox'] will be an array holding the values of the boxes checked.
In your PHP
if(isset($_POST['my_box']))
{
$subject = "sub";
$body = "body";
if (is_array($_POST['mybox']))
{
//multiple items were selected.
$to = implode(',',$_POST['my_box']);
mail($to,$subject,$body);
}
else //only one item was selected
{
echo $_POST['my_box'];
$to = $_POST['my_box'];
mail($to,$subject,$body);
}
}
else
//none were selected
You can simply assign the same name to all checkboxes, which actually results in a checkbox array.
<form name="someform" onsubmit="return validate(this)" action="process.php" method="post">
<input type="checkbox" name="names[]" value="Saji">Saji
<input type="checkbox" name="names[]" value="Muhaimin">Muhaimin
<input type="checkbox" name="names[]" value='Muhsin'>Muhsin
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
In process.php, you could have-
$name_val=$_POST['names'];
foreach($name_val as $values){
//Here $values will contain only the values of the checkboxes you had selected.
echo $values."<br />";
}
Does anyone know how I can get the value of an input box, without having a form? I want a submit button, but instead of submitting a form, I want it to change data in a MySQL database. Something like this maybe?
$img1="WHAT DO I PUT HERE?"
$idx=1
$sql="INSERT INTO games SET img1='$img1' WHERE id=$idx";
$result=mysql_query($sql);
Could I use that code on a "onclick" event? The input box's name and id is "img1".
If you don't want to submit a form, the only two other ways of accomplishing this are to click a link with the data as query parameters in the url, or use AJAX to send the data to the server in the background.
update:
Javascript, as usual. You'd put a link or button somewhere on the page with "Send to Server" or whatever for the text. The script would pull your information from the input fields, and then send it on to the server via an AJAX call. Something along these lines (note that I'm using Mootools for all this, as it makes life much easier than having to do the remote calls yourself):
function clickHandler() {
var img1 = $$("input[name='img1']")[0].value;
var r = new Request.JSON({
'url: 'http://yourserver.example.com/script.php',
'method': 'post',
'onComplete': function(success) { alert('AJAX call status: ' + (success ? 'succeeded': 'failed!'); },
'onFailure': function() { alert('Could not contact server'); },
'data': 'img1=' + img1
}).send();
}
and on the server you'd have something like:
<?php
$img1 = mysql_real_escape_string($_POST['img1']);
$idx=1;
$sql="INSERT INTO games SET img1='$img1' WHERE id=$idx";
$result=mysql_query($sql);
echo (($result !== FALSE) ? 1 : 0);
You'd probably want something more complicated than this, but this is the basis of an AJAX application. Some client-side javascript that makes requests, and a script on the server that handles them and returns any data/errors as needed.
Don't know if your completely against using a form or just might not know how to keep it hidden.
You can create a hidden form that submits the info with the click of a button.
<form name="hidden-form" action="youraction.php" method="post">
<input type="hidden" name="submitme" value="I get submitted">
<input type="hidden" name="submitmetoo" value="I get submitted">
<input type="hidden" name="submitmeaswell" value="I get submitted">
<input type="hidden" name="dontleavemeout" value="I get submitted">
<input name="submit" type="submit" value="SUBMIT" />
</form>
However anyone that looks at your html will be able to see this
I guess this is what you looking for.
this will only work if your html and php are on the same file...
<html>
<head>
</head>
<body>
<input type='text' id='user' placeholder='user'>
</body>
</html>
<?php
$val = "
<script>
document.write(document.querySelector('#user').value);
</script>
";
echo $val;
?>