In the current example I have a form set up that takes a unique id. There is also a link that takes a unique id. The javascript function will fade in that form when the link is selected. Is it possible to call a javascript function based on the PHP variables used to id the form and the link? And so that it will fade in the correct when that corresponds to the unique id of the form?
PHP
while($row = mysql_fetch_array($query)){ $form_id = $row[id]; ?><a href="#"
id="askedClick"><?php echo $row[post_text].'<br>'?></a>
<form action="<?php $curent_file ?>"
method="POST" id="<?php echo $row[id] ?>">Do you know the anwer?
<input type="submit" value="Yes" name="<?php echo $form_id.'yes'?>"
/>
<input type="submit" value="No" name="<?php echo $form_id.'no'?>" />
</form>
<?php } ?>
JAVASCRIPT
$(document).ready(function () {
$("phpvariable").hide();
$("#phpvariable").click(function () {
$("#phpvariable").fadeIn(1200)
});
});
You could use ids, but it will be much easier to just give your link a class of say "showForm" and use HTML traversal to hide the form that follows it
$('.showForm').click(function(){
$(this).nextAll('form').first().fadeIn();
});
You can use the echo php statement. Example below:
echo '
$(document).ready(function () {
$("#' . $phpvariable . '").hide();
$("#' . $phpvariable . '").click(function () {
$("#' . $phpvariable . '").fadeIn(1200);
});
});';
I found a much easier method of doing this, thought I should I go back and put this in for reference
//Javascript
$(".testLink").click(function() {
var linkId = $(this).attr('id');
$("#testDiv"+linkId).fadeIn(400)
});
//PHP
for ($i = 0;$i < /*whatever*/; $i++){
?>
Click Here
<div style="display:none;" id="<?php echo 'testDiv'.$i ?>" >
Unique Data
</div>
<?php
}
In this method, a unique id is created between the link clicked, and the element to be manipulated in the javascript. This way each link can be of the same class, but each will have a unique id associated with its corresponding element, i.e div, form, span etc.
Related
I have a form that includes a delete button. I want the user to be able to select all the items they wish to delete at once.
I managed to get the echo to display but the items still remain on the page. Can you please point out why that happens? Any help is appreciated!
Delete button:
<input name="del_btn" type="submit" value="Delete">
The check:
if (isset($_POST['del_btn']) && $_POST['del_btn']){
for($i = 0; $i < count($_POST['checkbox']); $i++){
if (isset($_POST['checkbox'])) {
mysql_query("DELETE FROM `posts` WHERE `id` = '" . $_POST['checkbox'][$i] . "' LIMIT 1");
echo 'deleted';
}
}
}
the items' checkbox:
<input name="checkbox[]" type="checkbox" id="<?php echo $id; ?>" />
This really depends on how variables are defined in your controller, and how they are displayed in your view file.
If you want to hide/clear the values in your forms you can:
Reload the page: create a redirect at the end of your if (isset($_POST['del_btn']) && $_POST['del_btn']){ statement that sends the user back to the new page.
Use jQuery to hide divs where the checkbox is checked.
Redefine variables in your controller after the post to be NULL.
Add a ternary operator to your values in the view so for example <input name="form_input" type="text" value=<?=isset($_POST['del_btn'] ? NULL : $form_input?>> which means that the form will display as NULL when the del_btn is submitted.
<input name="checkbox[]" type="checkbox" id="<?php echo $id; ?>" />
I think you must put something like
<input name="checkbox[]" type="checkbox" value="<?php echo $id; ?>" />
Note the word "value" instead of "id". You are putting the ID in the id attribute. It is to assign a specific target if you want to take the value. (You can use Javascript or JQuery to do this).
In your case, use the tag "value" to ensure that you have correct ID value for your check box. Echo the query and not the word "deleted".
$queryDel = "DELETE FROM posts WHERE id = " . $_POST['checkbox'][$i] . " LIMIT 1";
echo $queryDel;
Please beware of SQL Injection if you are using mysql_query(). Use mysqli instead. Use prepared statement to prevent it or at least provide some white list or validation.
Hope this helps. Thank you.
<input name="checkbox[]" type="checkbox" value ="<?php echo $id; ?>" id="<?php echo $id; ?>" />
Try this it will work. and check the value print_r($_POST) you will able to see all the post value and able to get right value.
When you are using checkbox your element became an array than you can use multiple approaches:
Use ajax (example with jQuery) to avoid submit:
<script>
$(document).ready(function() {
$('[name="del_btn"]').click(function() {
$.post('/my/action.php', $('form').serialize(), function(r) {
if (r.success) {
alert('deleted....');
} else {
alert('error');
}
},'json');
return false; // prevent submit
});
});
</script>
Than you can simplify your code with this:
<?php
if (isset($_POST['checkbox']) && count($_POST['checkbox'])){
$c = implode(',', array_map('intval', $_POST['checkbox'])); // sanitize data
$r = mysql_query("DELETE FROM `posts` WHERE `id` IN(" . $c .")");
echo json_encode(array('success' => $r));
}
Below is a script to upload images and save them to the DB.
On one page of the website, there's a table and inside each <li></li>, there is an upload icon where users can add one image.
The issue is the image upload only works for the "highest" empty <li> on the table.
Here, "highest" means the latest <li> saved in the DB (table is sorted by TIME DESC).
For instance, if I want to upload an image to a random <li></li> on the page, once I select an image, nothing happens. But if I select the "highest" empty (empty = no image saved in DB) <li></li>, it works like a charm.
HTML:
<li id="entry<?php echo $recipe_id ?>">
<div class="addimage_icon" id="upload<?php echo $recipe_id; ?>">
<form id="upload_icon" action="upload_extra.php" method="POST"
enctype="multipart/form-data">
<input class="upload" id="file" type="file" style="display:none" />
<input type="hidden" name="recipe_id" value="<?php echo $recipe_id; ?>"/>
<img class="upload_icon" src="/upload_icon.png">
</form>
</div>
</li>
JAVASCRIPT (upload gets triggered as soon as one image is chosen):
<script>
$('.upload_icon').click(function(){
$(this).parent().find('.upload').click();
});
document.getElementById("file").onchange = function() {
document.getElementById("upload_icon").submit();
}
</script>
PHP:
<?php
include "includes/connnect.php";
$id = $_SESSION['id'];
$recipe_id = mysql_real_escape_string($_POST['recipe_id']);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$recipe_id= $_POST['recipe_id'];
//get image attributes
$add = query("UPDATE cookbook SET recipe_pic = '".$location."' WHERE recipe_id =
'$recipe_id'");
header(Location:"home.php");
}
?>
What's going here ?
There are many, many problems with your question. First of all the HTML you've posted is invalid. I suspect that your Javascript code has a problem with such invalid HTML. However, the following code has not (for your HTML code duplicated once for demonstration purposes):
NodeList.prototype.forEach = Array.prototype.forEach;
document.querySelectorAll('input[type="file"]').forEach(function (file) {
var click = function() {
file.click();
};
var change = function() {
console.log('change:', file.value);
};
file.form.querySelector('img').addEventListener('click', click);
file.addEventListener('change', change);
});
http://jsfiddle.net/eBLL5/
All you need is to assign the correct listeners to the correct elements, as you can see, I do not use any ID values because they are duplicated.
I can use as well duplicate IDs in case you think this is not an argument, this is demonstrated in a related answer:
remove text from multiple spans having same id
I hope this helps you to get the feets again on the ground so that you can continue to validate the HTML and clean up a little bit.
It appears that your html form has
<input type="hidden" value="<?php echo $recipe_id; ?>"/>
However, the input field name attribute is not present so the post data stream will not have a definition for $_POST["recipe_id"] field. The undefined value is likely being interpreted by your script as 0 and so only the top or "highest" li image is updated.
If you alter the input field thus:
<input type="hidden" name="recipe_id" value="<?php echo $recipe_id; ?>"/>
You may have better results...
Just change this part :
document.getElementById("file").onchange = function() {
document.getElementById("upload_icon").submit();
}
With :
$("#file").change(function(){$(this).parents("form").get(0).submit();})
In your HTML, you have:
<form id="upload_icon" action="upload_extra.php" method="POST"
enctype="multipart/form-data">
Then your Javascript mentions:
document.getElementById("file").onchange = function() {
document.getElementById("upload_icon").submit();
}
According to some specifications (HTML4, HTML5), there shouldn't be same IDs on multiple elements. So, when you use an iteration, avoid printing ids without appending something unique on them, like:
<form id="upload_icon<?php print $recipe_id; ?>"
action="upload_extra.php" method="POST" enctype="multipart/form-data">
Your Javascript can be turned into something like the following. (please mind that you need to call this function after the page is loaded)
function afterPageLoad() {
var buttons = document.getElementsByClassName("upload");
for (i = 0; i < buttons.length; i++) {
buttons[i].onchange = function() {
this.form.submit();
}
}
}
Now, if your PHP code has stopped working, we would need to see that, too, at the part you omitted by writing
//get image attributes
where the $location variable is initiated.
In JavaScript provided its submitting the form by finding the element by ID, As in the HTML code the IDs are repeating (not a standard method, IDS can't repeat but class can) so the browser will always submit the last (highest) form only, that's why when adding image to highest row its working and in between its not.
Please check this code out
<script>
$(document).ready(function()
{
id = '';
$('.upload_icon').click(function(){
id = $(this).attr('id');
$(this).parent().find('#file'+id).click();
});
$(".upload").change(function () {
$('#upload_icon'+id).submit();
});
});
</script>
<style>
.upload_icon {
cursor:pointer;
}
</style>
<ul>
<?php for($recipe_id=1;$recipe_id<10;$recipe_id++): ?>
<li id="entry<?php echo $recipe_id ?>">
<div class="addimage_icon" id="upload<?php echo $recipe_id; ?>">
<form action="upload.php" method="POST" enctype="multipart/form-data" id="upload_icon<?php echo $recipe_id; ?>">
<input class="upload" id="file<?php echo $recipe_id; ?>" type="file" name="image" style="display:none"/>
<input type="hidden" name="recipe_id" value="<?php echo $recipe_id; ?>" />
<img class="upload_icon" src="https://cdn2.iconfinder.com/data/icons/picons-basic-2/57/basic2-036_cloud_upload-128.png" id="<?php echo $recipe_id; ?>">
</form>
</div>
</li>
<?php endfor; ?>
</li>
In the HTMl code I have provided have different IDs for each forms (used the $recipe_id as suffix), when ever click event on the upload icon is fired it will check which upload icon is clicked by its attribute Id and then the respective input type file value is changed by finding the element by Id (used the same $recipe_id as suffix here also). On input type change event also same logic is used to fire the respective form.
I have a table that lists my students.. and the License Number Column will either shown the license number or if there is no number in the DB it will show a textbox..
Upon submit (note: no submit button, to keep it need i just press return)
The results from the PHP script will be shown via Ajax.
My complete code is here.
http://pastebin.com/9k0EKXA9
Here is the code within the license number cell on each row:
<td><?php // check if license number exists.
if($row['license_no'] == '')
{
//show form.
?>
<form method="POST" id="license_no_update"">
<input type="text" name="license_no" value="License Number" />
<input type="hidden" value="<?php echo $row['student_id']; ?>" name="student_id" />
</form>
<div id="output"></div>
<?php
}else{
//show license no.
echo $row['license_no'];
}
?></td>
Here Is the JQUERY
<script type="text/javascript">
$(document).ready(function() {
$("#license_no_update").submit(function() {
var license_no_update = $(this).serialize();
$.post('license_update.php', license_no_update, function(data) {
// We not pop the output inside the #output DIV.
$("#output").html(data);
});
return false;
});
});
</script>
The problem i am having, even after searching google many times..
I know i have to have a new form & element id for each row of the table.
but even when i do have those, i do not know how to get JQUERY to find that unique number..
currently with the code attached if i submit on the first row of the table, the correct results are displayed, if i submit on any other row nothing is displayed..
I hope that all makes sense.
Regards
Aaron
Use .find() to find the value of the hidden input within the clicked form. Notice the use of $(this) which is the form itself, and then you can narrow down the input by it's name, since you know the name.
However, it is unclear what you want to do with the id so I left that up to you.
$("#license_no_update").submit(function() {
var studentID = $(this).find("input[name='student_id']").val();
var license_no_update = $(this).serialize();
$.post('license_update.php', license_no_update, function(data) {
// We not pop the output inside the #output DIV.
$("#output-" + studentID).html(data);
});
return false;
});
Update:
Here is one way of creating unique ID's for each output:
if($row['license_no'] == '')
{
//show form.
?>
<form method="POST" id="license_no_update"">
<input type="text" name="license_no" value="License Number" />
<input type="hidden" value="<?php echo $row['student_id']; ?>" name="student_id" />
</form>
<div id="output-<?php echo $row['student_id']; ?>"></div>
<?php
}else{
//show license no.
echo $row['license_no'];
}
What I want to do is that only when I click on a div with id="$project['slug']", it will load the iframe inside that div.
So, i removed the src attribute from the iframe, and add it on onclick event.
I have this in my HTML/PHP:
<div class="box" id="<?=$project['slug']?>" onclick="load_frame();">
<iframe id="frame_<?=$project['slug']?>" frameborder="0"></iframe>
</div>
Js:
function load_frame() {
id = location.hash.replace('#', '');
var source = "<?php echo $project['video']; ?>";
$('#frame_'+id).attr("src", source);
}
Unfortunately, when I inspect the iframe it shows: src="<?=$project['video']?>" instead of the value that the variable holds.
Do you have any idea what i am doing wrong?
thank you!
jQuery is a client side language and have access only to the DOM elements once they have been rendered. So what you need to do is store $project['video'] variable in a hidden field and then using the id of that field get access to the rendered data.
Also, i noticed that you should use <?php instead of <?
You may try something like this.
<div class="box" id="<?php echo $project['slug']; ?>">
<iframe id="frame_<?php echo $project['slug']; ?>" frameborder="0"></iframe>
<input type="hidden" id="<?php echo $project['slug']; ?>" value="<?php echo $project['video']" />
</div>
Then in jQuery do:
$(document).ready(function(){
$('.box').click(function(){
var slug = $(this).attr('id');
var source = $('input#' + slug).val();
$('iframe#' + slug).attr("src", source);
});
});
add hidden input on html page
<input type="hidden" id="hidsource" value="<?php echo $project['video']" />
edit your function in js like this
function load_frame() {
id = location.hash.replace('#', '');
$('#frame_'+id).attr("src", $('input#hidsource').val());
}
hope this will work
You might not have the shorthand syntax enabled on the server. Try standard PHP instead:
<?php echo $project['slug']; ?>
Hi Stackoverflow i hope you are all well today,
i seem to have run into an issue and am kindly requesting your assistance;
Basically i am using jQuery to manipulate a form, the form then stores in the session and upon returning to the page a foreach loop is used to return the values from the session into the page.
The issue is if I create more than one instance of this foreach loop it gives me an invalid argument (if i add the same code over and over again it works fine)
So firstly here is the code;
jQuery
$(function(){
$('.add_child').click(function(){
var attrName = $(this).attr('name');
var count = $(this).attr('count');
$(this).attr('count', (parseInt(count)+1))
var input = $('<input />');
var lineBreak = $('<br/>');
input.attr('type','text')
input.attr('name',attrName+"["+count+"]" )
$('.children_form').append(input);
$('.children_form').append(lineBreak);
})
$('.add_s_child').click(function(){
var attrName = $(this).attr('name');
var count = $(this).attr('count');
$(this).attr('count', (parseInt(count)+1))
var input = $('<input />');
var lineBreak = $('<br/>');
input.attr('type','text')
input.attr('name',attrName+"["+count+"]" )
$('.spouce_children').append(input);
$('.spouce_children').append(lineBreak);
})
});
and the PHP / HTML CODE -> Button One (add_child)
Children, please name your natural and / or addopted children
<?php foreach($_SESSION['children'] as $index=>$child){ ?>
<?php echo "<input type='text' name='children[{$index}]' value='{$child}'/>";?>
<?php } ?>
<input type="button" count='<?php echo count($_SESSION['children']);?>' name="children" class="add_child" value="Add Another Child"/>
<div class="children_form">
<?php //add the inputs here?>
</div>
and the PHP / HTML CODE -> Button Two (spouce_children)
<label>Spouces Children, please name all natural and addopted children</label>
<input type="text" name="spoucechild" id="spoucechild" />
<?php foreach($_SESSION['spoucechild'] as $index=>$child){ ?>
<?php echo "<input type='text' name='spoucechild[{$index}]' value='{$child}'/>";?>
<?php } ?>
<input type="button" count='<?php echo count($_SESSION['spoucechild']);?>' name="spoucechild" class="add_s_child" value="Add Another Child"/>
<div class="spouce_children">
<?php //add the inputs here?>
</div>
I would like to thank you for any help you can / will provide <3
Error Occurs here:
<?php foreach($_SESSION['spoucechild'] as $index=>$child){ ?>
#Xavier: You could try --
<?php
if (isset($_SESSION['spoucechild'])) {
foreach($_SESSION['spoucechild'] as $index=>$child){
echo '<input type="text" name="spoucechild[' . $index . ']" value="' . $child . '" />' . "\n";
}
}
?>