I have been working on this for some time now. I have a php file that has a div which reads a directory and loads the files in the directory into a dropdown. When the user selects from the file the file gets selected and teh operation is performed. However, the file name does not disappear from the dropdown until the page is refreshed. I have tried '.load' and it doesn't work. As in, the content of the div does not get updated.
My code is as follows:
This is the PHP file:
<div id="mgA" class="form-group">
<label>Management Address:</label>
<?php
$path = "/licenses/ve/address/unused";
clearstatcache();
$files = array();
$handle = opendir($path);
echo '<select required id="mgmtAdd" class="form-control select2" style="width: 100%;">';
while ($file = readdir($handle)) {
if (substr($file,0,1) != ".") {
$files[]=$file;
}
echo "<option selected = 'selected' value='0'>Select</option>";
natsort($files); //sorting
foreach($files as $file){
echo "<option value ='$file'>$file</option>";
}
echo '</select>';
if (is_dir_empty($path)) {
echo "Max no of hosts already created";
}
function is_dir_empty($path) {
if (!is_readable($path)) return NULL;
return (count(scandir($path)) == 2);
}
closedir($handle);?>
This is the button which on click the div should reload all the contents again:
$( "#vServer").on( "click", function(e) {
e.preventDefault();
$("#mgA").load(virtualDialog);
alert("refreshed");
virtualDialog.dialog( "open" );
});
Please let me know if anyone has any idea, any help is appreciated! Thank you!
As epascarillo has pointed out, you are using load() incorrectly. This may be more in line with what you wish to do but I did not test (or even check very closely) your PHP code.
I am also assuming that the div #mgA is the content of the jQueryUI dialog that you are opening with virtualDialog.
javascript/jQuery:
$( "#vServer").on( "click", function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'ajax-reload.php',
success: function(d){
$("#mgA").html(d);
virtualDialog.dialog( "open" );
}
});
});
ajax-reload.php
<?php
$path = "/licenses/ve/address/unused";
clearstatcache();
$files = array();
$handle = opendir($path);
$out = '<select required id="mgmtAdd" class="form-control select2" style="width: 100%;">';
while ($file = readdir($handle)) {
if (substr($file,0,1) != ".") {
$files[]=$file;
}
$out .= "<option selected = 'selected' value='0'>Select</option>";
natsort($files); //sorting
foreach($files as $file){
echo "<option value ='$file'>$file</option>";
}
} //<=== this brace was missing
$out .= '</select>';
if (is_dir_empty($path)) {
$out = "Max no of hosts already created";
}
function is_dir_empty($path) {
if (!is_readable($path)) return NULL;
return (count(scandir($path)) == 2);
}
closedir($handle);
echo $out;
?>
See these additional examples of simple AJAX -- sometimes it helps to see the really simple examples:
AJAX request callback using jQuery
Related
this is my first time on this site so I'll cut to chase.
I've been working on a fixed assets control web system using PHP, AJAX, jquery and MySQL as database (the project structure was made by following the tutorial from this website: https://www.itechempires.com/2016/07/pdo-crud-operations-using-php-bootstrap/ ), where such items are registered along with the categories to which each asset belongs, the transactions made by the users within the company and the reports generated by each transaction.
Currently I'm stuck with the dropdowns since I tried anything I could to make them work but without the results I've been looking for, which is:
in a modal there's a form where an asset is going to be added with its related information, two of those details are categories and subcategories which are handled by dependent dropdowns, the dropdown regarding to subcategories will be displayed once a category is selected.
The code snippets will be up for review which will be focused on the ones related to the dropdowns:
Tables
grupo (group or category)
id_grp (group id,autoincremented, not visible by the user)
codigo_grp (code)
nombre_grp (name)
subgeupo (subgroup or subcategory)
id_sgrp (subgroup id, autoincremented, not visible by the user)
codigo_sgrp (code)
nombre_sgrp (name)
vidaUtil_sgrp (useful life)
id_grp (group id, foreign key)
libAF.php: Contains all queries for crud operations
/*
* Get group's id and name
*
* #return $id_grp, $nombre_grp
* */
public function populateSelGrp()
{
$query = $this->db->prepare("SELECT id_grp, nombre_grp FROM grupo");
$query->execute();
$data = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
return $data;
}
/*
* Get sub-group's id and name
*
* #return $id_grp, $nombre_grp
* */
public function populateSelSgrp($id_grp)
{
$query = $this->db->prepare("SELECT * FROM subgrupo WHERE id_grp = :id_grp");
$query->bindParam("id_grp", $id_grp, PDO::PARAM_STR);
$query->execute();
$data = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
return $data;
}
populateSelGrp.php: loads the categories on to the parent dropdown
<?php
require 'libAF.php';
$data = "";
$object = new CRUD();
$grupos = $object->populateSelGrp();
$data .= '<select id="select_grp" class="form-control" onchange="populateSelSgrp()">';
$data .= '<option value="0" disabled selected>Escoja grupo</option>';
if (count($grupos) > 0) {
foreach ($grupos as $grupo) {
$data .= '<option id="selected_grp" value="' . $grupo['id_grp'] . '"> ' . $grupo['nombre_grp'] . '</option>';
}
}
else
{
$data .= '<option>No hay opciones disponibles</option>';
}
$data .= '</select>';
echo $data;
?>
populateSelSgrp.php: loads the subcategories on to the child dropdown
<?php
require 'libAF.php';
if (isset($_POST['id_grp']) && isset($_POST['id_grp']) != "") {
$id_grp = $_POST['id_grp'];
$data = "";
$object = new CRUD();
$subgrupos = $object->populateSelSgrp($id_grp);
$data .= '<label for="select_sgrp">Sub-grupo</label>';
$data .= '<select id="select_sgrp" class="form-control">';
$data .= '<option value="0" disabled selected>Escoja sub-grupo</option>';
if (count($subgrupos) > 0) {
foreach ($subgrupos as $subgrupo) {
$data .= '<option value="' . $subgrupo['id_sgrp'] . '"> ' . $subgrupo['nombre_sgrp'] . '</option>';
}
}
else
{
$data .= '<option>No hay opciones disponibles</option>';
}
$data .= '</select>';
echo $data;
}
?>
scptAF.js: Contains the scripts needed to make the inputs work
function populateSelGrp(){
$.get("ajax/activoFijo/populateSelGrp.php", {
},
function (data, status) {
//load options to dropdown list
$(".option_grp").html(data);
}
);
}
function populateSelSgrp(id_grp){
$.ajax({
url: "ajax/activoFijo/populateSelSgrp.php",
method: "POST",
data:{id_grp: id_grp},
success:function(data){
$(".option_sgrp").html(data);
}
})
}
activos.php (assets): visible page where the user adds, removes or updates an asset.
<div class="form-group">
<label for="select_grp">Grupo</label>
<div class="option_grp"></div>
</div>
<div class="form-group">
<div class="option_sgrp"></div>
</div>
I finally found a solution for this mess, was a little code I had to add to the javaScript file to send the id to the second dropdown. Although I finally fixed my problem, I'd like to see other suggestions on how to tackle this problem.
Here's my snippet
scptAF.js
function populateSelGrp() {
$.get("ajax/activoFijo/populateSelGrp.php", {
},
function (data, status) {
//load options to dropdown list
$(".option_grp").html(data);
}
);
}
function changeGrpId(){
var id_grp = document.getElementById("select_grp").value;
populateSelSgrp(id_grp);
}
function populateSelSgrp(id_grp) {
$.ajax({
url: "ajax/activoFijo/populateSelSgrp.php",
method: "POST",
data:{id_grp: id_grp},
success:function(data){
$(".option_sgrp").html(data);
}
})
}
I'm not a php-hero so, I try to hidden a section if the user not come from a specific country.
So I did this:
$.get("http://ipinfo.io", function (response) {
$("#country").html(response.country);
}, "jsonp");
<input hidden id="country" type="text" name="country" value="">
This work well and show me the country code (eg. IT).
Now I try to get this value and insert in a IF
$country = $_GET['country'];
$it = "IT";
<?php if ($country != $it): ?>
Code to hidden here...
<?php endif; ?>
What is it wrong here?
Change
$("#country").html(response.country);
to
$("#country").val(response.country);
Because php $_GET saves values.
Also I do not see a reason to do this:
$it = "IT";
<?php if ($country != $it): ?>
You can just do
<?php if ($country != "IT"): ?>
And last but not least you should not access $_GET directly. It is better to use function filter_input which in your case would be filter_input(INPUT_GET, 'country')
EDIT
I do not understand what is the hidden input for. But if you want to show or hide content depending on the country, and you get the country using ajax there is absolutely no need for this input.
Instead of making php condition (<?php if ($country != "IT")...) You can do it in js. Let's say that inside your condition there is a div with class content
Solution
Your html would look more or less like this
<div class="content">
<!-- Your content here -->
</div>
instead of php condition.
And in js you can do something like this
$.get("http://ipinfo.io", function (response) {
if (response.country == "IT") {
$(".content").hide();
}
}, "jsonp");
So what do we do here?
We check if country code equals "IT". If it is true we hide the content. And this is the same what you were doing in php (if country different than IT show content).
EDIT 2
Instead of hiding the div you can remove it
$(".content").remove();
Try hiding via javascript, ajax can run PHP scripts and bring it back into the DOM but you're better off using JS if you don't need a backendscript
$.get("http://ipinfo.io", function (response) {
var country = $("#country").html(response.country);
if(country != "IT"){ document.getElementByID("country").display = "none";
}, "jsonp");
<input hidden id="country" type="text" name="country" value="">
I use the ProcessWise cms, that have their own API. So this answer work only with the ProcessWise cms. ( the best one ;) )
<?PHP
function getUserIP()
{
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
$user_ip = getUserIP();
echo "ip: " . $user_ip . "<br />";
$http = new WireHttp();
$url = "http://ipinfo.io/{$user_ip}/country";
$response = $http->get($url, ['country' => '']);
echo "Country: " . $response . "<br />";
echo "Successful response: " . $sanitizer->entities($response) . "<br />";
?>
I have the idea of what i wanted but need assistance on how to get it done.Below is the scenerio: I have a two dropdwon. The First dropdown is fetched from the DB, which works fine. At the change event of the first dropdown,the system should go to the Database, and fetch the result into the next dropdown. see what I have done so far for assistance:
JQUERY SECTION
<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#locate").change(function(){
var selectedloc = $("#locate option:selected").val();
$.ajax({type: "POST",url:"process-loc.php",data:{loca:selectedloc}}).done(function(data){
var ans=jQuery.parse(data);
//using php-mysql before
var ps = ans.res;
$("#subloc").html(ps);
});
});
});
</script>
FrontEnd(HTML)
<tr>
<th>Primary Location:</th>
<?php
$result = mysqli_query($connection,"SELECT * FROM tab_location");?>
<td>
<select name="locate" class="form-control" id="locate">
<option>Select Main Location</option>
<?php while($rw = mysqli_fetch_array($result)){ ?>
<option value="<?php echo $rw['location_name'];?>"><?php echo $rw['location_name'];?></option>
<?php };?>
</select>
</td>
</tr>
<tr>
<th>Sub Location:</th>
<td id="subloc"></td>
</tr>
Process-loc.php
if(isset($_POST["loca"])){
include 'includes/session.php';
include 'includes/db_connection.php';
include 'includes/functions.php';
$main = $_POST["loca"];
$gets = "SELECT * FROM tab_fltlocation WHERE mainloc='".$main."'";
$get = mysqli_query($connection,$gets);
$gt = mysqli_fetch_array($get);
//$nos= $gt['opsNo'];
if(mysqli_num_rows($get)>=0)
{
echo json_encode(array("res"=>$gt));//or do a dropdown using <select name='subloc'><option value=$gt['loc']>$gt['loc']</option></select>
}else{
echo json_encode(array("res"=>"0"));
}
}
?>
This is what I wants to be displayed on the Front End page for the use:
$gt['loc']
How can I achieve this.
$query = "
SELECT
tariff_name
FROM tariff_setting";
$result = mysqli_query($this->_connection, $query);
while ($row = mysqli_fetch_assoc($result))
$response[] = $row['tariff_name'];
}
$tarrifList = json_encode($response);
// $tarrifList is the response and sent it in json encode format and decode on ajax success
// Javascript Process
var obj = JSON.parse(resdata);
var areaOption = "<option value=''>Select State</option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#patientSelectState").html(areaOption);
You can change your AJAX processor to do this:
Process-loc.php
/* Above code the same */
if(mysqli_num_rows($get)>=0) {
$out = '<select id="selSubLoc"><option value="">Choose One:</option>';
foreach($gt AS $loc){
$seld = ($_POST['loca'] == $loc) ' selected' ? : '' ;
$out .= '<option value="' .$loc. '" ' .$seld. '>' .$loc. '</option>';
}
$out .= '</select>';
}else{
$out = 0;
}
echo $out;
And change your front-end code's AJAX routine to be like this:
$.ajax({
type: "POST",
url:"process-loc.php",
data:{loca:selectedloc}
}).done(function(recd){
$("#subloc").html(recd);
});
The data received back from PHP will be in HTML format unless you use dataType: to change it, so you can build the HTML over on the PHP side and then just plop it into the #subloc table cell.
On the event of the first box call the function containing the ajax which would retrieve information from the database. This ajax call will get data according to the first input.
Now query your database and echo the results in a foreach loop(you can make a tag there only).
In the ajax 'success:' catch the data and display it.
//from the database
foreach ($info as $product)
{
echo "<option value=".$product['childsticker_id'].">".$product['name']</option>";
}
//ajax call page
success: function(result)
{
$("#states").html(result);
}
http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html
I have a JQuery script that submits user input to a PHP script in the same file, and then displays the result of what the PHP script does with the input. That part works fine. The issue that I’m having is that, upon submission, the JQuery script (at least, I think it's the script) also generates a new submission box below the original.
I’m not sure why. I thought at first that it was an issue with the input type, with the asynchronous part, or even with where I had the form in the overall code, but none of those seem to be playing any role. I'm still a beginner and I'm just not seeing the issue.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<form id = "my_form">
verb <input type = "text" id ="word1"/>
<input type = "submit"/></form>
<div id="name"></div>
<script>
$(document).ready(function(){
$("#my_form").on('submit', function(e)
{
e.preventDefault();
var verb = $ ("#word1").val();
var tag = "#Latin ";
var url = "http://en.wiktionary.org/wiki/"+verb+tag;
$.ajax({
url: "Parser.php",
data: {"verb": verb},
type: "POST",
async: true,
success: function(result){
$("#name").html(result);
$("#name").append(url);
}
});
});
});</script>
RESULT:
PHP
<?php
$bank = array();
function endsWith($haystack, $needle) {
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}
function check_end_array($str, $ends)
{
foreach ($ends as $try) {
if (substr($str, -1*strlen($try))===$try) return $try;
}
return false;
}
function db_connect() {
static $connection;
if(!isset($connection)) {
$connection = mysqli_connect('127.0.0.1','username','password','Verb_Bank');
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
}
function db_quote($value) {
$connection = db_connect();
return "'" . mysqli_real_escape_string($connection,$value) . "'";
}
$y = false;
if (isset($_POST['verb'])){
$y=db_quote($_POST['verb']);
echo $y;
echo "\n";
$m = db_query("SELECT `conjugation` FROM normal_verbs WHERE (" . $y . ") LIKE CONCAT('%',root,'%')");
if($m !== false) {
$rows = array();
while ($row = mysqli_fetch_assoc($m)) {
$rows[] = $row;
}
}
foreach ($rows as $key => $value){
if (in_array("first",$value)==true){
echo "first conjugation verb\n";}
$y = $_POST["verb"];
$x = $y;
foreach ($bank as $key => $value)
(series of IF-statements)
}}?>
As Roamer-1888 says's the problem lies in server side, you are returning a html which has a input too. You need to change your code to return only the result string which you append to the div. Else if this is not possible doing at server side as it might require you to change lot of code, then you can strip off the input element from the result and then append it to the div. Like below.
success: function(result){
var div = document.createElement('div');
div.innerHTML = result;
$(div).find('input').remove();
$("#name").html(div.innerHTML);
$("#name").append(url);
}
I have a javascript dropdown on website, here is the code-
<?php
function get_request_uri_without_page() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
$request = explode('/page/',$pageURL);
$request = explode('?', $request[0]);
return $request[0];
}
?>
<form action="<?php echo get_request_uri_without_page(); ?>" method="get" id="catselect" class="form-archive-140">
<!-- DROP DOWN HERE -->
<?php global $jtCatId; $jtCatId = true; wp_dropdown_categories('show_count=1&hierarchical=1&child_of=140&class=selectmenu&id=cat&show_option_none=Please Choose...'); ?>
<script type="text/javascript">
<!--
var dropdown = document.getElementById("cat");
function onCatChange() {
if ( dropdown.options[dropdown.selectedIndex].value > 0 ) {
location.href = "<?php echo get_request_uri_without_page(); ?>?cat="+dropdown.options[dropdown.selectedIndex].value;
}
}
dropdown.onchange = onCatChange;
-->
</script>
The output of this dropdown is a list of posts filtered by location, however the URL structure is as follows-
thewebsite/themaincategory?cat=141
I would like to replace the category id at the end with the category name, when I replace dropdown.selectedIndex to "text" the dropdown does not work, it doesn't give an error it just doesn't do anything.
Do I need to do a rewrite in the htaccess or is their a way to get the above code working.
I would like to apologise in advance if this is a stupid question, I am new to javascript and just trying to find my way.
Here is a working example of the above mentioned-
http://www.theweddingdirectory.co.za/professional-wedding-photographers
try something like this
var cat= document.getElementById("cat");
var text = cat.options[cat.selectedIndex].text;
EDITED CODE
function onCatChange() {
if ( dropdown.options[dropdown.selectedIndex].value > 0 ) {
location.href = "<?php echo get_request_uri_without_page(); ?>?cat="+dropdown.options[dropdown.selectedIndex].text.trim();
}
}