Filemaker, PHP and jquery > show hide elements - javascript

I am echoing out a form (foreach) from my filemaker records which will result in the items ID, Name, a Checkbox and then an image.
In my understanding i will have to use classes or the elements will all have the same id.
My Code;
foreach($result->getRecords() as $record){
$id = $record->getField('Record_ID_PHP');
$name = $record->getField('DB_Name');
$pic = $record->getField('Photo_Path');
echo '"'.$id.'"<br>';
echo $name.'<br>';
echo '<input type="checkbox" class="check" value="Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/'.$pic.'">';
echo '<div class="pics">';
echo '<img style="width:200px;" src="Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/'.$pic.'"><br>';
echo '<hr>';
echo '</div>';
}
Which results in a page full of the records, a checkbox and the relating image.
I wish to only show these images when the checkbox is checked but cannot find a solution, i have tried many jquery scripts, to no avail.
The images will then populate the next page as a pdf to be printed.
I am hoping not to have to grab the checkbox's values as an array to then use the get method with 100's of if statements but cant see another way ?
The jquery ive used.
$(document).ready(function () {
$('.pics').hide();
$('.check').click(function () {
$('pics').show;
});
$('.pics').hide;
});
and
$(function() {
$(".check").click(function(e) {
e.preventDefault();
$('.pics').hide();
$('.pics').show();
});
});
Plus many similar alternatives.
Is there something obvious i am missing ?
Query to filemaker method;
I have changed the path field to a calculated value which works great, thank you, although with 1000's of records, i would need lots of php code to echo the checkbox's to the website and lots more to be able to edit them from the website.
I have done this previously with the value held within the checkbox in filemaker.
$sesame = $print->getField('Allergens::Allergens[11]'); if ($sesame == "Sesame") { $sesame = "checked" ;} else if ($sesame !== "Sesame") {$sesame = "" ;}
This displays the checkbox synced with filemaker.
if ($_POST['Sesame'] == 'Sesame'){ $a_sesame = 'Sesame';} else { $a_sesame = 'No Sesame'; }
This is sent as a variable to my script.
if($a_sesame == "Sesame"){$contains_sesame = "Yes";} else { $contains_sesame = "No";}
This grabs the new value from the form.
Which all work great, but then i am writing a script in filemaker too to enable the to and from of the different names for each checkbox state.
which is for this part 120 lines long, this is a sample which i have to repeat for each repetition of this field.
Set Variable [ $sesame; Value:GetValue ( Get ( ScriptParameter ) ; 11 ) ]
If [ $sesame = "Sesame" ]
Set Field [ Allergens::Allergens[11]; "Sesame" ] Commit Records/Requests
[ Skip data entry validation; No dialog ]
Else If [ $sesame = "No Sesame" ]
Clear [ Allergens::Allergens[11] ] [ Select ]
Commit Records/Requests
[ Skip data entry validation; No dialog ]
Refresh Window
[ Flush cached join results; Flush cached external data ]
End If
This would be far too large to write for so many records, just for these 14 fields used 120 in filemaker and 400 plus in the php.

I am not 100% sure what you are trying to do but this should work. First add an extra div that closes input and div pics like below.
foreach($result->getRecords() as $record){
$id = $record->getField('Record_ID_PHP');
$name = $record->getField('DB_Name');
$pic = $record->getField('Photo_Path');
echo <<<TEXT
'{$id}'<br>
{$name}<br>
<div>
<input type='checkbox' class='check' value='Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/{$pic}'>
<div class='pics'>
<img style='width: 200px;' src='Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/{$pic}'><br>
<hr>
</div>
</div>
TEXT;
}
then change your java to this
$(document).ready(function() {
$(".pics").hide();
$(".check").click(function() {
$(this).siblings().toggle();
});
});
well I hope this helps

Another alternative would be to set up a simple calculated container field in FileMaker, with a calculated value of:
If ( checkbox; imageField )
This would only pass the image when the checkbox was ticked for a record. This should be faster than handling this in JavaScript, since you'd be limiting the number of images being sent over the wire.
Note: For performance, you might try this with this calculated container field stored and unstored. I suspect stored v unstored should make little difference, in which case I'd suggest leaving this unstored to minimize disk space consumed.

You can use the toggle()function:
$(function() {
$('.pics').hide();
$(".check").is(':checked',function(e) {
e.preventDefault();
$('.pics').toggle();
});
});

Related

Get value from jQuery editor to PHP

I'm using this jquery plugin to create a wysiwyg text editor,
I created a textarea in PHP where:
<textarea name="body" id="body"><?php echo $body?></textarea>
and
<script type="text/javascript">
$(document).ready( function() {
$("#body").Editor();
});
</script>
Now i need to get value of this area for send it to SQL
if (isset($_POST['add-article'])) {
unset($_POST['add-article']);
$_POST['user_id'] = $_SESSION['id'];
$_POST['username'] = htmlentities($_SESSION['username']);
$_POST['published'] = isset($_POST['published']) ? 1 : 0;
// I need this line
$_POST['body'] = htmlentities($_POST['body']);
When I put text into this editor, it doesn't enter (value) into the textarea.
I have to have value before I press the add-article button, beacuse now it gives me an empty text.
I found something like this
function displayText(){
alert($("#body").Editor("getText"));
}
This causes it to return text ( i think only display by JS ) but i completely dont know how to use in my PHP scripts.
Second thing is when i write article and make a mistake something like ( Article title already exist ) ( in one session ) text in textarea stayed, but now doesn`t work it.
I think about if there is an error for example "Title already exist" follows:
} else {
$title = $_POST['title'];
$body = $_POST['body'];
$category_id = $_POST['category_id'];
$published = isset($_POST['published']) ? 1 : 0;
}
In my honest opinion i need something like:
add-article.addEventListener('click', function {
$body (from PHP) = alert($("#body").Editor("getText"))(from JS);
}
Thank you in advance for help.
On the plugin page you referenced, I see this is one of the recommendations. Capture the value you want when the click button is pressed, before the form submits.
Add a script to your form submit to put the texteditor content into this element
<form onsubmit='return getItReady()'>
Add an element to the form you'll use as a proxy element and keep it hidden, something like
<textarea id='txtEditorContent' name='txtEditorContent' style='visibility:hidden;height:0px' tabindex="-1"></textarea>
Then add the script to prepare it
<script>
function getItReady() {
console.log('The content:', $('#body').Editor("getText"));
$('#txtEditorContent').val($('#body').Editor("getText"));
return true;
}
</script>
Then in your PHP, it will come through as $_POST['txtEditorContent'].

passing primary key instead of attribute on submit

I have an input tag that takes a users input that calls an AJAX dynamically outputs suggestions from my database. The issue is I want to store the primary key associated with that attribute.
I have figured out a way set it to the primary key when the user selects a value; however I would rather only have the attribute displayed on the front end. Essentially what I was thinking about doing was using the option tag and setting the value to the primary key, but after reading the documentation for it, that doesnt look like it would work.
HTML:
<input type="text" id = "zip_id" class="tftextinput2" autocomplete = "off" name="zip" placeholder="Zip Code" onkeyup = "autocompleter()">
<ul id = "zip_codes_list_id"></ul>
JS:
function autocompleter()
{
var min_length = 1; // min caracters to display the autocomplete
var keyword = $('#zip_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#zip_codes_list_id').show();
$('#zip_codes_list_id').html(data);
}
});
} else {
$('#zip_codes_list_id').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item)
{
// change input value
$('#zip_id').val(item);
// hide proposition list
$('#zip_codes_list_id').hide();
}
PHP:
<?php
//connect to db here
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM zip_codes WHERE zip LIKE (:keyword) ORDER BY zip_codes_id ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs)
{
// put in bold the written text
$zip = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['zip']);
// add new option
// echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['zip']).'\')">'.$zip.'</li>'; (this one only passes the attribute)
echo '<li " onclick="set_item(\''.str_replace("'", "\'", $rs['zip_codes_id']).'\')">'.$zip.'</li>';
//this one passes the attribute but changes the displayed value to the primary key.
}
?>
As you can see from the PHP file, what I am trying to do is pass in the primary key value but keep the displayed value the attribute. I am not sure how to do that. Should I be using the UL tag?
The issue in your code is that you try to the zip_id value for the input, but this input contains the zip field value - I assume it's the textual representation. There are a few ways how you could save the zip_id on the frontend - either store it in the model (if you're using some MVC framework, but I gues it's not the case) or simply add a hidden input field:
<input type="hidden" id="actual_zip_id" name="zip_id">
And
function set_item(item)
{
// change input value
$('#actual_zip_id').val(item);
// hide proposition list
$('#zip_codes_list_id').hide();
}
UPD
Speakng about the entire idea of autocompleting zip codes, it looks pretty nasty, as pointed by Darren Gourley (check the comments).
So you'd rather validate it with regex first, and then do your db-related logic like that:
$('#zip_id').on('change', function(){
// your stuff
})
Best regards, Alexander

how to dynamically render multiple form elements using for loop

i want to display a certain number of input tags for a form; this should depend on how many items a user dynamically selects that they want.
for example, if a user says they want 3 items. i want to display 3 input bars.
i am not clear of the best way to proceed with this. for example, i am able to determine how many items they select from the select options:
$(".howmany").change(function(){
var value = $(this).val();
}
but what is the correct way to proceed thereafter; do i dynamically render the exact number of input tags selected using a for each: or pre-display (but hide) all of the input tags and only show the exact number of input tags requested.
i would appreciate an example of how its been done . at the moment i am only able to hide the entire area. eg:
var requests = $("#howmany").val();
if (reqeusts < 1){
$('#reqeusts').hide();
}
else {
$('#reqeusts').show();
}
but i obviously need to be able to show individual form tags accordingly to the number the user selected.
hi again, i want to thank everyone for their answers.
i deeply sorry, but i forgot to mention that the reason for the confusion is that the values for the imput are dynamically fed from an array function.
public function arrayValues()
{
return $selection = array(
'0' => 'none' ,' 1' => '1 item' ,' 2' => '2 item' ,' 3' =>' 3 item' );
}
i then need to render one of the below imput select tags for each number of items selected.
<?php echo '
<select id="howmany" name="items[howmany]" />';
foreach ($arrayValues as $key => $value)
{
echo '<option value="' . $key .'">' . $value . '</option>';
}
echo'</select>';
?>
$(".howmany").change(function(){
var value = $(this).val(); // get the number of inputs
value = parseInt(value); // make sure it's an integer
htmlStr = "";
for (var i = 0; i < value; i++)
{
htmlStr += "Label " + i +" <input type='text'>";
}
$('.container').empty();
$('.container').append(htmlStr);
}
You need something like this:
$('button').click(function () {
$('div').empty().append(new Array(+$('input[type=number]').val()+1)
.join("<input type='text' placeholder='Type Something'/>"));
});
I hope this gives you an idea of how to solve your problem.
DEMO

onClick value + restartCode

<input type="button" onclick="restartBattle('Battle=Trainer&BattleID=294','nFOgYlQGjn')" value="Restart Battle" style="width:160px;">
That is the coding of the button. Unless the restart code is entered as well (it's dynamic, changes every refresh), I can't click the button with the methods of Javascript or jQuery that I've tried.
'nFOgYlQGjn' is the restartCode. I've tried this coding to click the button, but it won't work.
var btn = document.querySelector('input[value="Restart Battle"]');
if (btn) {
var x = Math.round((Math.random() * 90) + 663);
var y = Math.round((Math.random() * 15) + 589);
function restartBattle(url, restartCode) {
$('#battleContent').html('Loading...<br /><br />');
$('#battle').load('http://tpkrpg.net/core/battles/battle.php?'+url+'&RestartCode='+restartCode);
}
//btn.click();
}
This should work, since I took the function restartBattle part out of the source code, but it still won't work. Any ideas?
Pass the data as an object to the script. You could use on('click', method here) or click(method here) on the id of the input tag. Make sure jquery is included too.
button:
<input type="button" value="Restart Battle" id="restart" />
css:
#restart
{
width:160px;
}
jQuery:
/* sample how to get the values as variables
method one, static hard coded
var battleType = "Training";
var battleId = 294;
var restartCode = "nFOgYlQGjn";
method 2, php set via echo, requires page to be created by php, example uses theoretical data returned from a database stored as an associative array but could be changed for variables
var battleType = <?php echo $battle['training']; ?>;
var battleId = <?php echo $battle['id']; ?>;
var restartCode = <?php echo $battle['restart_code']; ?>;
*/
function restartBattle( varz )
{
$("#battleContent").html("Loading...<br /><br />");
$("#battle").load("http://tpkrpg.net/core/battles/battle.php", {Battle : varz.data.type, BattleId : varz.data.id, RestartCode : varz.data.code});
}
// handle the click of the button and execute functon with passed data.
$("#restart").on("click", { type : "Training", id : 294, code : "nFOgYlQGjn" }, restartBattle);
Your php code needs to check for this data being passed to it so it can return the data either some json, html, or plain text using echo.
battle.php:
$restartCode = ( ( isset( $_REQUEST['RestartCode'] ) ) ? $_REQUEST['RestartCode'] : false );
if( !$restartCode ) echo "Error : No restart code!";
That is a start, but you need to create variables that hold the data being sent to the php script or else it's hard coded to those values.
See method API

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.

Categories

Resources