Accessing live data created by jQuery in php - javascript

I have a method in my jQuery code which generates rows and add them to my table in html as follows (and works fine):
$(document).ready(function () {
$("#textDateAndTime").datetimepicker();
$(document).on("click","#ulInvite li h6",function(){
var h=this;
var selected=h.innerText.split(' ')[0];
var myExp=new RegExp(selected,"i");
$.getJSON("json_data.php",function(data){
$.each(data,function(key,val){
if((val.username.search(myExp))==0){
var output="<tr>"
+"<td>"+val.username+"</td>"
+"<td>"+val.firstName+"</td>"
+"<td>"+val.lastName+"</td>"
+"</tr>";
$("#tableInvite").append(output);
h.parentNode.parentNode.removeChild(h.parentNode);
}
});
});
});
And this is my table in the html file which is simple:
<table name="tableInvite" id="tableInvite" border="1px solid black">
</table>
Then I want to use the generated rows in my php file, which is called in <form> tag in html by method post. I use simple_html_dom.php file to parse my table with find method, but it don't get <td> elements because they were generated by jQuery, while it would get them fine if those were in html file originally.
require('simplehtmldom_1_5/simple_html_dom.php');
$html = file_get_html('add_meeting.html');
foreach($html->find('tr') as $row) {
$username = $row->find('td',0)->plaintext;
$firstname = $row->find('td',1)->plaintext;
$lastname = $row->find('td',2)->plaintext;
}
but it never gets to foreach because it can't find any <tr> elements there.
So, how can I access those rows generated live?
Thanks.

Related

ajax method ($.post) with mysql not working simple code

i have problem this code not working , i want display result of mysql without send no data
my simple code ajax
$('.myClass').on('click',function(){
$.post('resultAll.php');
});
code html
<li class="myClass" > click this </li>
code php / mysql for display result on page (name resultAll.php)
$stmt = $connect->prepare('SELECT * FROM table WHERE price = :aff');
$stmt->execute(array(':aff'=>'5'));
$res = $stmt->fetchAll();
foreach ($res as $row) {
?>
<div class="noon" style="width: 1000px;height: 500px">
<?php print_r($row['id'].' '); ?>
</div>
result these nothing
As per your code snippet, you want to fetch data from resultAll.php file into your HTML page. If I am correct then your code is wrong, you have to use below method instead of $.post() method
$('.myClass').on('click',function(){
$("#result").load('resultAll.php');
});
Your HTML code should be
<li class="myClass" > click this </li>
....
...
<div id="result"></div>
I mean in your page must have one div tag with id="result".
I hope this is works for you.
As you say that your Jquery is not working. Is your element .myClass is created with JS dynamically? Ensure this:
$(document.body).on('click', '.myClass', function(){
$.post('resultAll.php');
});
Edit
Add response from $.post to body:
$('.myClass').click(function(){
$.post('resultAll.php', function(response){
$(body).append(response);
});
});

Clear or Delete file from textField

I am working with PHP's Yii framework and having issues clearing or deleting the uploaded file from the textfield. Currently, it will delete the content from the fileField, but can't get it to delete the textfield. Any ideas?
UPDATE
I can now clear my textField because I've hard coded my clearFileInputField function by adding $('.getFile').val(""); I reference this in my HTML by adding the 'class' => 'getName' in the input section. While this clears the data, it doesn't remove the file after saving. Any suggestions?
HTML
<div id = "clearContent">
<?php echo $form->labelex($model,'info'); ?>
<?php echo $form->textfield($model,'info', array(placeholder => "No file chosen", readonly => true, 'class' => 'getName')); ?><br>
<?php echo $form->fileField($model,'info'); ?>
<?php echo $form->error($model,'info'); ?>
<input type="checkbox" onclick = "clearFileInputField('clearContent')" href="javascript:noAction();"> Remove File
</div>
JavaScript:
<script>
function clearFileInputField(tagId) {
document.getElementById(tagId).innerHTML = document.getElementById(tagId).innerHTML;
$('.getFile').val("");
}
</script>
I am not sure if I understood the problem you are having correctly. If I understood the question completely wrong, please elaborate and I will try to improve my answer.
If you want to remove the the content (the value attribute) of a text and file input you can use code like the following:
// listen to the click on the #clearnbtn element
document.getElementById('clearbtn').addEventListener('click', function() {
// Remove the value of the #foo and #bar elements
document.getElementById('foo').value = "";
document.getElementById('bar').value = "";
});
If you would like to remove an entire field you can do that like so:
// Retrieves the input element, gets its parents and removes itself from it
var fooElement = document.getElementById('foo');
fooElement.parentElement.removeChild(fooElement)
Or you can set the innerHTML attribute of the parent element to an empty string ('').
document.getElementById('clearContent').innerHTML = "";
https://jsfiddle.net/osjk7umh/1/

Separating variables for SQL insert using PHP and JavaScript

A grid table is displayed via PHP/MySQL that has a column for a checkbox that the user will check. The name is "checkMr[]", shown here:
echo "<tr><td>
<input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\"
data-info=\"{$Row[BOL_NUMBER]}\" data-to=\"{$Row[TO_NUMBER]}\"
name=\"checkMr[]\" />
</td>";
As you will notice, there is are attributes for id, data-info, and data-to that are sent to a modal window. Here is the JavaScript that sends the attributes to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
var selectedBL = [];
var selectedTO = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
selectedBL.push($(this).attr('data-info'))
selectedTO.push($(this).attr('data-to'))
});
$(".modal-body .containerNumber").val( selectedID );
$(".modal-body .bolNumber").val( selectedBL );
$(".modal-body .toNumber").val( selectedTO );
});
});
</script>
So far so good. The modal retrieves the attributes via javascript. I can choose to display them or not. Here is how the modal retrieves the attributes:
<div id="myModal">
<div class="modal-body">
<form action="" method="POST" name="modalForm">
<input type="hidden" name="containerNumber" class="containerNumber" id="containerNumber" />
<input type="hidden" name="bolNumber" class="bolNumber" id="bolNumber" />
<input type="hidden" name="toNumber" class="toNumber" id="toNumber" />
</form>
</div>
</div>
There are additional fields within the form that the user will enter data, I just chose not to display the code. But so far, everything works. There is a submit button that then sends the form data to PHP variables. There is a mysql INSERT statement that then updates the necessary table.
Here is the PHP code (within the modal window):
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
$to = $_POST['toNumber'];
if(isset($_POST['submit'])){
$bol = mysql_real_escape_string(stripslashes($bol));
$container = mysql_real_escape_string(stripslashes($container));
$to = mysql_real_escape_string(stripslashes($to));
$sql_query_string =
"INSERT INTO myTable (bol, container_num, to_num)
VALUES ('$bol', '$container', '$to')
}
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Saved')
</script>");
}
else{
echo ("<script language='javascript'>
window.alert('Not Saved')
</script>");
}
?>
All of this works. The user checks a checkbox, the modal window opens, the user fills out additional form fields, hits save, and as long as there are no issues, the appropriate window will pop and say "Saved."
Here is the issue: when the user checks MULTIPLE checkboxes, the modal does indeed retrieve multiple container numbers and I can display it. They seem to be already separated by a comma.
The problem comes when the PHP variables are holding multiple container numbers (or bol numbers). The container numbers need to be separated, and I guess there has to be a way the PHP can automatically create multiple INSERT statements for each container number.
I know the variables need to be placed in an array somehow. And then there has to be a FOR loop that will read each container and separate them if there is a comma.
I just don't know how to do this.
When you send array values over HTTP as with [], they will already be arrays in PHP, so you can already iterate over them:
foreach ($_POST['bol'] as $bol) {
"INSERT INTO bol VALUES ('$bol')";
}
Your queries are vulnerable to injection. You should be using properly parameterized queries with PDO/mysqli
Assuming the *_NUMBER variables as keys directly below are integers, use:
echo '<tr><td><input type="checkbox" value="'.json_encode(array('CONTAINER_NUMBER' => $Row[CONTAINER_NUMBER], 'BOL_NUMBER' => $Row[BOL_NUMBER], 'TO_NUMBER' => $Row[TO_NUMBER])).'" name="checkMr[]" /></td>';
Then...
$('a#specifyAnchor').click(function() {
var selectedCollection = [];
$(':checkbox[name="checkMr[]"]:checked').each(function() {
selectedCollection.push($(this).val());
});
$(".modal-body #checkboxCollections").val( selectedCollection );
});
Then...
<form action="" method="POST" name="modalForm">
<input type="hidden" name="checkboxCollections" id="checkboxCollections" />
Then...
<?php
$cc = $_POST['checkboxCollections'];
if (isset($_POST['submit'])) {
foreach ($cc as $v) {
$arr = json_decode($v);
$query = sprintf("INSERT INTO myTable (bol, container_num, to_num) VALUES ('%s', '%s', '%s')", $arr['BOL_NUMBER'], $arr['CONTAINER_NUMBER'], $arr['TO_NUMBER']);
// If query fails, do this...
// Else...
}
}
?>
Some caveats:
Notice the selector I used for your previous $('a').click() function. Do this so your form updates only when a specific link is clicked.
I removed your mysql_real_escape_string functions due to laziness. Make sure your data can be inserted into the table correctly.
Make sure you protect yourself against SQL injection vulnerabilities.
Be sure to test my code. You may have to change some things but understand the big picture here.

Dynamically appending a row by cloning an existing row?

I have a row in a table and that row is not displayed as css style is set to display:none .
HTML table:
<table class="myTable">
<tr class="prototype">
........
</tr>
</table>
CSS code:
.myTable .prototype{display:none;}
Now i have to clone the same row and add some data to it and append the row to the table as below: i have below jquery code:
var master = $(this).parents("table.myTable");
var prot = master.find(".prototype").clone();
prot.attr("class", "");
prot.find("#attributeValue").attr("value", "ABC");
prot.find("#contactFirstName").attr("value", "XYZ");
jQuery('table.myTable tr:last').before(prot);
But the row won'ttbe added to the table. Please help me.
Thanks!
If you run the code in the onLoad event, change the first line to var master = $(this).find("table.myTable"); or var master = $("table.myTable");
Use prot.removeClass(); instead of prot.attr("class", "");
Ids have to be unique, if elements in your prototype-row have an id you get invalid HTML.
Use $().val('ABC') instead of $().attr('value', 'ABC')
If it still doesn't work, please show more code (maybe a jsfiddle).
var master = $(this).parents("table.myTable");
var prot = master.find("tr.prototype").clone();
prot.removeClass('prototype');
prot.find("#attributeValue").val("ABC");
prot.find("#contactFirstName").val("XYZ");
master.append(prot);
prot.show();

How to write a table content to an xml?

Can somebody tell me how can i write a clientside table control content to an xml on a button click . I'm using a clientside table "selectedTexts" and on save button click i need to save the table content to an xml. Please help.
$(document).ready(function() {
$('#<%=btnSave.ClientID %>').click(function(event) {
var xml = "<schedule>";
$("#selectedColumns").find("tr").each(function() {
xml += "<data>";
xml += $(this).find("td").eq(1).html() + "\n";
xml += "</data>";
});
xml += "</schedule>";
this.isPrototypeOf(
alert(xml);
})
});
I managed to get the string in an xml format. How can i pass this string to my codebehind so that i can write it to an xml file. Or is it any other methods available to write it from the clientside itself?
if your table's code is as follows:
<table id="root">
<tr id="category_1">
<td>value-1</td>
<td>value-2</td>
</tr>
<tr id="category_2">
<td>value-7</td>
<td>value-8</td>
</tr>
</table>
then following JQuery will convert it to a xml where comments wih // denote first time output:
var xml="";
$("#root").each( function(index){
xml +="<"+$(this).attr("id")+">";
// <root>
$("#root tr").each( function(index){
xml +="<"+$(this).attr("id")+">";
// <root><category_1>
$(td,this).each( function(index){
xml +="<"+$(this).html()+">";
// <root><category_1><value_1><value_2>
}
}
}
Should work :-) ta-da...
#NewBie: I assume you are unable to generate id for <tr> so I am suggesting this way:
As you see in the code I have written: $("#root tr").each( function(index){
Here, index is the loop variable to represent current node/count of the matched element. For example if you had 50 <tr> row then index starts with 1 and goes upto 50. Thus you can use this variable to mark your <tr> tag :-)
Just edit like this:
$("#root tr").each( function(index){
xml +="<"+index+">"; // replaced $(this).attr("id") with index
// other codes here
}
Best of luck...

Categories

Resources