PHP AJAX within a table - php

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'];
}

Related

How to fetch value of a drop-down and a text box after btn click?

I have a form wherein I have a drop down which is being populated from the database also I have an input box right beneath it. I want to fetch the value of both the fields via Ajax using jQuery and insert them into the database.
Problem: Value of the text field is getting inserted successfully but the value of drop down is not getting inserted.
I know I will have to fetch the value of the drop down separately and then add it to the data in ajax but I am not able to figure how to do the same.
NOTE: COULD THE DOWN VOTERS BE KIND ENOUGH TO TELL ME WHY I WAS DOWNVOTED SO THAT I COULD IMPROVE UPON THINGS.
sub_category_add.php
<form method="post">
<select id="cat_sub_cat">
<?php
$data=mysqli_query($con,"SELECT * FROM category");
while($row=mysqli_fetch_array($data))
{
echo "<option value=".$row['cid'].">".$row['category']."</option>";
}
?>
</select><br><br>
<h3>Add Sub Categories</h3><br>
<input type="text" name="sub_cat"><br><br>
<input type="submit" name="submit" value="Insert" id="sub_cat_btn">
</form>
Ajax File:
$(document).on('click','#sub_cat_btn', function(event){
event.preventDefault();
$.ajax({
url:"sub_cat_add_back.php",
method:"post",
data:$('form').serialize(),
dataType:"html",
success:function(strMsg){
$("#cat_sub_msg").html(strMsg);
}
})
sub_cat_add_back.php
<?php
include "../includes/config.php";
$name=$_POST['sub_cat'];
$cid=$_POST['cat_sub_cat'];
$data=mysqli_query($con,"INSERT INTO subcategory (name,cid) VALUES ('$name','$cid')");
if($data=="true")
{
echo "Successfully Inserted";
}
else
{
echo "Error";
}
?>
Your problem is that the select tag does not have the Name attribute
<select id="cat_sub_cat" name="cat_sub_cat">
If you want to get values on click instead of form serialize. add id in input
<input type="text" name="sub_cat" id="custom">
$("#cat_sub_cat option:selected");
$("#custom").val();
and if you want to do that with form serialize then add name in your select
<select id="cat_sub_cat" name="your_select_name">

Save values in db with submit button only

I am trying to save some values into db, on first page i am running some matches and on the the 2nd page i need to save values. on first page only click button is shown to user, when he clicks , the values are stored.
code
<form action="ms_insert.php" method="post">
<input type="submit" value="Claim your daily bonus" name="test">
</form>
How can i submit all the values that are outside the form and send them to the ms_insert.php and process the values.
What i need to achieve it like this.
some values shall be matched , on successful match it will save the enteries into the db.
Here is the exact code that i am using now :
<?php
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
$sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
echo "success";
}
else
{
echo "wrong";
}
?>
<form action="" method="post">
<input type="hidden" value="123" name="match">
<input type="submit" value="Claim your daily bonus $o.o2" name="claim">
</form>
I want this php code to excute when user click the submit button.
There are two ways that I can think of doing this:
Simply set the post variable to another value as described here:
$_POST['text'] = 'another value';
This will override the previous value corresponding to text key of the array. The $_POST is super global associative array and you can change the values like a normal php array.
Second would be to use _SESSION tags as described in this post:
In the first.php:
$_SESSION['favcolor'] = 'green';
In ms_insert.php:
echo $_SESSION['favcolor']; // green
P.S. You can also use cookies
Additional sources:
http://www.felixgers.de/teaching/php/hidden1.html
You can use Javascript with a XHR object for example or try to insert your values to store in hidden inputs.
Solution 1 : AJAX, for example :
Your JS (Here with Jquery):
function saveInDb(){
/* Retrieve your values in your page : */
var myValue1 = $('#value1Id').val();
var myValue2 = $('#value2Id').val();
/*Create a Jquery ajax object : */
$.ajax({
type: "POST",
url: "ms_insert.php",
data: { "value1": myValue1, "value2": myValue2 }
}).done(function( msg ) {
alert( "Data Saved");
});
}
Your HTML :
<span id="value1Id">My value 1</span>
<span id="value2Id">My value 2</span>
<button onclick=saveInDb()></button>
Solution 2 : the HTML with hidden inputs :
<form action="ms_insert.php" method="post">
<input type="hidden" value="My value 1" name="value1">
<input type="hidden" value="My value 2" name="value2">
<input type="submit" value="Claim your daily bonus" name="test">
</form>

Value Checkbox Inside modal

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.

Image upload script only works for latest <li></li> saved in DB

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.

Allow user to create and submit up to 5 text boxes with jquery, and parse them into one array in php?

Is it possible?
I want a user to post an array full of 1-5 pieces of data.
At first there would be only one text field on show, but on clicking a 'plus' icon next to it, it would create another text field below it for more user input.
I would also want to have a delete icon next to text boxes 2-5, to remove them if necessary.
My JQuery knowledge is limited, and I can work out how to append text boxes to a list, but not to keep track of them/delete them. Ideally I would also want to pass them as an array to php, so I can easily loop through them.
<input type="text" size="15" maxlength="15" name="1"><img src="add.png" onclick="add();">
<!-- Below is hidden by default, and each one shows on click of the add image -->
<input type="text" size="15" maxlength="15" name="2"><img src="delete.png" onclick="delete(2);">
<input type="text" size="15" maxlength="15" name="3"><img src="delete.png" onclick="delete(3);">
<input type="text" size="15" maxlength="15" name="4"><img src="delete.png" onclick="delete(4);">
<input type="text" size="15" maxlength="15" name="5"><img src="delete.png" onclick="delete(5);">
jQuery clone() is very handy for this. A small example how it could be done (working example on jsfiddle)
<ul>
<li><input type="text" name="textbox[]" /></li>
</ul>
<input type="button" id="addTextbox" value="Add textbox" />
<script type="text/javascript">
$(function(){
$('#addTextbox').click(function(){
var li = $('ul li:first').clone().appendTo($('ul'));
// empty the value if something is already filled in the cloned copy
li.children('input').val('');
li.append($('<button />').click(function(){
li.remove();
// don't need to check how many there are, since it will be less than 5.
$('#addTextbox').attr('disabled',false);
}).text('Remove'));
// disable button if its the 5th that was added
if ($('ul').children().length==5){
$(this).attr('disabled',true);
}
});
});
</script>
For the server-side part, you could then do a foreach() loop through the $_POST['textbox']
As long as you give each text box a name like "my_input[]", then when the form is submitted, PHP can get the answer(s) as an array.
$_REQUEST['my_input']; would be an array of the values stored in each text box.
Source: Add and Remove items with jQuery
Add
Remove
<p><input type="text" value="1" /></p>
<script type="text/javascript">
$(function() { // when document has loaded
var i = $('input').size() + 1; // check how many input exists on the document and add 1 for the add command to work
$('a#add').click(function() { // when you click the add link
$('<p><input type="text" value="' + i + '" /></p>').appendTo('body'); // append (add) a new input to the document.
// if you have the input inside a form, change body to form in the appendTo
i++; //after the click i will be i = 3 if you click again i will be i = 4
});
$('a#remove').click(function() { // similar to the previous, when you click remove link
if(i > 1) { // if you have at least 1 input on the form
$('input:last').remove(); //remove the last input
i--; //deduct 1 from i so if i = 3, after i--, i will be i = 2
}
});
$('a.reset').click(function() {
while(i > 2) { // while you have more than 1 input on the page
$('input:last').remove(); // remove inputs
i--;
}
});
});
</script>
You will need to create DOM elements dynamically. See how it is done for example in this question. Notice that
document.createElement
is faster then using jquery's syntax like
$('<div></div>')
Using that technick, you could create inputs like
<input name="id1"/>
<input name="id2"/>
<input name="id3"/>
<input name="id4"/>
<input name="id5"/>
On submitting your form you'll get all them in your query string like
...id1=someval1&id2=someval2&...
Having that, you could process this query as you want on server side.
<form method="POST" id="myform">
<input />
Add textbox
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#add_textbox').click(function(){
var form=$(this).closest('form');
var count=form.find('input').length();
form.append('<div class="removable_textbox"><input />delete</div>');
$('.delete_input').click(function(){
$(this).find('.removable_textbox').remove();
return false;
});
return false;
});
$('#myform').submit(function(){
var i=1;
$(this).find('input').each(function(){
$(this).attr('name','input-'+i);
i++;
})
});
});
</script>
<?php
if(isset($_POST['input-1'])){
$input_array=$_POST;
}
?>
something like this?
I wrote a litte jQuery plugin called textbox. You can find it here: http://jsfiddle.net/mkuklis/pQyYy/2/
You can initialize it on the form element like this:
$('#form').textbox({
maxNum: 5,
values: ["test1"],
name: "textbox",
onSubmit: function(data) {
// do something with form data
}
});
the settings are optional and they indicate:
maxNum - the max number of elements rendered on the screen
values - an array of initial values (you can use this to pass initial values which for example could come from server)
name - the name of the input text field
onSubmit - onSubmit callback executed when save button is clicked. The passed data parameter holds serialized form data.
The plugin is not perfect but it could be a good start.

Categories