Add to mysql with checkbox and AJAX - php

I have some data which will be displayed like this;
foreach ($holidays as $holiday)
{
$resultTable .= "<p>{$holiday->title}" . "<br/>" .
"{$holiday->pubDate}" . "<br>" .
"{$holiday->description}" . "<input type=\"checkbox\" name=\"saveCB\" value=\"3\"/>" . "<br /></p>";
}
Is there an easy way by which when the checkbox is clicked and the data would be added to a mysql table using AJAX?
Regards Darren

Yes you need javascript to do this. It can be done pretty easily though, if you are satisfied with the form submitting, and the page refreshing each time a select box is changed (i.e. check/unchecked). If you can't accept this, you'll have to use ajax. That would be your optimal solution, and easy as ajax is, it is a nice to have in your toolbox for future projects.
That said, you can achieve this by giving your form an id attribute, and paste this javascript just beneath your form (and edit the form id var):
<script type="text/javascript">
var formId = "YOUR FORM ID HERE";
function submitForm(){document.getElementById(formId).submit()}
</script>
Then add the following attribute to each checkbox: onchange="submitForm()".
Again, it is highly recommended to use ajax for this sort of stuff, and if you look into jQuery ajax, you'll be impressed how easy this can be done.
EDIT: What you can do to actually implement this in your existing code (replace it):
<form action="php-file-to-process-form.php" id="your-form-id" method="post">
<?php if(count($holidays)>0): foreach($holidays as $holiday): ?>
<p>
<?php echo $holiday->title; ?>
<br>
<?php echo $holiday->description; ?>
<input type="checkbox" name="saveCB[<?php echo $holiday->id; ?>]" value="<?php echo $holiday->id; ?>">
</p>
<?php endforeach; endif; ?>
</form>
<script type="text/javascript">
var formId = "your-form-id";
function submitForm(){document.getElementById(formId).submit()}
</script>
Please note i rewrote parts of your code. But in this case, assuming your $holiday objects has an "id" property, php-file-to-process-form.php should receive a fairly comprehensible post request.

PHP doesn't have onClick events, you would have to use JavaScript for something like that.. Or make it so you post your values with PHP (using a form), then it would be possible.

To avoid page refreshing with a form submit you'll want to use AJAX. You didn't tag your question as using jquery, but I highly recommend it. Here is a jQuery example of what you want:
$('input[type=checkbox]').click(function() {
if ($(this).is(':checked')) {
var name = $(this).attr('name');
var value = $(this).val();
$.post('/path/to/your/php/code', {name: value}, function(data){
//Handle the result of your POST here with data containing whatever you echo back from PHP.
});
}
});
Note that this puts the same click handler on all your checkboxes which might be the wrong assumption. If you have other checkboxes on your form that you don't want to use with this logic you'd just need to change the jQuery selector from 'input[type=checkbox]' to something more restrictive such as inputs that have a certain css class.

Related

Passing the link's text as a value to the next page

I am trying to pass the link's text as a value to the next page so I can use it to search the database for the item and retrieve the information related to the value .I have tried using the POST method but regardless the information is not passed. This is the code I tried .
<form action="DetailedMenu.php" method = "POST" action = "<?php $_PHP_SELF ?>">
<?php
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
echo str_repeat(' ', 4); ?>
<a href="DetailedMenu.php" ><?php echo $array[$i]["Food_Name"];?></a>
<?php echo " " .str_repeat('. ', 25). "€".$array[$i]["Food_Price"]."<br>"; ?>
<input type="hidden" name="name" value="<?php echo $array[$i]["Food_Name"];?>">
<?php
}
}
?>
</form>
You don't need the form.
The easiest way to do what you're trying to do....
In addition to including the text in the content of the link, include it as a query string parameter.
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
...
<?php echo $array[$i]["Food_Name"];?>
...
}
}
I would actually recommend something more like this. I obviously don't know the names of your fields, so I've just taken a guess...
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
...
<?php echo $array[$i]["Food_Name"];?>
...
}
}
You'll be able to access "FoodID" as a parameter within your PHP, just as you would if it had been submitted from a form.
You may be looking for AJAX. AJAX lets you send the form data to a back end PHP file (that can then insert data into a DB, and/or get data from the DB) without refreshing the page.
In fact, when you are using AJAX you don't even need to use a <form> structure -- simple DIVs work just fine. Then you don't need to use event.preventDefault() to suppress the built-in form refresh.
Just build a structure inside a DIV (input fields, labels, etc) and when the user is ready to submit, they can click an ordinary button:
<button id="btnSubmit">Submit</button>
jQuery:
$('#btnSubmit').click(function(){
var fn = $('#firstname').val();
var ln = $('#lastname').val();
$.ajax({
type: 'post',
url: 'ajax_receiver.php',
data: 'fn=' +fn+ '&ln=' +ln,
success: function(d){
if (d.length) alert(d);
}
});
});
ajax_receiver.php:
<?php
$fn = $_POST['fn'];
$ln = $_POST['ln'];
//Do your stuff
Check out this post and especially its examples. Copy them onto your own system and see how they work. It's pretty simple.

php how to handle hyperlink like a POST instead of GET?

I will have a query that return a set of results, and these results will be in hyperlink form as shown below:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
Now user get to click on this hyperlink and get routed to abc.php?cif=$cif..
My question is, is it possible to only show abc.php to user, just like a POST method, and $cif remains available at abc.php?
As #Flosculus said above, the "best" solution to simulate a post request is doing something like proposed here: JavaScript post request like a form submit
However, despite it's surely a reliable solution, I'm wondering you just don't use sessions instead, something like:
From the page where you set the cif variable:
session_start();
$_SESSION['cif'] = $row['cif'];
In abc.php:
session_start();
if (isset($_SESSION['cif'])) {
// Do what you need
}
EDIT::
Another (possible) solution is setting an hidden input and silently submit a form when you click on an anchor, like this:
From your example, instead of:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
You do this:
When you print all the entries, please add this first (from PHP):
<?php
echo <<<HEADER
<form action="abc.php" method="post" id="submitAble">
<input type="hidden" name="cif" id="cif" value="{$row['cif']}">
<table>
HEADER;
// Get data from your query.. Here is an example:
while ($row = mysli_fetch_assoc($query)) {
echo <<<ENTRY
<tr>
<td>{$row['cif']}</td>
</tr>
ENTRY;
}
echo "</table> <!-- \table collapse --></form> <!-- \form collapse -->";
?>
Then, if you're using jQuery (thing that I'm recommending), simply add an event listener in javascript, like this:
$('.cifSetter').on('click', function(e) {
e.preventDefault();
$('#cif').val($(this).data('cif'));
$('#submitAble').submit();
});
If you don't have jQuery, use this instead:
var cifSetter = document.getElementsByClassName('cifSetter');
for (var i = 0; i < cifSetter.length; i++) {
cifSetter[i].addEventListener('click', function(e) {
e.preventDefault();
var cif = document.getElementById('cif');
cif.value = this.dataset.cif;
document.getElementById('submitAble').submit();
});
}
In both ways, whenever an anchor gets clicked, it will prevent its standard behavior (redirecting) and will instead set the value of an hidden field to the value of the CURRENT "cif" and submit the form with the desired value.
To retrieve the desired value from abc.php, just do this:
$cif = $_POST['cif'];
However, keep in mind that the hidden field is editable by the client (most persons won't be able to edit it, though), therefore you should also sanitize your data when you retrieve it.
Sessions could do it but I'd recommend to just use $_POST. I dont get why you wouldn't want to use POST.

get increasing variable from php to jquery

how to pass a variable to jquery with php ?
i have to call the jquery from html this is what is confusing me:
jquery:
$(document).ready(function() {
$('#pre-info').click(function() {
$('#hide').slideToggle("fast");
});
});
now i want a $i after #pre-info and after #hide.
im calling the jqueryScript like this :
thank you.
Okay, here is more code :
<?php
$i =0;
//Make some querys nd stuff
foreach ($all as $one) {
//Here the event 1 is createt but the pre info gets increased with each event listet
echo "<div class='EVENT'><div id='pre-info$i'>";
// get som other tables nd stuff
echo"</div><div id='hide$i' style='display:none;'>";
//now this part is hidden until i click on the pre-info
//hidden Stuff
$i++;
}
?>
<script type="text/javascript">
$(document).ready(function() {
$('.pre-info').click(function() {
var hiddenid=$(this).data('hiddenid');
$('#'+hiddenid).slideToggle();
});
});
</script>
it does still not work, did i miss anything?
for me it looks like pre-info in this javascript needs a reference ( $i) as well ?
maybe i just dont understand the jquery completly..
Ok so you have several hidden divs and for each one you also have a listener to toggle their visibility. The original list comes from php which in turn gets the data from a query.
You could use data attributes to link pre-infos to hidden elements:
$i =0;
foreach ($all as $one) {
echo "<div class='pre-info' data-hiddenid='hide$i'>click me</div>";
echo "<div id='hide$i' style='display:none;'> hidden stuff </div>";
$i++;
}
then you just need one listener on jQuery
jQuery(document).ready(function() {
jQuery('.pre-info').click(function() {
var hiddenid=jQuery(this).data('hiddenid');
jQuery('#'+hiddenid).slideToggle();
});
});
Hope it helps (edit, I wrapped the listener in the document ready event)
By the way, it seems to me you're reinventing the wheel. You could use jQuery UI's accordions or Bootstrap collapsibles with nice, crossbrowser transitions.
If the JS is in .php file, you can just use:
$(document).ready(function() {
$('#pre-info<?php echo $x; ?>').click(function() {
$('#hide<?php echo $x; ?>').slideToggle("fast");
});
});
Your question does not contain enough information to give you more detailed answer, I'm afraid.
you could embed the php variable you require into a hidden html attribute or a data attribute
Hidden Element HTML
<input type="hidden" id="someId" name="someName" value="<?php echo $someVariable?>"/>
Javascript
var someVar = $('#someId').val()
Data HTML
<div id="someId" data-some-var="<?php echo $someVariable?>"></div>
Javascript
var someVar = $("#someId").data("some-var")
Note that if you use data you must include the keyword "data" before whatever you decide to name the attribute

javascript checkbox not reacting when clicking, always have to press submit

For some reason I can't get to work a script I have been trying out for a few days.
I have some checkboxes that show different colors. When the user clicks on one color I want the script to reload one of the DIVs of my website.
Everything works fine with the <form> tags and an <input type="submit">, basically with a button. But it never works by just checking a checkbox, I always have to click on submit.
Any help with the code would be much appreciated!
Thanks!
javascript:
<script>
$('.colors').delegate('input:checkbox', 'change', function() {
if ($(this).attr("checked")) {
var id = $("#regularCheckbox").find(':checked').val();
$('#itemMain').load('index.php?color='+id);
}
}).find('input:checkbox').change();
</script>
form:
<?php
$colors = mysql_query("SELECT DISTINCT color_base1 FROM item_descr ORDER BY color_base1");
while ($colorBoxes = mysql_fetch_array($colors))
{
echo "<input type='checkbox' id='checkbox-1-1' class='regularCheckbox' name='color' value='".$colorBoxes[color_base1]."' /><font class='similarItemsText'> ".$colorBoxes[color_base1]."</font><br />";
}
?>
</div>
$("#regularCheckbox").find(':checked')
seems to be wrong based on your PHP echo. regularCheckbox is a class, not an id, so you will want to select $(".regularCheckbox:checked'). Btw, you should not output the same id repeatedly in a loop, ids need to be unique.
Also, you might just want to use jQuery's serialize() method on your form.

Focusing 'multiple' HTML input fields with jQuery or javascript

Hi again :)
I'm using jQuery script to show/hide some content:
<script type="text/javascript">
$('.toggleButton').click(function() {
var id = this.id.replace('toggleButton', '');
$('#content' + id).toggle();
});
</script>
Since I'm using PHP, I am iterating through few items and each of them has a button to show/hide its content. My content is actually a form with few input fields. In each item, first field of my form has a same name (let's say 'line1').
What I would like to do is when I click on an item and open its content, to take a focus on input field 'line1'. When I click on other item to take a focus on its 'line1' field, and so on...
Preferably with jQuery because I suppose it would be simpler, but javascript solution would be also great :)
Thanks for any help!
EDIT: I will attach a part of code which is that I need to show and hide... Maybe it will be of some help... I am using codeigniter, so not to be confused by some functions :)
echo "<div class=\"toggleButton\" id=\"toggleButton".$item['id']."\">CLICK TO OPEN</div>";
echo "<div class=\"content\" id=\"content".$item['id']."\" style=\"display:none;\">";
echo form_open('title/add'); // codeigniter's open form
for ($i = 1; $i <= $item['rows']; $i++) {
echo "<input type=\"text\" class=\"line\" id=\"line".($i)."\">".br();
}
echo form_submit('submit', 'submit'); // codeigniter's submit for button
echo "</form>";
echo "</div>";
Change your last line to:
$('#content' + id).toggle().find('input').first().focus()
did you try giving common class name and call function based on class name

Categories