I have a problem with the reservation module I developed in the last few months. You can have a look at it at the following address:
Taxi milan
Everything is working perfectly except for one issue. When I reduce the size of the browser window, I decided to make the image disappear and leave only the reservation module. When it is resized it stops working: all the script functions (the one providing the arrivals based on the departure selection and the "get price" button) do not work. Can you tell me what is causing the issue?
Below you can find the main parts of the code in which you may find the issue.
HOMEPAGE
<body>
<?php
$explode = explode('/', $_SERVER['REQUEST_URI']);
if($explode[1] == 'it' and $explode[2] == 'ros-ncc'){
?>
<div id="image">
<div id="modulemax">
<?php
require('wp-content/themes/customizr/prenota/index.php');
?>
</div>
</div>
<?php
}else if($explode[1] == '' and $explode[2] == ''){
?>
<div id="image">
<div id="modulemax">
<?php
require('wp-content/themes/customizr/book/index.php');
?>
</div>
</div>
<?php
} else {
}
?>
<div id="modulemin">
<?php
$explode = explode('/', $_SERVER['REQUEST_URI']);
if($explode[1] == 'it' and $explode[2] == 'ros-ncc'){
require('wp-content/themes/customizr/prenota/index.php');
}else if($explode[1] == '' and $explode[2] == ''){
require('wp-content/themes/customizr/book/index.php');
} else {
}
?>
</div>
</body>
INDEX - BOOK (english reservation module)
<?php include "prova1.php"; ?>
<script>
function getArrival(val) {
$.ajax({
type: "POST",
url: "wp-content/themes/customizr/book/process.php",
data:'dep_name='+val,
success: function(data){
$("#arrivals-list").html(data);
}
});
}
</script>
<script>
function chk(){
var var1=document.getElementById('departures-list').value;
var var2=document.getElementById('arrivals-list').value;
var var3=document.getElementById('passengers').value;
var var4=document.getElementById('bags').value;
var dataString='var1='+ var1 +'&var2='+ var2 +'&var3='+ var3 +'&var4='+ var4;
$.ajax({
type: "POST",
url: "wp-content/themes/customizr/book/process2.php",
data:dataString,
cache:false,
success: function(html){
$('#resbox').html(html);
}
});
return false;
}
</script>
<body>
<div id="rcorners1">
<form action='wp-content/themes/customizr/book/index.php' method='post'>
<label>Departure:</label>
<select name="departures" id="departures-list" class="form-control" onchange="getArrival(this.value);">
<option value="">Select Departure</option>
<?php
require('wp-content/themes/customizr/book/prova1.php');
$sql1 = "SELECT * FROM departures";
$result1 = $mysqli->query($sql1);
while($row1 = $result1->fetch_assoc()){
?>
<option value="<?php echo $row1["dep_name"]; ?>|<?php echo $row1["dep_air"]; ?>"><?php echo $row1["dep_name"]; ?></option>
<?php } ?>
</select>
<label>Arrival:</label>
<select id="arrivals-list" name="arrivals">
<option value="">Select Arrival</option>
</select>
<input id="input" type="submit" name="submit" onclick="return chk()" value="Get Price" />
</form>
You have two different div in your website. One of it has id = image, and second is id = modulemin. Div with id = image hiding when screen size < 800px width with css( display = none ), and second is hiding when screen size > 799px width with css( display = none ). And both of them have similar forms. Why you need it? Why to have 2 similar forms only for different screen sizes?
Your main problem is with id's of your form inputs variables var1, var2 ....
Your trying to got some info using ids of inputs in this lines:
var var1=document.getElementById('departures-list').value;
But, as you can understand, you always will get only inputs from first form in DOM tree, because after finding first occurrence of any id, js stoped searching and return it. More detailed about it you can find in any js documentation.
You can use class instead of id for getting all inputs with same classname from page. You can use some differ id for forms, and then get inputs with id/name/class/tagname as child node of that form( ex. ).
Also, strongly not recommend to send ajax request to some other file. Instead of it, use wp-ajax.
Related
I have a PHP file which SELECT's all from the row found based on an SQL query. When I put the echo in a div, I get all information, but when I try to echo it into an input box in a form, it does not shows.
What am I doing wrong?
Please also note that I am aware that I am (most likely) making a lot of mistakes when it comes to security practices or programming standards, but this whole thing (PHPDesktop > https://github.com/cztomczak/phpdesktop) will get packed into an EXE file which will run locally only (no need for an online connection as the SQLite3 DB gets packed in with the EXE), and I am still figuring out how to program this in the first place, so efficient and tidy coding are not high on my list yet ;-)
DO_CUSTEDIT.PHP
$custName = $_POST['custName'];
$query = "SELECT * FROM `CustDB` WHERE CustName LIKE '%$custName%'";
$result = $db->query($query);
while ($row = $result->fetchArray()) {
$custID = $row['CustID'];
......;
}
if (!$result) {
echo $db->lastErrorMsg();
$db->close();
exit;
} else {
echo $custID;
echo ......;
$db->close();
exit;
}
EDITCUST.PHP / Javascipt
<script>
$(document).ready(function() {
$("#subeditcust").on('click',function(e) {
e.preventDefault();
$.ajax( {
url: "lib/do_editcust.php",
method: "post",
data: $("form").serialize(),
dataType: "text",
success: function(strMessage) {
if (strMessage == "Customer updated successfully") {
$("#message").text(strMessage);
$("#neweditform").get(0).reset();
} else {
$("#message").text(strMessage);
}
}
});
});
});
</script>
EDITCUST.PHP / HTML
<form id="editcustform" name="editcustform" action="" method="post">
<div class="row">
<div class="column-half" style="background-color:#fff">
<table>
<tr>
<td>
<a>Customer ID</a>
</td>
<td>
<div class="inputb">
<input type="text" name="custID" value="<?php echo (isset($custID)) ? $custID: ''; ?>" readonly/>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<table style="table-layout:fixed">
<td style="background-color: rgb(215,215,215); padding:0 10px;">
<button id="subeditcust" type="submit" class="mainbtn">Create</button>
</td>
<td style="background-color: rgb(215,215,215); padding:0 10px;">
<button id="reseteditcust" type="reset" class="mainbtn">Reset</button>
</td>
</table>
</div>
</form>
<input type="text" name="custID" value="<?php echo (isset($custID) ? $custID: ''); ?>" readonly/>
Replace this line with yours it will work. IA
It seems you have two different files, right? DO_CUSTEDIT.PHP and EDITCUST.PHP
The variables are being created on DO_CUSTEDIT.PHP and the when you are creating the HTML code those variables ($custID) are not setted.
Is one file including or requiring the other?
EDITCUST.PHP is your first page from you are submitting form to DO_CUSTEDIT.PHP
When you land on EDITCUST.PHP variable $custID is not created
When the form is submitted through ajax, the ajax returns the data inform of object or array depending on how you are echoing the data from DO_CUSTEDIT.PHP
I would recommend to use json_encode() php function to return inform of array
To debug the value by logging the data in console (though function console.log())
After returning the value from ajax, you have to populate the value in form through jquery something like $(input[name="custID"]).val( data.custID )
I managed to figure it out!
DO_CUSTEDIT.php / PHP
$results = array($custID, $custName);
echo json_encode($results, JSON_PRETTY_PRINT);
EDITCUST.php / HTML
<input type="text" id="custID" name="custID" value="" readonly/>
<input type="text" id="custName" name="custName" value="" readonly/>
EDITCUST.php / JS
<script>
$(document).ready(function() {
$("#subeditcust").on('click',function(e) {
e.preventDefault();
$.ajax( {
url: "lib/do_editcust.php",
method: "post",
data: $("form").serialize(),
dataType: 'json',
success: function(data){
document.getElementById('custID').value = data[0];
document.getElementById('custName').value = data[1];
}
});
});
});
</script>
firstly, let me express that I have tried four methods (All slightly different) that all seem to produce the same issue, which is no data being outputted, even simple echo 'test' to rule out a DB issue (and also trying TEST in html on the called page, no result.
Here is a snapshot of the HTML and Javascript:
(document).on('change','category_id',function(){
var id = $(this).val();
$.ajax({
method: 'POST',
url: 'supportgetsubcats.php',
data: {'subcatid' : id},
success: function(data){
$('#subcatresponse').hide().html(data).fadeIn(); // update the DIV
}
});
});
<div class="form-group">
<label class="col-sm-2 control-label">Category *</label>
<div class="col-sm-4">
<select class="form-control" class="category_id" name="category_id" id="category_id">
<option value="" selected="selected">-- Select --</option>
<?php
$query="select * from support_categories where hide = '0' or hide is NULL order by name ASC";
$rs=sqlsrv_query($conn,$query);
while($row=sqlsrv_fetch_array($rs))
{
extract($row);
?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php
}
?>
</select>
</div>
</div><!-- form-group -->
<div class="form-group">
<div id="subcatresponse" name="subcatresponse" class="col-sm-4">
</div>
</div><!-- form-group -->
Here is the PHP that is called:
<?php require_once("includes/header.php");
error_reporting(E_ALL);
echo 'TEST';
if(isset($_POST["subcatid"])){
// Capture selected country
$category = $_POST["subcatid"];
$query="select * from support_subcategories where parent_category = '" . $category . "' order by name ASC";
$rsp=sqlsrv_query($conn,$query);
$subCatArr = array();
while($row=sqlsrv_fetch_array($rsp))
{
$subcat = $row['name'];
array_push($subCatArr, $category, $subcat);
}
// Display city dropdown based on country name
if($category == '-- Select --'){
} else {
echo '<label class="col-sm-2 control-label">Sub Category</label>';
echo '<select class="form-control" name="subcategory_id" id="subcategory_id">';
foreach($subCatArr[$category] as $value){
echo '<option value="'. $value .'">'. $value .'</option>';
}
echo "</select>";
}
}
?>
I get no response, not even basic text back, so I am not entirely sure what is wrong with the AJAX call, jQuery is included and proven to be working as the menu system on this interface won't display without jQuery so I am confident that is not the issue.
It looks like for whatever reason, the data from the HTML Select is not being passed to the AJAX call for POST.
Any thoughts greatly appreciated, TIA.
Try changing
(document).on('change', 'category_id', function() {
to
$(document).on('change', '#category_id', function() {
The second parameter to the on call takes a selector, but you seem to be passing in the name of the element instead. The name of the element is used when trying to access the element in PHP, and you use the selector (id, class, element) in JavaScript.
Alternatively, you could also use
$('#category_id').on('change', function()
You haven't posted it in your question, but in case you don't have it, it is always a good idea to only execute your jQuery code after the page has finished loading, otherwise your code may be trying to access an element that hasn't been loaded yet.
Surround your jQuery code with
$(document).ready(function() {
// Run jQuery code
}
add type='POST' to your ajax call
Also change this
(document).on('change','category_id',function(){
to
$(document).on('change','category_id',function(){
I am a beginner in using jQuery and Ajax.
I have the following hierarchy of directories on a server.
I would like to get the file hierarchy dynamically into dropdown like this
OnClick of "Search" Button, a download URL (as shown below) with the selected drop down values should appear
"http://abc.def.com/ProductName1/Series1.1/FileName1.1.zip"
I understand the best way to accomplish this is using jQuery and Ajax.
How do I make the directory hierarchy of "Product Name" on server to appear dynamically ? And the the respective "Product Series" and "File" change whenever new Product Name is selected?
Here is just a real basic layout. This particular solution calls itself but you can split it into two pages. To make multiple calls to build your dropdowns, you probably could use a function since the logic will likely repeat itself as you drill down the folders:
index.php
<?php
error_reporting(E_ALL);
if(isset($_POST['scan']) && !empty($_POST['scan'])) {
// For your convenience, you can see what returns
print_r($_POST);
$filter[] = '.';
$filter[] = '..';
// Decode directory string from form
$dir = base64_decode(urldecode($_POST['dir']));
// Add root (you may have defined a root, but I am
// using the server document root key/value
$current = str_replace("//","/",$_SERVER['DOCUMENT_ROOT'].$dir);
// Check that the directory exists
if(is_dir($current)) {
// Scan this directory
$files = scandir($current);
// If there are folders/files
if(!empty($files)) { ?>
<label>Series</label>
<select name="series">
<?php
foreach($files as $infolder) {
// If just return directories
if(is_dir($current.$infolder) && !in_array($infolder,$filter)) { ?>
<option name="<?php echo urlencode(base64_encode($infolder)); ?>"><?php echo substr($infolder,0,20); ?></option>
<?php
}
} ?>
</select>
<?php
}
}
// Exit so you don't continue to print the bottom stuff
// Which is what you would load in the first place
exit;
}
// These are just fake, obviously. You can populate the
// first dropdown however you want
$dir = "/root/";
$dir2 = "/root/folder1/";
?>
<form id="get_files" method="post">
<input type="hidden" name="scan" value="true" />
<select name="dir">
<!-- This encoding just makes it easier to transport this data -->
<!-- base64 is probably itself sufficient -->
<option value="<?php echo urlencode(base64_encode($dir)); ?>"><?php echo substr($dir,0,10); ?></option>
<option value="<?php echo urlencode(base64_encode($dir2)); ?>"><?php echo substr($dir2,0,10); ?></option>
</select>
<div id="form_load"></div>
<input type="submit" value="submit" />
</form>
<!-- jQUERY LIBRARIES -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<!-- jQUERY AJAX -->
<script>
$("#get_files").submit(function() {
$.ajax({
url: 'index.php',
data: $(this).serialize(),
type: 'POST',
success: function(response) {
$("#form_load").html(response);
}
});
return false;
});
</script>
I have page with multiple tables being generated by php/mysql. One of the elements is a in/out button. I have it ajax'ed so that the button changes to the on or off image with each click without reloading the page.
And it worked like charm! Until it didn't. If one table or a combination of tables exceeds so many rows...it stops working. But still works on the rows above it. Why would that be?
Here's the table generation...this occurs in multiple php files.
<tbody>
<?php while($row = MySQL_fetch_array($result)):
$id = htmlentities($row['id']);
$status = htmlentities($row['status']);
include ("button.php");
?>
<tr>
<td title="lname" width="100px">
<div style="width:100px; overflow:hidden;">
<?php echo(htmlentities($row['last_name'])); ?>
</div>
</td>
<td width="100px">
<div style="width:100px; overflow:hidden;">
<?php echo(htmlentities($row['first_name'])); ?>
</div>
</td>
.
.
.
<td>
<div style="width:100px; overflow:hidden;">
<?php echo '<div><div id="r'.$id.'"><div id="test"><img class="rating" id="'.$status.$id.'" src="'.$color.'"><div style="display:none;">'.$status.'</div></div></div></div>';?>
</div>
</td>
</tr>
<?php endwhile; ?>
Here's the script:
<script>
$(function(){
$(document).on("click", ".rating", function(){
var status = $(this).attr("id").substr(0,1);
var id = $(this).attr("id").substr(1);
var data = "id="+id+"&status="+status;
$.ajax({
type: "POST",
url: "rate.php",
data: data,
success: function(e){
$("#r"+id).html(e);
}
})
});
});
</script>
Here's the rate.php referenced in the code above:
<?php
include ("db.php");
$id = $_POST["id"];
$newstatus = $_POST["status"];
if($newstatus == 0){
mysql_query("UPDATE users SET status = 1 WHERE id='$id'");
}
else {
mysql_query("UPDATE users SET status = 0 WHERE id='$id'");
}
include("button.php"); //FILE WITH THE LIKE & DISLIKE BUTTONS AND THE NUMBER OF LIKES & DISLIKES
$list = '<div id="test"><img class="rating" id="'.$q[0].$id.'" src="'.$color.'"><div style="display:none;">'.$q[0].'</div>';
echo $list;
?>
And the button.php file referenced above:
<?php
$q = mysql_query("SELECT status FROM users WHERE id='$id'");
$q = mysql_fetch_array($q);
if($q[0]){
$color = "green.png";
}
else{
$color = "red.png";
}
?>
So yeah...if the mysql query for one table is too large, after a certain number of rows, the in/out buttons stop working. Or if I have multiple smaller tables, once it exceeds a certain total number of rows, same thing.
Help?
While debugging in comments, it was realized that duplicate id's were being used. ID's must be unique within a single page, otherwise unexpected results may occur (such as the problem described in the question).
To test for duplicate id's, use the attribute equals selector.
console.log($("[id=" + theidtotest + "]").length)
if you ever get more than 1 elements from that line, you're doing something wrong.
I'm working on putting together a multi-page set of forms that are interlinked by a session and use Javascript for form validation whenever each section is submitted. My first form is working fantastically. My second one, not so much. It's a dynamically created form that depends on the previous form for the number of drop down boxes (between 1 and 20) that are populated from a database. I will spare you all the query code to create the array that fills in my dropdowns and get straight to the form validation script and then the form itself.
The validation script from the head without the <script> tags:
function validateForm()
{
var count = <?php echo $_SESSION['credits']; ?>;
var i = 1;
for (i = 1; i <= count; i++)
{
var j = i;
for (j++; j <= count; j++)
{
var a = document.forms["addcredits"]["creditdropdown_"+i].value;
var b = document.forms["addcredits"]["creditdropdown_"+j].value;
if ((a == b) && (a != 0))
{
alert('Cannot select the same writer more than once.');
return false;
}
}
}
var foundOne = false;
var h = 1;
while (h <= count && !foundOne)
{
if (document.forms["addcredits"]["creditdropdown_"+h].value != 0)
{
foundOne = true;
}
h++;
}
if (!foundOne)
{
alert('You must select at least one writer to credit.');
return false;
}
}
The form code:
<form id="addcredits" class="appintro" method="post" action="recordcheck.php" onsubmit="return validateForm()">
<div class="form_description">
<h2>Song Title Submission</h2>
<p>Step 2: Select writing credits for song title</p>
</div>
<ul>
<?php
for ($i = 1; $i <= $_SESSION['credits']; $i++)
{ ?>
<li id="li_<?php echo $i; ?>">
<label class="description" for="creditdropdown_<?php echo $i; ?>">Song Credit #<?php echo $i; ?>:</label>
<select "creditdropdown_<?php echo $i; ?>">
<option value="0">Select a writer</option>
<?php foreach ($writers as $key => $writer) { ?>
<option value="<?php echo $key; ?>"><?php echo $writer; ?></option>
<?php } ?>
</select>
<p class="guidelines" id="guidelines_<?php echo $i; ?>">Writer not found in database? Add them here.</p>
</li>
<?php } ?>
<li id="buttons">
<input type="hidden" name="form_id" value="2">
<input type="hidden" name="submit" value="1">
<input id="nextButton" class="button_text" type="submit" name="submit" value="Next">
</li>
</ul>
</form>
Neither of the alert windows pop-up when I click Next and if I stick random debugg-ing alert windows into the validation script, the only ones I was able to get to show up were the ones I stuck at the beginning of the code. The furthest I got them to work was the first assignment of a after that, not even the debuggers would show. I'm assuming I'm doing something incorrectly in the assignment or there is something wrong with the values in the dropdown? Either way, I'm stumped.
I'd say the problem is in your HTML:
<select "creditdropdown_<?php echo $i; ?>">
You are specifying, presumably, the name attribute but you forgot the name= part. Try this:
<select name="creditdropdown_<?php echo $i; ?>">
In your validation function when you get to this line:
var a = document.forms["addcredits"]["creditdropdown_"+i].value;
You'll find you have an error because document.forms["addcredits"]["creditdropdown_"+i] is undefined because of the missing name= in the html and undefined can't have a .value property.
(By the way, debugging with alert() is useful very occasionally, but you're much better off using the built in developer tools in Chrome - just hit (I think) ctrl-shift-J to get the JS console - or download FireBug for Firefox. Or use IE's developer toolbar. Use console.log() instead of alert(), and/or step through the code until you find the problem.)