how to fetch html data when it's add dynamic via jquery - javascript

$("#add").click(function()
{
$("#content").append("<input type=text name=resource>");
})
I have to work with dynamically add text box so how fetch those value in php.

Jquery Dynamic Adding:
$("#add").on('click',function()
{
$("#content").append("<input type=text name=resource[] />");
});
PHP Code with Metod POST:
$data =$_POST['resource'];
For Individual Values:
foreach($data as $vals)
{
echo $vals;
}

hay it's just resource name as array like
resource[]

if php variable available, then you can add that variable inside the append or anywhere likes following
$("#add").click(function() {
$("#content").append("input type=text name=resource value="<?php echo $variable; ?>">);
});

Related

PHP loop value sent to javascript

I'm avoiding using a database for my latest project and so I am using files and folders. I list folders of a directory as buttons and each one loads a screen with a list of files within it. I'm now trying to load in the file's contents dynamically without refresh to avoid loosing the menu (list of files shown on screen as buttons). I'm trying to use ajax but because the file buttons are created using a foreach php loop, the value I pass to javascript/ajax when I click one of the file buttons is incorrect as it always wants to pass the first button's value in the list!
Here is the PHP code:
<?php
if(isset($_POST['FolderContent'])) {
foreach (glob($_POST['FolderContent']."/*.*") as $file) {
if(is_file($file)){
$fileNoExt = substr($file, 0, -4); //Remove file extension so the menu item shows only the name of the file
$character = explode('/', $fileNoExt);
$filePathTrimmed = trim(end($character));
echo "<form method='POST'>
<input type='submit' ID='selectBtn' value='$filePathTrimmed' onclick='return displayData();'/>
<input type='hidden' id='dataField' name='content' value='$file'/>
<input type='hidden' name='title' value='$filePathTrimmed'/>
</form>";
} else {
echo "Files not found!";
}
}
}
?>
And this is the JS:
<script>
function displayData()
{
var btnData = document.getElementByID('selectBtn').value;
alert("The currently selected button is "+btnData);
});
}
</script>
As you can see the PHP loops and creates a form for each button plus hidden fields. The JS just tries to grap the value of the button clicked and alert it. Problem is that the value is always the first file in the list.
What am I doing wrong please? If I use a class on the button instead of an ID then I will need to state the number in the array:
var btnData = document.getElementsByClassName('selectBtn')[0].value;
But this means I'd need to know the place within the array and make using the value pretty pointless.
I'm pretty stuck - or thick!
Thanks.
You need to use this inside onclick='return displayData(); and then use it in your function like below:-
Working snippet:-
function displayData(ele){
var btnData = ele.value;
alert("The currently selected button is "+btnData);
return false;
}
<form method='POST'>
<input type='submit' value='hi' onclick='return displayData(this);'/>
<input type='hidden' name='content' value='$file'/>
<input type='hidden' name='title' value='$filePathTrimmed'/>
</form>
You are setting the same id value for each separate form. You should ensure that all the id attribute values are unique for all html elements as a rule of thumb to avoid unpredictable behaviours in the dom.
<?php
if(isset($_POST['FolderContent'])) {
foreach (glob($_POST['FolderContent']."/*.*") as $idx => $file) {
if(is_file($file)){
$fileNoExt = substr($file, 0, -4); //Remove file extension so the menu item shows only the name of the file
$character = explode('/', $fileNoExt);
$filePathTrimmed = trim(end($character));
echo "<form method='POST'>
<input type='submit' id='selectBtn-{$idx}' value='$filePathTrimmed' onclick='return displayData(this.id);'/>
<input type='hidden' id='dataField' name='content' value='$file'/>
<input type='hidden' name='title' value='$filePathTrimmed'/>
</form>";
} else {
echo "Files not found!";
}
}
}
?>
And javascript:
<script>
function displayData(clicked_id)
{
var btnData = document.getElementByID(clicked_id).value;
alert("The currently selected button is "+btnData);
return false;
}
</script>
Solution: I used 'return false' at the end of the javascript/ajax code block, and 'this' in the php code to pass current data held in 'value' - thanks Alive to Die.
I also I made use of the 'name' attribute to store and access further data data.
PHP:
echo "<form method='POST'>
<input type='submit' id='selectBtn' name='$file' value='$filePathTrimmed' onclick='return displayData(this);'/>
</form>";
JS:
<script>
function displayData(fileName)
{
var btnData =fileName.name;
var name = fileName.value;
$.ajax({
type : "POST",
url : "DisplayFileContents.php",
data : {"data": btnData, "name": name},
success : function(result) {
$('.page-content').html(result);
$('body').animate({scrollTop: 0}, 200);
}
});
return false;
};
DisplayFileContents.php:
<?php
$filename=$_POST['data'];
$title = $_POST['name'];
echo "<h2>".$title."</h2>";
echo "<pre>";
Include $filename;
echo "</pre>";
?>

looping file upload form with PHP

im currently using jquery booklet Moleskine Notebook with jQuery Booklet to make a logbook with some images to be uploaded for every page.
what im doing is im looping the div of every page in php as im calling data from DB, but when i tried to use file upload form as follows , it only works on first page on. the upload button appeared on every other page but it does nothing, not even call the upload window.
every page has its own log_id $row['log_id'].
so any solution is much appreciated.
if (mysqli_multi_query($conn, $sql)) {
do {
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_array($result)){
echo '<div>';
echo ' <form method="post" name="upload_form" id="upload_form" enctype="multipart/form-data" action="php/multiple_upload.php">';
echo ' <input type="hidden" name="form_submit" value="1"/>';
echo ' <input type="file" class="hidden" name="images[]" id="upload-images" multiple >';
echo ' <input name="log_id" type="hidden" value="'.$row['log_id'].'">' ;
echo ' </form>';
echo '</div>' ;
}
mysqli_free_result($result);
}
} while (mysqli_next_result($conn));
}
and the here is the script for calling form
$(document).ready(function(){
$('#upload-images').on('change',function(){
$('#upload_form').ajaxForm({
beforeSubmit:function(e){
$('.progress').show();
},
success:function(e){
$('.progress').hide();
location.reload(true);
},
error:function(e){
}
}).submit();
});
});
If you're using id $('#upload_form').ajaxForm({***});. This will only find and target the first #upload_form
And if you're using class like $('.upload_form').ajaxForm({***});. This will find and target all the form class .upload_form
You need to define which form you're looking for. In this case, You just need to find the closest/parent of .upload-images form. Like below.
Do like this.
$(document).ready(function(){
$('.upload-images').on('change',function(){
$(this).closest('form').ajaxForm({ // target the parent form
beforeSubmit:function(e){
$('.progress').show();
},
success:function(e){
$('.progress').hide();
location.reload(true);
},
error:function(e){
}
}).submit();
});
});

Pass value from a table into a function using jquery

I was trying to pass the variable thecode, which is in the table using jquery into the function named getComments(). My code has as following. First I have my jquery script which is this:
$(document).ready(function(){
$("#comment_process").click(function(){
if($("#comment_text").val() != ""){
$('.post_loader').show();
$.post("comments_business.php?action=post", {
comment: $("#comment_text").val()
}, function(data) {
$(".comments").hide().html(data).fadeIn('slow');
$("#comment_text").val("");
$('.post_loader').hide();
});
}
});
});
Next I have the following script with html and php:
<!--- more code at the top---->
<?php $auto = $profile_data_business['business_code']; ?>
<table>
<textarea rows="3" id="comment_text" placeholder="share an update."></textarea>
<input type="" id="comment_code" name="thecode" value="<?php echo $auto; ?>" />
<input type="button" id="comment_process" />
</table>
<div class="comments"><?php include_once("comments_business.php");?> </div>
the page named comments_business.php includes a function which is the following:
<?php
function getComments(){
$session_user_id = $_SESSION['user_id'];
$comments = "";
// can't get variable $thisemail
$thisemail = mysql_real_escape_string($_POST['thecode']);
$sql = mysql_query("SELECT * FROM comments_business WHERE ( `flag`=0 and `user`='$thisemail' and `comments_id` NOT IN (SELECT `comments_id` FROM `hide_comment_business` where `user`='$session_user_id') ) ORDER BY comment_date DESC LIMIT 40") or die (mysql_error());
//more code here
return $comments;
}
?>
Any idea how should I change my jquery code so that I will be able to pass $thisemail variable successfully into getComments() function?
When you use $.post don't need to write GET parameter in URL (action=post).
When you post data by comment name, you must get data by some name
in php ($_POST['comment']).
When you use ajax shouldn't use function in php or call function
after defintion.
When you use ajax must print or echo data in php file to display in
post result.

Why wont javascript get values of php generated html?

im using ajax to query my mysql to my database.
But im stock at issue with my php generated html form input - javascript/jquery will simply not pick up the value. From normal html is no issue of course.
php (works fine, all echos are good)
<?php
function getAge() {
$age = "<select name='age'>";
$result = $mysqli->query("select * from ages");
while ($row = $result->fetch_row()) {
$age.="<option value=" . $row[0] . ">". $row[1] ."</option>";
}
$age.="</select>";
return $age;
}
?>
html
<form id="myform">
<input name='name' value='Nick'>
<input name='sport' value='Football'>
<?php echo getAge(); ?>
<input type='submit'>
</form>
javascript
$("form#myform").on('submit', function(e){
e.preventDefault();
var json = {}
$.each(this.elements, function(){
json[this.name] = this.value || '';
});
}
Everything works well except it wont get the value of the <select>. If i make a normal html select it works.. ?!
Also anybody know how to delete the submit button from the json object? :-)
Any dynamically generated HTML will not have the events applied to them, as those events are applied on page load. So if you apply the events to the document, you will be able to pull values from dynamically generated html. Like so:
var json = {};
$(document).on('submit', 'form#myform', function(e){
$('*', this).each(function(){
json[$(this).attr('name')] = $(this).val();
});
});
Hope this helps!
change this line:
$age.="<option value=" . $row[0] . ">". $row[1] ."</option>";
to this:
$age.="<option value='" . $row[0] . "'>". $row[1] ."</option>";
//----------------^---------------^------put quotes
And i think you can make use of .serializeArray() which does the same you want but in a different way like multiple objects with multiple [{ name : value}] pairs:
$(function(){ //<-----put this block too
$("form#myform").on('submit', function(e){
e.preventDefault();
var json = $(this).serializeArray();
}); //<----checkout the closing
}); //<---doc ready closed.

JQUERY .val not working......HTML table created using PHP unable to get the specific row value

I have created a HTML table using a echoing each row in a by looping through the rows of the database which is stored into the PHP fetch array function after retrieving from the database using the SELECT statement. Along with this I added another column which is a submit button hence it looped through every each row.
I did this so that I could get the "ID" of each row when submitted and run another script using AJAX JQUERY. But the problem is that my javascript code only gets the value of the first row when submited and it is unresponsive to the other rows.
Table code:
<form id="mainform">
<table>
<th>ID</th>
<?php
$result = mysql_query("SELECT * FROM test");
while ($row = mysql_fetch_array($result)) {
$ID = $row['ID'];
echo "<td><input type='hidden' id='hiddenfield' value='$ID'></td>";
echo "<td><input type='submit' value='select' /></td>";
}
?>
</table>
</form>
Javascript:
$("#mainform").on("submit", function(){
$("#testdiv").empty();
$.get("boom.php", { ID: $("#hiddenfield").val() },
function(data) {
$("#newdiv").append(data);
});
});
</script>
With this AJAX code I am trying to get the value to boom.php where now I am just testing if the correct value has been parsed.
Anyone can help me out? I am stuck...
There are two problems: first, you can't reuse the same id on multiple fields. They must be unique. Use a class:
echo "<td><input type='hidden' class='hiddenfield' value='$ID'></td>";
even then, .val() will only return the first matching item's value.
Assuming you want to pass a list of ID values, you'll need to build the list yourself:
$("#mainform").on("submit", function(){
$("#testdiv").empty();
var vals = [];
$('.hiddenfield').each(
function() {
var field = $(this);
vals.push(field.val());
}
);
$.get("boom.php", { ID: JSON.stringify(vals) },
will pass a string version of the list (e.g. ["1","2","3"]);
If you want to send each ID separately, do so within the each loop:
$('.hiddenfield').each(
function() {
var field = $(this);
$.get("boom.php", { ID: field.val() },
}
);

Categories

Resources