I am working on notification system. So I am following this blog (http://www.phptutorials.club/ajax-notification-in-php-with-example/).
Please see the code.
It's working fine and it's giving me a notification, but the problem is if I include the page in another index.php page, then it's giving me (error (Not Found).
I renamed the index.php as notification.php and I am including it on my website index.php page. So after including it's giving me an error but without including it's working fine.
Please suggest I know PHP but don't know about ajax and jquery,js.
Please see my code below.
notification.php
<style>
#notification_count {
padding: 0px 3px 3px 7px;
background: #cc0000;
color: #ffffff;
font-weight: bold;
margin-left: 77px;
border-radius: 9px;
-moz-border-radius: 9px;
-webkit-border-radius: 9px;
position: absolute;
margin-top: -1px;
font-size: 10px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
function addmsg(type, msg) {
$('#notification_count').html(msg);
}
function waitForMsg() {
$.ajax({
type: "GET",
url: "select.php",
async: true,
cache: false,
timeout: 50000,
success: function(data) {
addmsg("new", data);
setTimeout(
waitForMsg,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg,
15000);
}
});
};
$(document).ready(function() {
waitForMsg();
});
</script>
<span id="notification_count"></span>
Notifications
<div id="HTMLnoti" style="textalign:center"></div>
<script>
</script>
select.php
<?php include "../../includes/db.php" ?>
<?php
$sql = "SELECT * from comments where comment_status = 'unapproved'";
global $connection;
$select_comments= mysqli_query($connection, $sql) or die('Could not look up user information; ' . mysqli_error($connection));
$count = mysqli_num_rows($select_comments);
echo $count;
mysqli_close($connection);
?>
So after including the notification.php file in index.php.it's giving me an error.
But without including this file. it's working fine.
<!-- Notification panel-->
<?php include "../includes/notification.php" ?>
First check if your include path is correct. Try:
<?php include "../../includes/notification.php" ?>
Additionally, check the path to select.php in your ajax call
$.ajax({
type: "GET",
url: "select.php",
...
Second, you should think about splitting notification.php into three parts:
put CSS into main .css file
JavaScript code should be in notification.js
HTML code you can leave in notification.php
Then include notification.php in the index.php after you have included .css and .js files.
Related
Users will submit data using the text editor given on the website. My golang server will capture it , process it and then display result below the text editor on the website.
I am able to get the user input and process it, but I'm unable to send it back to website for displaying results.
main function:
http.Handle("/", http.FileServer(http.Dir("./codemirror")))
http.HandleFunc("/getRules", getRules)
...
getRules function:
//capture form data
//do some processing on captured data
js, _ := json.Marshal(resp)
w.Header().Set("Content-Type", "application/json")
w.Write(js)
index.html:
<!DOCTYPE html>
<html>
<head>
<title>nvrule playground</title>
<link rel="stylesheet" type="text/css" href="plugin/codemirror/lib/codemirror.css">
<link rel="stylesheet" type="text/css" href="plugin/codemirror/theme/the-matrix.css">
<style>
.button {
padding: 15px 25px;
font-size: 24px;
text-align: center;
cursor: pointer;
outline: none;
color: #fff;
background-color: #4CAF50;
border: none;
border-radius: 15px;
box-shadow: 0 9px #999;
}
.button:hover {background-color: #3e8e41}
.button:active {
background-color: #3e8e41;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
</style>
</head>
<body>
<iframe name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe>
<form action="/getRules" method="post" id="ruleForm" target="hiddenFrame">
<textarea id="codemirror-textarea" name="rule"></textarea>
<input class="button" type="submit" value="Send" />
</form>
<!-- javascript -->
<script type="text/javascript" src="plugin/codemirror/lib/codemirror.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/default.js"></script>
</body>
</html>
default.js:
var editor = CodeMirror.fromTextArea(document.getElementById("codemirror-textarea"), {
lineNumbers : true,
theme : "the-matrix",
value: "Enter rules here"
});
I figured it out. You can use ajax.
$('#ruleForm').submit(function(e){
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
success: function(json){
console.log(json)
var templateHtml = $('#resultsArea').html(),
template = Handlebars.compile(templateHtml);
$('#ajaxResponse').html(template(json));
}
});
});
useful link:stackoverflow (question contains my answer)
You can have an endpoint to get the status of the processing that you can poll using setTimeout, something like:
/rule/:id/status
It can return a status code such as (apart of the typical 404, 500, etc.):
{ status: "processing | idle | finished" }
Once the status is finished then GET the result.
/rule/:id
Hope it helps.
I want to add a loading spinner while my remote script is running and my frontend page is in "waiting for ..." state.
I only have 1 php page and one CSS . ( for the moment still in tests so I have not split script page and html page yet).
I have the following css for the loader :
Style.css edited to replace the "." with "#"
#loader {
border: 16px solid #f3f3f3; /* Light grey */
border-top: 16px solid #3498db; /* Blue */
border-radius: 50%;
width: 120px;
height: 120px;
animation: spin 2s linear infinite;
}
#keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
My page looks like this ( after cleaning it ) :
EDIT with webbm comments
<!DOCTYPE html>
<html>
<head>
<title> BETA APP HOME PAGE </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<link rel="stylesheet" href="CSS/style.css">
</head>
<body>
<div id="loader"></div>
<?php
if (isset($_POST['STARTVISUREC']))
{
echo '<script>console.log("End loader spinner")</script>';
// making appearing the spinner before the call to remote server.
echo '<script language="javascript">';
echo 'document.getElementById("loader").style.display="inline"';
echo '</script>';
// calling remote APP in BE server.
$remotstarter = file_get_contents('http://192.168.56.154/WEBAPP/wa_start.php');
echo '<script>console.log("End loader spinner")</script>';
// making disappearing the spinner after the call to remote is finished.
echo '<script language="javascript">';
echo 'document.getElementById("loader").style.display="hidden"';
echo '</script>';
}
if (isset($_POST['STARTFACEREC']))
{
// calling local script for other usage.
shell_exec("sudo python AppPy/cgi-bin/test.py");
echo("Off");
}
?>
<form method="post">
<button name="STARTVISUREC">START VISU REC</button>
<button name="STARTFACEREC">START FACE REC</button><br><br>
</form>
<script>
</script>
</div>
</div>
<div style="margin-left:15%;padding:1px 16px;height:10px;">
</div>
</body>
</html>
still not OK The loading spinner is not appearing
For your case specifically, you could echo a script tag.
<?php
echo '<script language="javascript">';
echo 'document.getElementById("loader").style.display="inline"';
echo '</script>';
?>
Note that I switched around the usage of " and '. Check out the echo documentation for why this is useful https://secure.php.net/manual/en/function.echo.php
I recommend you look into ajax queries which can allow you to perform the javascript actions inside of javascript based on the server response.
Here's a basic example: https://www.w3schools.com/php/php_ajax_php.asp
I have been working with jQuery/JavaScript and ajax for the first time and I am trying to work with the weather underground API to display some weather information on a web-page hosted on google cloud.
I have been reading the weather underground code example and I am trying to work with that which is why the code will look so familiar but I am just trying to get it to work so I can move forward. I have also looked at other stack overflow where similar code questions were asked but I am still not getting anywhere. I apologize for the redundancy but I am unsure why it is not working.
Everything seems to be making sense but when the HTML is suppose to "alert" when the page is loaded I am getting nothing. I would really appreciate some input even if I am doing something stupid just want to get this chunk working in order to move forward.
Below is my HTML file that is a mix of JavaScript and HTML.
<!DOCTYPE html>
<html>
<head>
<title>Hello, The Cloud!</title>
<link rel="stylesheet" type="text/css" href="/static/style.css">
</head>
<body>
<h1>Hello, The Cloud!</h1>
<p> Lets Check the Weather! </p>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/47acb7d74302f585/geolookup/conditions/q/IA/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});
</script>
</html>
My simple CSS file is shown below.
h1 {
color: #000000;
text-align: center;
font-size: 60px;
text-decoration: underline;
}
body {
background-color: LavenderBlush;
font-size: 20px;
}
div {
background-color: lightgrey;
color: #FF0000;
id: "clockbox";
font-size: 20px;
font-family: "Times New Roman", Times, Serif;
width: 420px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}
.alert {
padding: 20px;
background-color: #f44336; /* Red */
color: white;
margin-bottom: 15px;
}
I appreciate any feedback!
Thank you
Thanks to some great advice from #GAEfan and yuriy636 I was able to figure out that Google Cloud does not play well with HTTP requests thus it was just a simple change from HTTP to HTTPS in the URL's as you can see in the code below.
<!DOCTYPE html>
<html>
<head>
<title>Hello, The Cloud!</title>
<link rel="stylesheet" type="text/css" href="/static/style.css">
</head>
<body>
<h1>Hello, The Cloud!</h1>
<p> Lets Check the Weather! </p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$.ajax({
url : "https://api.wunderground.com/api/47acb7d74302f585/geolookup/conditions/q/IA/Cedar_Rapids.json",
success : function(parsed_json) {
console.log(parsed_json);
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});
</script>
</body>
</html>
Here is a link to more info on Google Cloud and HTTP/HTTPS: https://cloud.google.com/compute/docs/load-balancing/http/
Thank you for everyone's help!
The problem is that you don't have <script> tags inside your <body> tag.
This is what I mean:
<!DOCTYPE html>
<html>
<head>
<title>Hello, The Cloud!</title>
<link rel="stylesheet" type="text/css" href="/static/style.css">
</head>
<body>
<h1>Hello, The Cloud!</h1>
<p> Lets Check the Weather! </p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/47acb7d74302f585/geolookup/conditions/q/IA/Cedar_Rapids.json",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});
</script>
</body>
</html>
If you hit an error first, you won't get to the alert. Try adding this logging, to make sure you aren't getting a key error:
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/47acb7d74302f585/geolookup/conditions/q/IA/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
console.log(parsed_json);
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});
I'm trying to develop a code that is able to change the font of an element dynamically by using a font file (TTF) uploaded. The code below works fine in Chrome, Opera and Firefox, but doesn't work in IE, Edge and Safari.
<html>
<head>
<style>
#my-font {
margin-top: 50px;
font-size: 20pt;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(function(){
$("#font").change(function(){
// post the font file to the php script that will move the file uploaded to the folder "fonts"
$.ajax( {
url: 'movefontfile.php',
type: 'POST',
data: new FormData($("#send")[0]),
processData: false,
contentType: false,
}).done(function(name){
// set the font face
var f = new FontFace("myfont", "url(fonts/"+name+")", {});
f.load().then(function (loadedFace) {
document.fonts.add(loadedFace);
var fptags = document.getElementById('my-font');
fptags.style.fontFamily = "myfont, sans-serif";
});
});
})
});
</script>
</head>
<body>
<form id="send">
<input type="file" id="font" name="font">
</form>
<p id="my-font">
This is a font text
</p>
</body>
</html>
This is the php code:
<?php
$name = $_FILES['font']['name'];
move_uploaded_file($_FILES['font']['tmp_name'], 'fonts/'.$name);
echo $name;
?>
Someone could help me? I need a code that works in every popular browser. Thanks.
IE and Edge don't have support for the JavaScript FontFace object. You might have better luck dynamically creating the CSS #font-face code, like so:
$.ajax( {
url: 'movefontfile.php',
type: 'POST',
data: new FormData($("#send")[0]),
processData: false,
contentType: false,
}).done(function(data){
$('<style>').text("#font-face {font-family: 'myfont'; src: url('fonts/myfont.ttf');}");
var fptags = document.getElementById('my-font');
fptags.style.fontFamily = "myfont, sans-serif";
});
Try to use the browser debugger by pressing F12 key and check the font on the <p> tag.
<p id="my-font">
Fix it on console window and update your code accordingly.
I find a solution that works in Safari and Edge, but doesn't works to IE yet.
It is very ugly, but works:
<html>
<head>
<style>
#my-font {
margin-top: 50px;
font-size: 20pt;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
var font;
$(function(){
$("#font").change(function(){
// post the font file to the php script that will move the file uploaded to the folder "fonts"
$.ajax( {
url: 'movefontfile.php',
type: 'POST',
data: new FormData($("#send")[0]),
processData: false,
contentType: false,
}).done(function(data){
$('link[rel=stylesheet][href="'+font+'.css"]').remove();
font = data;
$('head').append('<link rel="stylesheet" type="text/css" href="'+data+'.css">');
$('#my-font').css('font-family', 'myfont, sans-serif');
});
})
});
</script>
</head>
<body>
<form id="send">
<input type="file" id="font" name="font">
</form>
<p id="my-font">
This is a font text
</p>
</body>
</html>
And the PHP script:
<?php
$name = $_FILES['font']['name'];
move_uploaded_file($_FILES['font']['tmp_name'], 'fonts/'.$name);
$css = file_get_contents('font-face-aux.css');
$css = str_replace('?FONT_NAME?', $name, $css);
$f = fopen($name.'.css', 'w');
fwrite($f, $css);
fclose($f);
echo $name;
?>
And the auxiliar CSS:
#font-face {
font-family: 'myfont';
src: url('fonts/?FONT_NAME?');
}
I closely followed an AJAX tutorial ( https://www.youtube.com/watch?v=WwngGtboldU ) to learn how to prevent certain sections of a website from loading. You can see at 17:50 he clicks the links and, rather than the entire page loading, only a certain section loads in.
However, it's simply not working for me. When I click "Cats" or "Dogs", the entire page loads. It's very frustrating! Could anyone figure out what might be going wrong in my version? I've been using XAMPP, by the way, and I always test this by opening cats.php or dogs.php.
style.css
body{
background-color: aqua;
}
ul#nav {
list-style:none;
padding:0;
margin: 0 0 10px 0;
}
ul#nav li {
display:inline;
margin-right:10px;
}
header.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>History API</title>
</head>
<body>
<nav id="main">
<ul>
<li>Cats</li>
<li>Dogs</li>
</ul>
</nav>
footer.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
var nav, content, fetchAndInsert;
nav = $('nav#main');
content = $('section#content');
//Fetches and inserts content into the container
fetchAndInsert = function(href) {
$.ajax({
url: 'http://localhost/BlankApacheHistoryAPI/content' + href.split('/').pop(),
method: 'GET',
cache: false,
success: function(data){
content.html(data);
}
});
});
//User goes back/forward
$(window).on('popstate', function() {
fetchAndInsert(location.pathname);
});
nav.find('a').on('click', function(e) {
var href = $(this).attr('href');
//Manipulate history
history.pushState(null, null, href);
//Fetch and insert content
fetchAndInsert(href);
e.preventDefault();
});
});
</script>
</body>
</html>
cats.php
<?php
require 'views/header.php';
?>
<section id="content">
<?php require 'content/cats.php'; ?>
</section>
<?php
require 'views/footer.php';
?>
content/cats.php
Cats say meow
dogs.php
<?php
require 'views/header.php';
?>
<section id="content">
<?php require 'content/dogs.php'; ?>
</section>
<?php
require 'views/footer.php';
?>
content/dogs.php
Dogs say woof
I think you are missing the last forward slash:
url: 'http://localhost/BlankApacheHistoryAPI/content' + href.split('/').pop(),
should be
url: 'http://localhost/BlankApacheHistoryAPI/content/' + href.split('/').pop(),
At the end of your fetchAndInsert = function(href) you wrote }); while in fact the paranthesis should be there. Change it to }; (hint: check your developer console (F12) to see any error messages)
Remove history.pushState(null, null, href); - it's actually redirecting you to the link ("the entire page loads")