Load php results with .load() - javascript

I am trying to load the result of a php page with .load() inside a html page. I want to load the results inside a div element with id id="div3_example_result" that i have included in the html page... I want the result to appear when I press one of the calendar date, because I am building a calendar..
I have build this function:
<script type="text/javascript">
window.onload = function(){
g_globalObject = new JsDatePick({
useMode:1,
isStripped:true,
target:"div3_example"
g_globalObject.setOnSelectedDelegate(function(){
var obj = g_globalObject.getSelectedDay();
alert("a date was just selected and the date is : " + obj.day + "/" + obj.month + "/" + obj.year);
$('#div3_example_result').load('insert.php');
});
};
</script>
and this is the html part
<body>
<br />
<div id="div3_example" style="margin-left: 500px; margin-top: 100px; border:dashed 1px red; width:205px; height:230px;">
</div>
<div id="div3_example_result" style="height:20px; line-height:20px; margin:10px 0 0 0; border:dashed 1px #666;">
</div>
</body>
But it does not function. Only the alert message appears when I click in one date, but the div is still empty..No result is uploaded...Can you help me please? Thanks in advance...
The php file:
<html>
<body>
<?php
$con = mysql_connect('127.0.0.1','root','');
if (!$con)
{
die('Lidhja me databazen nuk mund te kryhet' .mysql_error(). ' </body></html>');
}
if(!mysql_select_db("Axhenda",$con))
die('Nuk mund te hapet databaza Axhenda'.mysql_error(). '</body></html>');
$result = mysql_query("SELECT * FROM Perdoruesi");
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
</body>
</html>

Related

get data from xampp sql server using html and php

I'm a complete beginner in php and I am working on a front end project where I have to create a hangman game based on 12 island names stored in a mysql xampp server . I have to get a random island from the database as an unordered string displayed in my html and guess which island it is . I have no idea how to implement this using php since I am a complete beginner but I have watched tutorials about how to send data from html forms to an sql server with php . I guess this is kinf of the opposite task .
I have written complete html css and js code about displaying my hangman game and I use a simple word to be displayed randomly via javascript and when you fill the spaces a submit button appears .
function hangman(){
var island = "Santorini"; //the given word that is supposed to be found
var t = document.createTextNode(shuffleWord(island))
document.getElementById("hidden-word").appendChild(t);
createSpaces(island);
const inputLists = document.querySelectorAll("input");
document.querySelectorAll("input").forEach(el => {
el.addEventListener('input', evt => {
const showButton = [...inputLists].filter(ip => ip.value.trim() !== '').length === inputLists.length;
document.getElementById('submitbtn').style.display = showButton ? 'block' : 'none';
});
});
}
function shuffleWord (word){
var shuffledWord = '';
word = word.split('');
while (word.length > 0) {
shuffledWord += word.splice(word.length * Math.random() << 0, 1);
}
return shuffledWord;
}
function createSpaces(text){
for(var i=0;i<text.length;i++){
var space = document.createElement("input");
space.setAttribute("class" , "dash");
document.getElementById("hangman-container").appendChild(space);
}
}
.transparent-box{
border:none;
position:absolute;
top:10%;
left:15%;
background-color:black;
height:500px;
width:70%;
opacity: 0.6;
}
.transparent-box p{
color:white;
text-align:center;
}
.transparent-box h1{
color:white;
position: relative;
text-align:center;
font-size:20px;
top:30px;
}
#hangman-container{
position: relative;
width:auto;
top:30%;
left:0%;
background-color: transparent;
display: flex;
flex-direction: row;
justify-content: space-evenly;
}
.dash{
margin:0;
padding:20px;
align-items: flex-start;
width:4%;
border:none;
border-radius: 5%;
background-color: turquoise;
color:red;
font-size:40px;
}
.dash:focus{
opacity:0.8;
}
#submitbtn{
display: none;
position: absolute;
top:200%;
left:80%;
float:right;
}
<body onload=hangman()>
<div class="transparent-box" id="t-box">
<p>Play here </p>
<h1 id="hidden-word">The word is : </h1>
<form id="hangman-container" method="POST">
<button type="submit" class="hide" id="submitbtn">Submit</button>
</form>
</div>
</body>
The problem is how to use php to get a random island name from my database and display it instead of sending a string via javascript .
I would appreciate your help with this . Thank you in advance .
First create a table:
CREATE TABLE islands(
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL
);
Insert the islands names there (add as many as you wish in place of the ...):
INSERT INTO islands(name) VALUES
("Santorini"),("Tassos"),...;
Now the following SELECT query will fetch one random island name from the DB:
SELECT name
FROM islands
ORDER BY RAND()
LIMIT 1;
In PHP you can execute the query like this:
// replace the words in uppercase with your actual credentials!
$link = #mysqli_connect('localhost','USERNAME','PASSWORD','DBNAME');
if(!$link){
echo 'Error connecting to the DB';
exit;
}
$sql = "SELECT name FROM islands ORDER BY RAND() LIMIT 1";
$result = #mysqli_query($link, $sql);
if(!$result){
echo 'There is an issue with the database';
exit;
}
$row = #mysqli_fetch_assoc($result);
// This will give you the random island name (if they are inserted properly)
echo $row['name']??'No islands are inserted in the database yet';
Now to shuffle it, we can use str_shuffle() function. Finally your code may start to look like this:
<body onload=hangman()>
<div class="transparent-box" id="t-box">
<p>Play here </p>
<h1 id="hidden-word">The word is :
<?php
// replace the words in uppercase with your actual credentials!
$link = #mysqli_connect('localhost','USERNAME','PASSWORD','DBNAME');
if(!$link){
echo 'Error connecting to the DB';
exit;
}
$sql = "SELECT name FROM islands ORDER BY RAND() LIMIT 1";
$result = #mysqli_query($link, $sql);
if(!$result){
echo 'There is an issue with the database';
exit;
}
$row = #mysqli_fetch_assoc($result);
echo str_shuffle($row['name']);
?>
</h1>
<form id="hangman-container" method="POST">
<button type="submit" class="hide" id="submitbtn">Submit</button>
</form>
</div>
</body>
Now you will need to adjust your JavaScript code of course.

Retrieving id error from jQuery and PHP Chat

I have some problems on the retrieving id from php on mysql, somewhat, for what I found out, is that the id is saving somewhere (eg: something like a cache) where it saves it and create a loop when I don't ask for a loop.
For example
you can see the chat windows. Where it shows the user you are talking and the list of user which are online. (Like facebook)
The problem here is that when I toggle where it says "Nuno Monteiro" chat message. it hides it, and goes to the id "1" in this case but if I click on "Joane" and do that the id it will show as "1" and after "2".
And when I go back to "Nuno" I can not toggle and hide again but it gives me the id as "1" then "2" then "1" again "2" like that.
What I want is to pick just the current id from the function callID(id) and just select that one.
Here below you have the code:
dashboard.php:
<div class="chat-data" id="chat-data" style="display:none;">
<?php
for ($i = 0; $i < count($result); $i++) {
if($result[$i]['online'] == 0) {
echo "<span onclick='callID(".$result[$i]['id'].");' class='user-btn".$result[$i]['id']."' style='padding: 7px; display:inline-block; position: relative; border-bottom: 1px solid #ccc; width: 100%; cursor: pointer;'><span class='offline'></span> ".$result[$i]['firstname']." ".$result[$i]['lastname']."</span>";
} else {
echo "<span onclick='callID(".$result[$i]['id'].");' class='user-btn".$result[$i]['id']."' style='padding: 7px; display:inline-block; position: relative; border-bottom: 1px solid #ccc; width: 100%; cursor: pointer;'><span class='online'></span> ".$result[$i]['firstname']." ".$result[$i]['lastname']."</span>";
}
}
?>
</div>
This is the part from the chat(1) window.
The part of "Nuno Monteiro" window is also from dashboard.php, which is the following code:
<div class="chat-user" style="display: none;">
<div class='user-title'>
<span class="titles"></span>
<span class='pull-right remove_field'>X</span>
</div>
<div class="chat-time">
<div class="msg_data" id="msg_data">
<div class="friend_pic pull-left">
<img src="<?php echo $domain; ?>resources/img/babox_logo.png" data-toggle="tooltip" data-placement="bottom" title="Nuno Monteiro" />
</div>
<div class="friend">
<span>Hey There are you ok?</span>
</div>
<div class="your_pic pull-right">
<img src="<?php echo $domain; ?>resources/img/babox_logo.png" data-toggle="tooltip" data-placement="bottom" title="You" />
</div>
<div class="you">
<span>I am fine!</span>
</div>
</div>
<div class="msg_box" id="msg_box">
<textarea id="chatbox"></textarea>
</div>
</div>
</div>
The $domain variable is where I get my website name so I don't need to change it in every code I have and change it only there.
That is picking up results from $db = new DbManager(); and the variable $result will execute the select by doing: $result = $db->execute_select($sql)
The $sql variable is: "SELECT * FROM users";
Then we going pass through our jQuery function (which I mention above):
function callID(id) {
$(".chat-time").prop("id",id);
$(".chat-user").hide();
$(".remove_field").click(function() {
$(".chat-user").hide();
});
$.post('callID.php', {id : id }, function(rID) {
// nothing on here
$(".user-title").click(function(e) {
$('#' + rID).toggle();
e.preventDefault();
alert(rID);
});
if(id == rID) {
$(".chat-user").show();
$(".user-title span.titles").html($(".user-btn" + rID).text());
} else {
$(".chat-user").hide();
}
});
}
this is part from my general.js script.
Then the script will go pick the information to the callID.php:
<?php
include('application/database/dbmanager.php');
$db = new DbManager();
$sql = "SELECT id FROM users WHERE id='".$_POST['id']."'";
$db->execute_select($sql);
echo $_POST['id'];
?>
What I wanted to happen is that when I toggle in the online user chat on each username, go pick only the id of that user, so later I can save the messages in database and pick it up.

How to open close div with transition effect in php page?

I want to add some transition like slidedown, fadein using jquery. when someone clicks on a title city. it opens with effect. I am trying it with jquery but it won't work. Any solution that where i am wrong or solution with css ?
Java Script Code :
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
//------------------- Jq used to show/open single div when click on title link -----------
function showDiv(obj)
{
$('.CityDivInner').css('display','block');
var div = $(obj).find('.CityDivInner').css('display','none');
}
</script>
<script>
$(document).ready(function(){
$(".CityDivOuter").click(function(){
$(".CityDivInner").slideDown("slow");
});
});
</script>
Css Code :
<style>
.CityDivInner
{
display:none;
}
</style>
</head>
Php Code :
<?php
$link = mysqli_connect("localhost", "root", "", "test");
// Check connection
if($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM sample";
if($result = mysqli_query($link, $sql))
{
if(mysqli_num_rows($result) > 0)
{
echo "<div class='cityContainer'>";
while($row = mysqli_fetch_array($result))
{
echo "<div class='cityContainerInner' style='border: 2px solid black;' >
<p class='CityDivOuter' onclick='showDiv(this);'>City</p>
<div class='CityDivInner' style='border: 1px solid black;'>
<p class='CityTitle'>". $row['UserCity'] ."</p>
</div>
</div></br>";
}
echo "</div>";
// Close result set
mysqli_free_result($result);
}
else
{
echo "No records matching your query were found.";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
</body>
Check this code, This might help you!
$(document).ready(function(){
$('.expand').hide();
$(".expand, .collapse").click(function(){
$(".CityDivInner").slideToggle("slow");
$('.expand').toggle();
$('.collapse').toggle();
});
});
.CityDivInner{
width:300px;
height:100px;
background:#888;
}
.expand, .collapse{
margin:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="CityDivInner"></div>
<button class="expand">Expand</button>
<button class="collapse">Collpase</button>

Pass info from text input through jquery in to php, which returns json, need to parse the return

I am getting a return of undefined. I don't even know what to do. So lost...
html
<!DOCTYPE html>
<html>
<head>
<!--Jquery CDN-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<!--Local files attached-->
<script type="text/javascript" src="CountryList.js"></script>
<link rel="stylesheet" type="text/css" href="CountryList.css" />
</head>
<body>
<div id="wrapper">
<!--Header-->
<h1>Country Information</h1>
<!--input box-->
<form>
<label for="countryInput">Input Country Name : </label>
<input type="text" id="countryInput"></input>
</form>
<br>
<br>
<!--Containing divs for lists-->
<div id="wrapper2">
<!--countries will load here-->
<div id="countryList">
Countries:
<div id="actualList">
</div>
</div>
<!--country info will load here-->
<div id="countryInfo">
Country Info:
<div id="actualInfo">
</div>
</div>
</div>
</div>
</body>
<div id="footer">
<!--Link to page-->
</div>
</html>
css
body{
margin-top:3%;
background-color:white;
text-align:center;
}
h1 {
}
h2 {
font-size:14pt;
}
#header {
color:white;
text-align:center;
padding:5px;
}
#footer {
color:white;
text-align:center;
padding:5px;
}
#countryList {
text-align:center;
overflow:auto;
width: 10%;
height: 400px;
border: 1px solid black;
display: inline-block;
float:left;
margin-left:20%;
}
#countryInfo {
text-align:center;
overflow:auto;
width: 49%;
height: 400px;
margin-right: 20%;
border: 1px solid black;
display: inline-block;
float:right;
}
button {
margin-left:15px;
margin-top:10px;
padding:5px;
margin-bottom:10px;
}
Javascript:
$(document).ready( function(){
var fieldInput = "";
var countrylist = "";
var countryinfo = "";
var countryjson = "getCountryListAsJSON.php";
$( "#countryInput" ).keyup(function( event ) {
fieldInput = $(this).val();
// show that something is loading
$('#actualList').html("<b>Loading response...</b>");
$.ajax({
type: 'GET',
url: countryjson,
data: fieldInput,
dataType: "json"
})
.success(function(data){
alert("success");
countrylist =data;
console.log(countrylist[1]);
$('#actualList').html(countrylist);
})
.done(function(data){
})
.fail(function() {
// just in case posting your form failed
$('#actualList').html("Failed to find countries.");
});
});
$( "#countryInput" ).focus(function() {
$("#countryInput").val("");
$("#actualInfo").html("");
$("#actualList").html("");
fieldInput="";
});
});;
the php script that was provided
<?php
// Name: getCountryListAsJSON.php
// Desc: Gets a sorted list of country names from the world DB which
// begin with the specified letters
// Params: country - beginning string of letters to match
// Outputs: JSON encoded array of country names (strings)
//get argument if provided
if(isset($_GET['country']))
$country = $_GET['country'];
else
$country = "no country specified!"; //will match nothing
//connect to database
$con = mysqli_connect("localhost", "worlddemo", "worldpass", "world")
or die("Some error occurred during connection " . mysqli_error($con));
//run query
$query = "SELECT * FROM country WHERE Name LIKE '$country%' ORDER BY name";
$results = mysqli_query($con, $query);
//build an array of strings (country names) from results
$countryList = array();
while($row = mysqli_fetch_array($results))
{
$countryList[] = htmlentities($row['Name'], ENT_COMPAT, 'UTF-8');
//note: special characters caused problems, hence htmlentities
}
//finish up
mysqli_close($con);
echo json_encode($countryList);
?>
I only get it returned as an undefined.
So I am trying to pass whatever is put in the text input to php.
For each key it is supposed to return a list of countries from a Database (hosted on my localhost xampp)
Im not sure whether its a problem with my teachers PHP or if I am just missing something in my code. I have been trying to just get it to write out in the console to see if I am getting a proper return, but the only thing that seems to be happening is it is returning undefined.
link to the world db http://downloads.mysql.com/docs/world.sql.zip
Access "getCountryListAsJSON.php" file directly from your browser (http://your-server/getCountryListAsJSON.php) and see what happens. If its all ok on the server side, you should see something like this on the page: ["country1", "country2", "country3", ... ]
Another thing you can try is change your success callback to something like this:
.success(function(data){
//alert("success");
var countrylist = data;
var html = "";
for( var i in countryList ){
html += countryList[i];
}
$('#actualList').html(html);
})

how to convert multiple div into image (png/jpeg) using php and javascript?

How can I convert multiple dynamic div (created at runtime) into image. There are more than 50 div which are created at runtime using php array. I just want all those div to be converted to image seperately.
Here is the code I tried for -
<?php
$names = [" ", "abc", "def", "ghi yfg", "jkl", "mno"];
$i=1;
foreach ($names as $name ) {
?>
<div class='mydivCls' id="mydiv<?php echo $i?>">
<p id="mytext"><?php echo $name ?></p>
</div>
<?php $i++; } ?>
<div id="canvas" style="display:none;">
<p>Canvas:</p>
</div>
<div id="image">
<p>Image:</p>
</div>
My Css code --
<style>
#font-face {
font-family:roboto;
src: url("/roboto/Roboto-Medium.ttf")
}
.mydivCls {
background-image: url("1.png");
width: 325px;
height: 207px;
}
.mydivCls p {
font-family: roboto;
padding-top: 100px;
text-align: center;
}
</style>
And here is my script --
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
<script>
var i=1;
$(".mydivCls").each (function(){
html2canvas([document.getElementById('mydiv'+i)], {
onrendered: function (canvas) {
document.getElementById('canvas').appendChild(canvas);
var data = canvas.toDataURL('image/png');
var image = new Image();
image.src = data;
document.getElementById('image').appendChild(image);
}
});
i++;
});
</script>
I'm getting following error in my console --
TypeError: document.getElementById(...) is null
document.getElementById('canvas'+i).appendChild(canvas);
Here is the solution I found --
<?php
/**
* This Script is used for converting a particular div to image
*/
?>
and my HTML code --
<?php
$names = [" ", "Kuldeep Kumar", "Rishabh Gaur", "AMIT RANJAN", "Vinay Agarwal", "MANJEET KUMAR", "Shuchi Singla", "Sumit Chaturvedi"];
$i=1;
foreach ($names as $name ) {
?>
<div class='mydivCls' id="mydiv<?php echo $i?>">
<p id="mytext"><?php echo $name ?></p>
</div>
<?php $i++; } ?>
<div id="canvas" style="display:none;">
<p>Canvas:</p>
</div>
<div id="image">
<p>Image:</p>
</div>
and changes in script --
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
<script>
var i=1;
$(".mydivCls").each (function(){
html2canvas([document.getElementById('mydiv'+i)], {
onrendered: function (canvas) {
document.getElementById('canvas').appendChild(canvas);
var data = canvas.toDataURL('image/png');
var image = new Image();
image.src = data;
document.getElementById('image').appendChild(image);
}
});
i++;
});
</script>
Code for image generation is correct, you have issue in your php part (all div have the same id). Need to increment $i variable:
<?php $i=1;
foreach ($names as $name ) {
?>
<div class='mydivCls' id="mydiv<?php echo $i?>">
<p id="mytext"><?php echo $name ?></p>
</div>
<?php $i++;
} ?>

Categories

Resources