What I want to be able to is on button click I want to check a Server-Side directory for the existence of certain files.
If they exist I wish to display a checkbox corresponding to that file.
So far I have managed to use PHP and AJAX to check if the files exist or not and write to and array: 1 if the file exists, and a 0 if not.
Now...what I need to do at this stage is call upon this array, from my PHP file, or write this array to a div on my main HTML page. However when I go to echo it navigates away from my Main.html, opening a new page and writing on that.
Big question is can I write the array on my main html page from my PHP_Function.php file.
I have the following HTML code:
<form action="PHP_Function.php">
<input type="submit" class="learnButton" name="insert" value="Find Available Evidence" />
</form>
<form action="available_evidence">
<input type="checkbox" name="vehicle" value="Bike"> Facebook<br>
<input type="checkbox" name="vehicle" value="Car" checked> Facebook Messenger<br>
<input type="checkbox" name="vehicle" value="Bike"> Twitter<br>
</form>
With the following array within PHP_function.php file:
if(in_array("Facebook.xml", $dirArray)){
$IfPresentArray[0]="1";
}else {
$IfPresentArray[0]="0";
}
foreach ($IfPresentArray as $value) {
echo "$value<br />\n";
}
I am very new to PHP and HTML, and I have been banging my head off the wall with this for a while now.
Any help would be greatly appreciated.
You are using AJAX so all your communication will need to go back and forth over that medium. In brief, your PHP script (the one called by ajax) will echo JSON values (typically created by json_encode($myarray)) and this will then be available to your javascript over on your client-side.
A quick google for "jquery ajax json example" should get you some good, helpful ideas of how it fits together.
Here's the client-side from one of those google links above - note the .done part
<script type="text/javascript">
$(document).ready(function(){
$(':submit').on('click', function() { // This event fires when a button is clicked
var button = $(this).val();
$.ajax({ // ajax call starts
url: 'serverside.php', // JQuery loads serverside.php
data: 'button=' + $(this).val(), // Send value of the clicked button
dataType: 'json', // Choosing a JSON datatype
})
.done(function(data) { // Variable data contains the data we get from serverside
$('#wines').html(''); // Clear #wines div
if (button == 'all') { // If clicked buttons value is all, we post every wine
for (var i in data.red) {
$('#wines').append('Red wine: ' + data.red[i] + '<br/>');
}
for (var i in data.white) {
$('#wines').append('White wine: ' + data.white[i] + '<br/>');
}
}
else if (button == 'red') { // If clicked buttons value is red, we post only red wines
for (var i in data) {
$('#wines').append('Red wine: ' + data[i] + '<br/>');
}
}
else if (button == 'white') { // If clicked buttons value is white, we post only white wines
for (var i in data) {
$('#wines').append('White wine: ' + data[i] + '<br/>');
}
}
});
return false; // keeps the page from not refreshing
});
});
</script>
You can store your array inside a $_SESSION variable, but you'll have to use a session_start(); on both pages.
On your php page, use: $_SESSION['array'] = $array; and then on your main page retrieve the array by the inverse: $array = $_SESSION['array'];.
You can now use said array on your main page.
To retrieve a specific value: $value1 = $_SESSION['array'][0];
For further reference:
Array as session variable
Related
Im pretty new with javascript programming.
I have some .php code, where 2 dropdown lists (in the same FORM) are populated by 2 different mysqli queries, this works without any problem.
Im trying to get javascript to handle the selected parts of the dropdown lists, with onchange, this works for only one dropdown list, and i cant really figure out how to get around this one.
This is the code that works with one dropdown menu, and it updates automaticly the page without submitting:
$chosen_location = $_GET['Lid'];
$chosen_car = $_GET['Cid'];
?>
<script type="text/javascript">
function changeDropDown(dropdown){
var location = dropdown.options[dropdown.selectedIndex].value;
*var car = dropdown.options[dropdown.selectedIndex].value;*
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}
</script>
Part of the .php code:
<select size="1" name="form_location_id" id="form_location_id" onchange='changeDropDown(this);'>
<option value = <?php echo ($location_id) ?> selected><?php echo ($location_name) ?></option>
<select size="1" name="form_car" id="form_car" onchange='changeDropDown(this);'>
<option value = <?php echo ($car_type_id) ?>><?php echo "" . ($car_class) . " - " . ($car_manufacturer) . " - " . ($car) . "" ?></option>
The italic marked I know will not catch the correct value, but this is where im at right now...
How is it possible to get an action URL with both selected values ? as this is going to be used in a mysqli query to show data from the actual selection
Thanks in advance... :)
Currently, you are submitting the form through JavaScript. If the selects are inside the form, their values will automatically be submitted when you submit the form. You don't even have to change the action of the form.
So, you can just generate a normal form (including submit button, if you will), and it will work. Then, add a little JavaScript sauce to make it submit automatically.
The code below does just that. JavaScripts adds a class to the body. This is a way to easily change styling based on JavaScript being enabled or not. In this case, I use it to hide the submit button, which is only needed in a non-JavaScript situation.
Then, I bind the on change handler, not unlike yours, to submit the form when a value is selected. By giving the selects a proper name, their values will automatically be added as intended.
Note how the event handlers are bound through code. You don't have to hardcode any calls to JavaScript in the HTML, so you can keep the HTML clean and separate (readability!).
// Bind to load event of the window. Alternatively, put the script at the end of the document.
window.addEventListener("load", function() {
// Indicate that JavaScript works. You can use this to style the document, for instance
// hide the submit button, if the form is automatically submitted on change..
document.body.classList.add("js");
// With JavaScript, you can automatically submit the form, but you still don't have to modify it.
var theform = document.getElementById("theform");
var selects = document.querySelectorAll("#theform select");
for (var i = 0; i < selects.length; ++i) {
selects[i].addEventListener("change",
function() {
alert("submitting now");
theform.submit();
});
}
});
.js button[type="submit"] {
display: none;
}
<!-- Just a form with selects is enough. You don't even have to have JavaScript to post this. -->
<form id="theform" action="test.php" method="get">
<select name="Lid">
<option>Example...</option>
<option>Use PHP,</option>
<option>to fill these.</option>
</select>
<select name="Cid">....</select>
<button type="submit">Post</button>
</form>
You can update your code to following
function changeDropDown(){
var elLocation = document.getElementById('form_location_id');
var elCar = document.getElementById('form_car');
var location = elLocation.options[elLocation.selectedIndex].value;
var car = elCar.options[elCar.selectedIndex].value;
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}
try to do this
<script>
// get select elements
var form_location_id = document.getElementById('form_location_id');
var form_car = document.getElementById('form_car');
// on change
form_location_id.addEventListener('change', changeDropDown1);
form_car.addEventListener('change', changeDropDown2);
</script>
And change the 'changeDropDown1' and 'changeDropDown2' to your handler function
try this
<script type="text/JavaScript">
var dropdownLocation = document.getElementById("form_location_id");
var dropdownCar = document.getElementById("form_car");
function changeDropDown() {
var location = dropdownLocation.options[dropdownLocation.selectedIndex].value;
var car = dropdownCar.options[dropdownCar.selectedIndex].value;
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}
</script>
dropdownLocation et dropdownCar are outside the function to save time because this 2 vars need only to be set one time
I have a file called bpSearch. Inside bpSearch, I have a MODAL window, called addNewModal. Within addNewModal, I have 2 INPUT fields called partnerName and partnerCode. I have a button that once clicked, opens into another MODAL window, called searchPartnerModal.
Here is the a portion of the FORM inside addNewModal:
<form action="bpSearch.php" method="get">
<input type="text" readonly id="partnerName" name="partnerName" />
<input type="text" readonly id="partnerCode" name="partnerCode" />
Go
</form>
When the user clicks GO, it opens searchPartnerModal.
searchPartnerModal is where the user will enter either a code or a name (doesn't have to be both). But upon hitting SEARCH, I use an AJAX call that returns JSON that I parse and eventually return in a UL field called pNames. We're still inside searchPartnerModal.
Here is the FORM inside searchPartnerModal:
<form action="bpSearch.php" method="get">
<input type="text" id="pNameSearch" name="pNameSearch" />
<input type="text" id="pCodeSearch" name="pCodeSearch" />
<input type="button" class="btn" id="pSearch" name="pSearch" value="search" />
</form>
When the user enters a name, I use jquery to send it over to a PHP script that will then return the data in a UL tag.
Here is the jquery that will search if the user enters a name:
$('#pSearch').on('click', function()
{
var partnername = $('#pNameSearch').val();
if($.trim(partnername) != '')
{
$.post('api/pNameSearch.php', {partnername: partnername}, function(data)
{
var obj = JSON.parse(data);
$('#pNames').empty();
var htmlToInsert = obj.map(function (item)
{
return '<li><a id="getPInfo" href="javascript:;"
onclick="getPInfo()" data-selname="'+item.FULL_NAME+'"
data-selcode="'+item.PARTNER_CODE+'">'
+ item.FULL_NAME + ' - '
+ item.PARTNER_CODE + '</a></li>';
}).join('');
$('#pNames').html(htmlToInsert);
});
};
});
With this code, I am able to send the name to search the database table for a valid name. The data is returned via JSON and is parsed and displayed inside the UL tag (called pNames) as LI tags, each with an A tag with their own data-attributes, called data-selname and data-selcode.
Now what I need to do is once the user clicks on one of the returned data links inside pNames, I need to send it back to the previous modal window, addNewModal.
This is where I'm stuck.
If you look inside the Jquery above, after I parsed the JSON, you will see that I created another Javascript function inside the A tag of each returned piece of data, called getPInfo().
Here is what I got so far for the function getPInfo() :
function getPInfo()
{
var selname = ($('#getPInfo').attr('data-selname'));
var selcode = ($('#getPInfo').attr('data-selcode'));
}
At this point, I can alert both variables (selname and selcode) and get them to display in an alert window.
What I want to do is send both of those variables back to addNewModal in the respective INPUT fields, called partnerName and partnerCode.
So selname will go to partnerName and selcode will go to partnerCode.
I didn't display the PHP script that returned the data.
Change the anchor id=getPInfo to class=getPInfo since you have multiple anchors. Next, handle the click event of the anchor and extract the data attributes and set the corresponding form elements in the addNewModal form. Following should work based on the markup i see so far.
$(function(){
$('body').on('click', 'a.getPInfo', function (e) {
var $a = $(e.srcElement || e.target);
$('#partnerName').val($a.attr('data-selname'));
$('#partnerCode').val($a.attr('data-selcode'));
$('#searchPartnerModal').modal('hide'); //assuming bootstrap modal
});
});
The news feed on the sites dashboard I'm working on has multiple items from different users; and can also be commented on. However, whenever you write a comment under each post, it only posts to the post at the top of the feed (the most recent one). Comments are posted instantly by pressing the enter key, which then runs this JS code which is on the index.php page.
$(function(){
$('#comment_body').live( 'keypress' , function (e) {
var boxVal = $(this).val();
var sendTo = $('#to_id').val();
if ( e.keyCode == '13' ) {
e.preventDefault();
$.post( 'instantcom.php' , { 'comment_body' : boxVal , 'activity_id' : sendTo } , function () {
// reload data or just leave blank
} );
$('#comment_body').val('');
}
} );
});
Then, the HTML for the comment box on each post is as follows:
<p align="center" style="height:45px;">
<input type="text" name="comment_body" id="comment_body" style="margin-top:12px;border:1px solid blue !important;width:329px;height:21px;" />
<span class=" glyphicons-icon camera" style="position:relative;bottom:50px;left:155px;"></span></p>
<input name="type" type="hidden" value="a" />
<input name="activity_id" id="to_id" type="hidden" value="' . $act_item_id . '" />
The ' . $act_item_id . ' is just a PHP variable which contains the unique ID of the status update.
So then, any ideas as to why comments are only posting to the most recent posts instead of the ones they're meant to post to?
You're using an id to identify which post you're commenting against? to_id right? Well, that's an id on the page, id's should be unique to the page.
I have a few radio buttons in a page and I need to save their values or whatever value is selected to a file.
Here is a sample code:
<input name="select" type="radio" value="a" />
<input name="select" type="radio" value="b" />
<input name="select" type="radio" value="c" />
<input name="select" type="radio" value="d" />
Whenever the user selects one I need it saved / appended into a file.
Possible?
UPDATE:
Tried this:
<script>
$(document).ready(function () {
$("input[name='select']").change(function(e) {
e.preventDefault();
$.post("zzz.html", { selectedValue : $(this).val() }, function(response) {
// do something with server response
alert('saved');
});
});
});
</script>
Result: No Result. Nothing created / Nothing Saved.
$("button").click(function(){
$.post('save_values.php', $("form").serialize(), function(){
alert('saved');
});
return false;
});
If you want to save the the text to a file on your server, then you can use php.
This example checks to see if a file name has been set, and the text to log has also been set.
It opens the file and appends text to it by specifying "a+".
So visiting
http://websitename.com/myfile.php?filename=test.txt&log=string to write
Will create and append the text to that file on your server.
If then you want to provide the textfile to the user to download you can just use
http://websitename.com/test.txt
This code is untested
<?php
if(isset($_GET["filename"]) == true && isset($_GET["log"]) == true){
$fp = fopen($_GET["filename"], "a+");
if($fp !== null){
fputs($fp, $_GET["log"] . "\r\n");
fclose($fp);
}
}
?>
jquery get method
$.get("myfile.php", { filename: "text.txt", log: "string to write" });
Assuming you want to save the selected value every time the radio group has been changed:
$("input[name='select']").change(function(e) {
e.preventDefault();
$.post("foo.html", { selectedValue : $(this).val() }, function(response) {
// do something with server response
});
});
If it is on server you can submit to a servlet and open a file and write on the file.
if it is in client side you can try using this jQuery plugin http://jquery.tiddlywiki.org/twFile.html and do that...
I'm using jQuery Multiple File Upload Plugin
and I have the following:
$(function(){ // wait for document to load
$('#attachFiles').MultiFile({
list: '#attList',
STRING: { remove: '<img src="cross.gif" title="Remove this attachment" border="0">' },
afterFileAppend: function(element, value, master_element) {
$(".amount").each(function(){
var i = $(this).attr("i");
var curVal = $("#attachment_" + i).val();
if($("#attachment_" + i).is(":checked") && curVal == "X") {
$("#attachment_" + i).attr("value", value);
$("#attachment_" + i).attr("title", "Attachment " + value + " linked");
aCounter++;
};
});
if(aCounter==0) {
alert("You need to select...");
//Remove should be here
}
}
});
});
If I add a file named test.pdf then one named test2.pdf my goal is to automatically remove test2.pdf if my aCounter variable is 0 (that would mean the user did not check off any additional check boxes named attachment_#.
I can't seem to figure out how to remove just the file that was added.
If I understand correctly, the value of the file that I add gets added to id="attachfiles" which is a
<input type="file" name="userfile[]" id="attachFiles" class="file" size="1" accept="pdf|jpg|jpeg">
So I'm assuming I should be able to somehow remove the most recently added item somehow.
Any assistance or guidance would be great.
The jQuery Multiple File plugins that I've used do NOT use some array to hold the set of files. They use a series of
<input type="file" ... style="position:absolute; left:-3000px;" />
<input type="file" ... style="position:absolute; left:-3000px;" />
elements that are hidden after the user selects a file. The displayed input element is replaced with a new one. This also seems to be the case with your plugin. You should be able to find the most recent file by doing some selector
$("#mydiv input[type='file']").last()
or something similar and removing it from the DOM.
You can probably also do a trigger('click') on the appropriate delete button.