Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
hi there i got a jquery/ajax/javascript plugin that i'm calling/running directly off my HTML website - it's basically a vertical ticker - news update ticker -
here's the code -
<script src="jquery.vticker-min.js"></script>
<script type="text/javascript">
$(function(){
$('#news-container').vTicker({
speed: 500,
pause: 3000,
animation: 'fade',
mousePause: false,
showItems: 3
});
$('#news-container1').vTicker({
speed: 700,
pause: 4000,
animation: 'fade',
mousePause: false,
showItems: 1
});
});
</script>
I have a PHP file which prints out statements automatically inserted in a PHP table in the backend which is then automatically printed out on the ticker.
Here's the PHP code for that - the name of the PHP file is "getuser2.php"...
<?php
$con=mysqli_connect("localhost","root","*****","smartliving");
// check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM smartliving.my_dba");
while($row = mysqli_fetch_array($result))
{
echo $row['LastName'] . " " . $row['FirstName'];
echo "<br>";
}
mysqli_close($con);
?>
the PHP file spits out the updated information in between the following tags (which contain the ticker):
<div style="overflow: hidden; position: relative; height: 125px;" id="news-container">
</div>
without reading from the PHP file, the updated code would be placed in between the two tags above...
...now how do I go about calling the php file from the javascript news update ticker and displaying it between the two div tags in the main HTML page? the javascript news ticker is ALSO called from the main HTML page but in another part of the page...
it seems simple...but its been boggling my mind for a quite a while
ok - so here's what i did - Rob M - it made NO difference what so ever!!!
here's the stuff that i did - updated code and all according to what Rob asked me to do: - i see no difference though!
From the PHP side -
<?php
$con=mysqli_connect("localhost","root","*******","smartliving");
// check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM smartliving.my_dba");
while($row = mysqli_fetch_array($result))
{
echo $row['LastName'] . " " . $row['FirstName'];
echo "<br>";
}
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$response = array();
while($row = mysqli_fetch_array($result))
{
array_push($response, $row);
}
header('Content-type: application/json');
echo json_encode($response);
exit;
}
mysqli_close($con);
?>
From the Javascript side:
<script src="jquery.vticker-min.js"></script>
<script type="text/javascript">
$(function(){
var $news_container = $('#news-container');
$.getJSON('getuser2.php', function(data){
$.each(data, function(item){
$news_container.append('<div style="overflow: hidden; position: relative; height: 125px;" id="news-container">'+item.LastName+' '+item.FirstName+'</div>');
});
});
$('#news-container').vTicker({
speed: 500,
pause: 3000,
animation: 'fade',
mousePause: false,
showItems: 3
});
$('#news-container1').vTicker({
speed: 700,
pause: 4000,
animation: 'fade',
mousePause: false,
showItems: 1
});
});
From the HTML side:
<div style="overflow: hidden; position: relative; height: 125px;" id="news-container">
<ul style="position: absolute; margin: 10pt; padding: 0pt; top: 0px;">
<li style="margin: 0pt; padding: 0pt; height: 38px; display: list-item;">
<div>
4) jugbit.com jquery vticker more info more info more info
</div>
</li>
<li style="margin: 0pt; padding: 0pt; height: 38px; display: list-item;">
<div>
1) Lorem ipsum dolor sit amet, porta at, imperdiet id neque.
</div>
</li><li style="margin: 0pt; padding: 0pt; height: 38px; display: list-item;">
<div>
2) Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>
</li><li style="margin: 0pt; padding: 0pt; height: 38px;">
<div>
3) Lorem ipsum dolor sit amet more info more info more info
</div>
</li></ul>
</div>
</div>
OK...LETS SIMPLIFY THIS ONE STEP AT A TIME - HOW DO I CALL A PHP FILE ONTO A REGULAR HTML FILE ...FORGET THE JAVASCRIPT/JSON PART - THE PHP FILE RETURNS A SET OF STRINGS FROM A DATABASE IN THE BACKEND...I NEED THE STRING TO BE REPRINTED ONTO THE FRONT PAGE OF THE HTML FILE...HOW WOULD I MANAGE TO DO IT? ANY POINTERS?
getuser2.php returns the following which it extracted from an InnoDB databse in the backend:
Griffin Peter
Griffin Lois
Swanson Joseph
Quagmire Glenn
How do i get this list to be printed onto an HTML file? it would be nice if i could know!
As my original comment stated, AJAX is what you are looking for. It is a very important aspect of web development and I suggest you click the link I posted to the jQuery documentation and read the documentation and/or read the Wikipedia article on AJAX.
Essentially, AJAX allows you to fetch content and inject it into the DOM without reloading the page. That really is the answer to the question: 'how to call php file from html/javascript".
Specific examples of how you could use it are below.
On your PHP side, you can detect that it's an AJAX request with the following:
<?php
$con=mysqli_connect("localhost","root","********","smartliving");
// check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM smartliving.my_dba");
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$response = array();
while($row = mysqli_fetch_array($result))
{
array_push($response, $row);
}
header('Content-type: application/json');
echo json_encode($response);
exit;
} else {
while($row = mysqli_fetch_array($result))
{
echo $row['LastName'] . " " . $row['FirstName'];
echo "<br>";
}
}
mysqli_close($con);
?>
In your JavaScript, you can make the request via a nice shortcut method $.getJSON (Note: I'm using the HTML you provided, but please be aware that having multiple elements with the same id is improper and will have unintended consequences, I suggest switching to a class instead):
var $ul = $('#news-container').find('ul');
$.getJSON('getuser2.php', function(data){
$.each(data, function(item){
$news_container.append('<li style="margin: 0pt; padding: 0pt; height: 38px;"><div>'+item.LastName+' '+item.FirstName+'</div></li>');
});
});
This is my best guess with the information you have provided. Happy to elaborate on this if needed.
Related
Okay so I'm trying to create a replica of the Billboard Hot 100. I have already a database and the page with the proper format I want. But when I tried to retrieve the data from the database, the format I used became a huge mess and a lot of errors appeared.
Here's my code:
<div class="chartsList">
<ul class="charts" style="list-style: none;">
<?php
$songQuery = mysqli_query($con, "SELECT * FROM songs ORDER BY sales DESC LIMIT 100");
while($row = mysqli_fetch_array($songQuery)) {
$i = 2;
foreach($songQuery as $songId)
echo "<li class='chartsRow'>
<div style='width:10%;height:100%;float:left; text-align: center;color:black;font-size: 40px;line-height: 150px;font-weight: 600;'>$i</div>
<img style='height: 30%; float: right; position: relative; top: 50; right: 89%;'src='" . $row['movement'] . "'>
<img type='button' style='float: right;width: 25px;position: relative;top: 60;'onclick='myFunction()'src='assets/icons/expand.png'>
<div style='width:90%; height:100%; display: block;''>
<div style='width:15%;height:100%;float:left'>
<img style='height: 90%;margin-top: 8;'src='". $row['coverArt'] . "'>
</div>
<div style='width:85%; height: 100%;margin-left: 26%;''>
<a style='font-size: 30px; font-weight: 600; position: relative; top: 30;'>" . $row['title'] . "</a>
<p style='position: relative;top: 10;''>" . $row['artist'] . "</p>
</div>
</div>
<div id='moreinfo'>
<div class='lefty'>
<a>" . $row['lastWeek'] . "</a>
<p>LAST WEEK</p>
</div>
<div class='lefty' style='border-left-style: solid;border-left-width: 1px;border-right-style: solid;border-right-width: 1px;border-right-color: #b7b7b7; border-left-color: #b7b7b7;'>
<a>" . $row['peak'] . "</a>
<p>PEAK POSITION</p>
</div>
<div class='lefty'>
<a>" . $row['woc'] . "</a>
<p>WEEKS ON CHART</p>
</div>
</div>
</li>";
$i = $i + 2;
}
?>
</ul>
</div>
Current Issue:
"Warning: mysqli_fetch_array() expects parameter 1 to be
mysqli_result, boolean given in C:\xampp\htdocs\billboard\hot-100.php
on line 52"
What I'm trying to achieve is something that looks like this: https://www.billboard.com/charts/hot-100 but with the rows from 2-100 taking up 60% of the screen and a lower portion that can appear/disappear when clicking the extend icon.
Not sure what all the errors are but the main issue here is that you need to turn on error reporting and check for connection errors before trying to use the query and then also check for errors after running the query but before accessing the result set.
I have removed the inner foreach loop because it is redundant. You can create a counter by simply incrementing a variable. See comments in code.
<?php
// Turn on error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Turn MySQL errors into PHP exceptions
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// I assume you have a procedural-style connection setup here.
$con = mysqli_connect("localhost", "xxx", "xxx", "xxx");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
<div class="chartsList">
<ul class="charts" style="list-style: none;">
<?php
$counter = 0;
$songQuery = mysqli_query($con, "SELECT * FROM songs ORDER BY sales DESC LIMIT 100");
// Now, check if your query has an error
if ($songQuery === false){
die('Error in query: ' . mysqli_error($con));
}
while ($row = mysqli_fetch_array($songQuery)) {
// Your HTML appears to be malformed. I'm getting all sorts of errors in my IDE.
// Removing the HTML here but you should be able to merge that back in without issues.
// If you need a counter to display row numbers, you can just create one.
// Notice I created a $counter variable above.
// increment it by:
// $counter++; to increment by 1 OR
// $counter = $counter + 2; to increment by 2
// Now, use $row['column_name'] where you need it.
} ?>
</ul>
</div>
EDIT
Sounds like you're also having CSS/styling issues. Get the DB query going first and then ask a new, specific question with more details including screen shots.
I have been trying to echo a message in a slideshow that is a plugin in WordPress. However, no matter what I do I can not get it to work. What have I done wrong? it should be possible to echo this message in a plugin. The plugin's name is Photo Gallery
<div id="bwg_slideshow_image_container_<?php echo $bwg; ?>" class="bwg_slideshow_image_container_<?php echo $bwg; ?>" >
<!-- Changed Added popup -->
<?php
if($host == 'https://www.artists.com/#') {
echo $this->__('<div style="width: 200px; height:100px; top: 50px; left: 20px; position:absolute; z-index: 3,000; background-color: #fff; color: #000;"> Please click on the arrow at the bottom of the page for additional information</div>');
} ?>
<!-- Changed end added -->
PROBLEM:
I have a dynamic form that is using JQuery steps to make it a wizard. Right now, there is a step where a drop down box selection triggers an AJAX call that then adds form fields to the form. I need the height of the div that this field is in to become longer based off of the amount of fields added.
IMAGES:
The form starts with two drop downs:
Once something is selected for the second dropdown, the AJAX call is made and the form appends fields.
The grey box should resize to accomodate the appended fields.
CODE:
The CSS for the div is as follows:
.wizard > .content
{
background: #eee;
display: table-cell;
margin: 0.5em;
min-height: 35em;
position: relative;
width: auto;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
I can add a permanent height here, but it's not dynamic.
The form is a Zend Form, so the HTML is as follows:
<div class="container-fluid">
<?php if ($this->error) : ?>
<div class="row-fluid">
<?php echo $this->error; ?>
</div>
<?php else : ?>
<?php echo $this->form()->openTag($form); ?>
<h3>Details</h3>
<section>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_NAME, false, true); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_DUE_DTTM, !($this->uberAdmin)); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_DESCRIPTION); ?>
</section>
<h3>Options</h3>
<section>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_REVIEW_PROJECT); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_WTL_PROJECT); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_JOB_TABLE); ?>
</section>
<h3>Project Configuration</h3>
<section>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_TYPES, !($this->uberAdmin), true); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_SUBTYPES, !($this->uberAdmin)); ?>
<?php
echo $this->partial('project/project/dynamicFormElements.phtml', array('form' => $this->projectForm, 'div' => 'project-config-elts'));
?>
</section>
<h3>Workflow Configuration</h3>
<section>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_WORKFLOW_TYPES, !($this->uberAdmin)); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_WORKFLOW_SUBTYPES, !($this->uberAdmin), true); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_WORKFLOW_CONFIG, !($this->uberAdmin)); ?>
</section>
This generates HTML with the structure below:
The highlighted div is the div in question.
My AJAX call is done here:
// Handle AJAX dynamic form creation results
function updateProjectForm(resp) {
$('div#project-config-elts').html(resp.html);
}
// Handle ajax error
function projectFormError(req, status, err) {
var errorString = '<div class="row-fluid alert alert-error">' +
'Error retrieving project form.' +
'</div>';
$('div#project-config-elts').html(errorString);
}
// AJAX request to get dynamic Project config form
function requestProjConfigForm() {
var request = {project_type: $('select[name=project_types]').val(),
project_subtype: $('select[name=project_subtypes]').val()
};
var ajaxOptions = {
url: 'projectform',
type:'POST',
dataType: 'json',
success: updateProjectForm,
error: projectFormError,
data: request
};
// Initiate the request!
$.ajax(ajaxOptions);
}
$('select[name=project_types]').change(function(){
updateProjectSubtypes();
});
// Handle a change in the selection of the particular project
$('select[name=project_subtypes]').change(function(){
requestProjConfigForm();
});
$('select[name=workflow_types]').change(function(){
updateWorkflowSubtypes();
});
$.validator.addMethod("validJSON", function(val, el) {
try {
JSON.parse(val);
return true;
} catch(e) {
return false;
}
}, "*Not valid JSON");
form.validate({
errorPlacement: function(error, element) {
$( element )
.closest( "form" )
.find( "label[for='" + element.attr( "id" ) + "']" )
.append( error );
},
rules: {
project_config: { validJSON: true }
}
});
I'm thinking that here I can dynamically change the height, but I'm not quite sure how to do so.
It looks like you're running into an issue that has been discussed on the jQuery Steps plugin github page: https://github.com/rstaib/jquery-steps/issues/147
basically, since the body of the step content is positioned absolutely with a percent height, it's height is no longer based on the content within it. A few things people used to try to fix this are:
By waqashsn:
.content > .body{
/*position: absolute*/
float:left;
width:95%;
height:95%;
padding:2.5%
}
Here's another alternative by AneeshRS that instead causes overflowing content to scroll:
.wizard.clearfix > .content.clearfix{
min-height: 500px;
overflow-y: auto;
}
Checkout the link to the issues page for a better explanation of either of these. Note however that any solution that involves removing the absolute positioning will likely cause transitions to no longer work.
I have a problem in running jquery . Here the table sample:
table database
id | name | value
1 data1 10
2 data2 20
3 data3 30
4 data4 40
5 data5 50
Here is my code:
<?php
$sql = "SELECT * FROM database ORDER BY id"
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{?>
<div id="flip">
<?php echo $row['name']?>
</div>
<div id="panel">
<?php echo $row['value']?>
</div>
<?php
}
?>
But the slide toogle jquery only execute once, on the first element. How to make slide toggle execute every row in while looping?
Here is my slidetoggle()Jquery:
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
});
</script>
And the CSS :
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
#panel {
padding: 50px;
display: none;
}
</style>
Based on Jack A. answer, build first your HTML with classes instead of multiples IDs. Then, in your script, use jQuery.next() to find the next panel element and toggle it:
$(document).ready(function(){
$(".flip").click(function(){
$(this).next('.panel').slideToggle("slow");
});
});
Here is a jsfiddle illustrating this.
You are using the same id in multiple elements. Build a unique id for every element. E.g. flip1, flip2, etc. and panel1, panel2, etc.
You are creating multiple HTML elements with the same ID ("flip" and "panel"), which is not correct; IDs should be unique.
An alternative is to use a class instead of an ID:
while($row = $result->fetch_assoc())
{?>
<div class="flip">
<?php echo $row['name']?>
</div>
<div class="panel">
<?php echo $row['value']?>
</div>
<?php
}
JavaScript:
$(document).ready(function(){
$(".flip").click(function(){
$(".panel").slideToggle("slow");
});
});
This will act on all of the elements simultaneously.
I let people fill in a form, and insert distances etc. They get stored in a db.
Then I lead them to a page, where I show the number of axles (12 in this case) and make a circle of them (in css)
Then it looks like this:
The code for this:
<?php
$show_axle = $database->axles($_GET['train_id']);
?>
<div id="axle_bogie_border">
<div id="axle_position">
<?php
foreach($show_axle as $axlefigure){ ?>
<div id='number_of_axles'> <?php echo $axlefigure['axle'] ?></div>
<?php
}
?>
</div>
</div>
The axle_border make the Train image (The black rectangle)
The axle_position take care that the axles (Numbers actually) Don't go in the image but slightly below it (So it looks like wheels/axles).
The Number_of_axles make the numbers look like a circle (Like wheels/axles).
Now the function:
function axles($id){
$sql = "SELECT * FROM axle WHERE train_id = :id2";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(":id2", $id, PDO::PARAM_STR);
$sth->execute();
return $sth->fetchAll();
}
The function selects everything from the table axle (See first image).
Now, I actually want the axles to take a position. And I'm thinking about doing that via the Distance row.
So:
Axle 1 has the number 5 for distance. So it goes 5px from the far left
Axle 2 has the number 10. So i want it 10 pixels next to the axle 1.
Axle 3 has the number 5. So i want it 5 pixels next to the axle 2.
Etc.
Eventually it needs to look like this:
My question: Is this posible. If yes, how?
EDIT:
it is working now :)
I did the following:
<?php
$show_axle = $database->axles($_GET['train_id']);
?>
<div id="axle_bogie_border">
<div id="axle_position2">
<?php
foreach($show_axle as $axlefigure){ ?>
<div style="margin-left:<?php echo $axlefigure['distance'];?>px;">
<?php echo $axlefigure['axle'] ?>
</div>
<?php
}
?>
</div>
</div>
And the css:
#axle_position2 {
margin-top: 9%;
position: relative;
float: left;
}
#axle_position2 div {
background: green;
float: left;
position: inline-block;
width: 40px;
height: 40px;
border-radius: 50px;
}