Calling a php file within a html file using javascript - javascript

I have a PHP file that outputs my google analytics tracking code from my database. But unfortunately my website front end is HTML. Is there a way using Javascript to call my file templates/google-analytics-code.php and output my google tracking code?
This is my PHP file that outputs my tracking code:
<?php
include_once"../database.php";
$qry="select * from google_analytics";
$result=mysqli_query($con,$qry) or die(mysqli_error($con));
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$google_analytics_id = $row["google_analytics_id"];
}
}
echo $google_analytics_id;
?>
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="google-site-verification" content="VFDwnGJ-4
RPz2jHchu3ARhbY2GLqkvyII4IbtAR-aP0" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.istreamradio.ie/css/bootstrap.css">
<link rel="stylesheet" href="http://www.istreamradio.ie/css/font-awesome.css">
<meta name="google-signin-client_id" content="80957862538-juiu2cgia32rn3lik36fv9a1ihc6fqof.apps.googleusercontent.com">
<link rel="stylesheet" href="http://www.istreamradio.ie/css/animate.css">
<link rel="stylesheet" href="http://www.istreamradio.ie/css/style.css">
<link rel="stylesheet" href="http://www.istreamradio.ie/css/player.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>Listen Radio</title>
<base href="/">
</head>
<body ng-app="musiclistener">
<p><span ng-include="'templates/cookiebar-settings.php'"></span>
<span ng-cloak>
<span ng-view ></span>
</span>
</p>
<div id='player-container'>
<audio controls id='music-player' src="#"></audio>
<div class='container-fluid'>
<div class='col-sm-1 col-xs-3 text-center' id='play-icon-container'>
<i class='fa fa-play' id='play-btn' ng-click="playtoogle()">
</i>
</div>
<div class='col-sm-1 center-block hidden-xs' id='podcast-icon-container'>
<img src="{{ playerthumb }}" id='play-img' class='img-responsive center-block'>
</div>
<div class='col-md-6 col-sm-4 col-xs-6' id='podcast-bar-container'>
<span style='color:#fff;position:relative;top:3px;text-transform:capitalize' ng-if="musicplayingentity">{{ musicplayingentity}}</span>
<div id='podcast-progress'>
<div id='podcast-id-value'></div>
</div>
</div>
<div class='col-md-1 col-sm-2 text-center hidden-xs' id='addons-icon-container'>
<span ng-hide="userLoggedIn">
<a href data-toggle="modal" data-target="#loginModal"><i
class='fa fa-plus pull-left'></i></a>
<a href data-toggle="modal" data-target="#loginModal"><i
class='fa fa-comment '></i></a>
</span>
<span ng-show="userLoggedIn">
<i ng-click="makeFavoritePlayer()" ng-hide="playingfav" class='fa fa-plus extrafun'></i>
<i ng-click="removeFavoritePlayer()" ng-show="playingfav" class='fa fa-check extrafun'></i>
<i ng-click="showCommentBoxPlayer()" class='fa fa-comment '></i>
</span>
<i class='fa fa-share pull-right' ng-click="shareboxPlayer()"></i>
</div>
<div class='col-sm-3 col-xs-3 text-center' id='volume-container'>
<div class='col-xs-2'>
<i class='fa fa-volume-up'></i>
</div>
<div class='col-xs-1 col-md-9'>
<div id='volume-progress'>
<div id='volume-id-value'></div>
</div>
</div>
</div>
</div>
</div>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="http://www.istreamradio.ie/ang/angular.min.js"></script>
<script src="http://www.istreamradio.ie/ang/angular-sanitize.min.js"></script>
<script src="http://www.istreamradio.ie/ang/angular-route.min.js"></script>
<script src="http://www.istreamradio.ie/ang/angular-cookies.min.js"></script>
<script src="http://www.istreamradio.ie/ang/angular-facebook-sdk.js"></script>
<script>
window.fbAsyncInit = function () {
FB.init({ appId: '195962897544265', xfbml: true, version: 'v2.8' });
};
</script>
<script src="http://www.istreamradio.ie/ang/app.js"></script>
<script src="http://www.istreamradio.ie/ang/controllers.js"></script>
<script src='http://www.istreamradio.ie/js/jquery.js'></script>
<script src='http://www.istreamradio.ie/js/bootstrap.js'></script>
<script src='http://www.istreamradio.ie/js/typed.js'></script>
<script src='http://www.istreamradio.ie/js/wow.js'></script>
<script src='http://www.istreamradio.ie/js/player.js'></script>
<script>
new WOW().init();
</script>
<script>
$(function () {
$(".typing-text").typed({
strings: ["MUSIC", "SPORTS", "BOOKS", "NEWS", "TALK"],
typeSpeed: 200,
backSpeed: 150,
loop: true
});
});
</script>
</body>
</html>

You can do that with AJAX.
<script type="text/javascript">
$.ajax({
type: "GET",
url: 'templates/google-analytics-code.php', // make sure to give this a valid path
success: function(data){
// the data returned is passed to the success function. You can do anything with it in here, like appending it to the DOM with jQuery.
$('body').append(data);
}
});
</script>
Note: You will need to have jQuery loaded for this.

The php would have to exist on a web server and be capable of listening for some kind of request (http most likely) containing GET or POST data, and respond accordingly. You can't just do it with the file system.
One option is to make your file index.php instead of index.html and echo out the html you wanted.

Related

Laravel 5.3 impossible to put script on view (autocomplete field)

I’m currently working on Laravel 5.3 for my internship.
And as you guessed, I have an annoying issue let me explain it:
On a page, I have to put an « autocomplete » field but It’s not working at all.
I have this error I can’t solve:
[Vue warn]: Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed. app.js:139
Furthermore, I need to keep the larvel « template » like the top bar with the login name, etc…
I tried a lot of solutions found on the internet but nothing worked.
I’m totally desperate, do you have any solutions ?
ps: Sorry for the awful grammar, I'm french and I'm learning, thanks for your comprehension.
selectcr.blade.php
#extends('layouts.app')
#section('content')
<!DOCTYPE html>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Selection de Compte-Rendu</div>
<div class="panel-body"> Selectionnez le client:
<input id="intervenant-name" type="text" class="form-control pd-l-50" placeholder="Recherche par nom d'entreprise">
<script src="{{asset('js/jquery-1.12.4.js')}}"></script>
<script src="{{asset('js/jquery-ui.js')}}"></script>
<script>
(function () {
src = "/prefcard/maker-search-intervenant";
$("#intervenant-name").autocomplete({
source: function (request, response)
{
$.ajax({
url: src,
dataType: "json",
data:
{
term: request.term
},
success: function (data)
{
response(data);
}
});
},
min_length: 2,
select: function (event, ui)
{
//console.log(ui.item.value);return false;
var test = ui.item.value ? ui.item.value : '';
if (test != '')
{
var url = '/prefcard/maker-search-intervenant';
var formAutocomplete = $('<form action="' + url + '" method="post">' +
'<input type="hidden" name="_token" value="{{ csrf_token() }}">' +
'<input type="text" name="term" value="' + ui.item.value + '" />' +
'</form>');
$('body').append(formAutocomplete);
formAutocomplete.submit();
}
}
});
})();
</script>
</div>
</div>
</div>
</div>
</div>
#yield('javascript')
#endsection
SelectCRController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class SelectCRController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('selectcr');
}
public function searchIntervenant(Request $request) {
$query = $request->get('term', '');
$results = DB::table('intervenant')->where('intervenantEntreprise', 'LIKE', '%' . $query . '%')->orWhere('intervenantFonction', 'LIKE', '%' . $query . '%')->take(5)->get();
$data = array();
foreach ($results as $result) {
$data[] = array('value' => $result->intervenantEntreprise . ' ' . $result->intervenantEmail, 'id' => $result->id);
}
if (count($data))
return $data;
else
return ['value' => 'No Result Found', 'id' => ''];
}
public function postSearchIntervenant(Request $request) {
//Do whatever you want to search accordingly name and then return
return view('dashboard')->with('intervenant', $intervenant);
}
}
web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
Route::get('/', function () {return view('welcome');});
Auth::routes();
Route::get('/home', 'HomeController#index');
Route::get('/configuration', 'ConfigurationController#index');
Route::get('/selectcr', 'SelectCRController#index');
Route::get('/prefcard/maker-search-intervenant', 'SelectCRController#searchIntervenant');
Route::post('/prefcard/maker-search-intervenant', 'SelectCRController#postSearchIntervenant');
Route::get('/intervenant', function () {return view('intervenant');});
Route::get('/api/intervenant/{id?}', 'IntervenantController#index');
Route::post('/api/intervenant', 'IntervenantController#store');
Route::post('/api/intervenant/{id?}', 'IntervenantController#update');
Route::delete('/api/intervenant/{id?}', 'IntervenantController#destroy');
Route::get('/utilisateur', function () {return view('utilisateur');});
Route::get('/api/utilisateur/{id?}', 'UtilisateurController#index');
Route::post('/api/utilisateur', 'UtilisateurController#store');
Route::post('/api/utilisateur/{id?}', 'UtilisateurController#update');
Route::delete('/api/utilisateur/{id?}', 'UtilisateurController#destroy');
Route::post('register', 'Auth\RegisterController#register');
//Route::auth();
app.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Styles -->
<link href="/css/app.css" rel="stylesheet">
<!-- Scripts -->
<script>
window.Laravel = <?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>
</script>
</head>
<body>
<div id="app">
<nav class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<!-- Collapsed Hamburger -->
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse">
<span class="sr-only">Toggle Navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- Branding Image -->
<a class="navbar-brand" href="{{ url('/') }}">
{{ config('app.name', 'Laravel') }}
</a>
</div>
<div class="collapse navbar-collapse" id="app-navbar-collapse">
<!-- Left Side Of Navbar -->
<ul class="nav navbar-nav">
</ul>
<!-- Right Side Of Navbar -->
<ul class="nav navbar-nav navbar-right">
<!-- Authentication Links -->
#if (Auth::guest())
<li>Login</li>
#else
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
{{ Auth::user()->name }} <span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="{{ url('/logout') }}"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
Logout
</a>
<form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
</li>
</ul>
</li>
#endif
</ul>
</div>
</div>
</nav>
#yield('content')
</div>
<!-- Scripts -->
<script src="/js/app.js"></script>
</body>
</html>
UPDATE
Now and with some modifications the error disappeared but the scripts are not working at all.
<!DOCTYPE html>
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Selection de Compte-Rendu</div>
<div class="panel-body"> Selectionnez le client:
<input id="intervenant-name" type="text" class="form-control pd-l-50" placeholder="Recherche par nom d'entreprise">
</div>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script src="{{asset('js/jquery-1.12.4.js')}}"></script>
<script src="{{asset('js/jquery-ui.js')}}"></script>
<script>
(function () {
src = "/prefcard/maker-search-intervenant";
$("#intervenant-name").autocomplete({
source: function (request, response)
{
$.ajax({
url: src,
dataType: "json",
data:
{
term: request.term
},
success: function (data)
{
response(data);
}
});
},
min_length: 2,
select: function (event, ui)
{
//console.log(ui.item.value);return false;
var test = ui.item.value ? ui.item.value : '';
if (test != '')
{
var url = '/prefcard/maker-search-intervenant';
var formAutocomplete = $('<form action="' + url + '" method="post">' +
'<input type="hidden" name="_token" value="{{ csrf_token() }}">' +
'<input type="text" name="term" value="' + ui.item.value + '" />' +
'</form>');
$('body').append(formAutocomplete);
formAutocomplete.submit();
}
}
});
})();
</script>
#endsection
#yield('javascript')
1) You have a Vuejs error (add tag plz). Looks like you need to move script tags out of vuejs container.
2) !DOCTYPE html must be at the top of your document, not in the middle.
Blade is powerful to "inject" your view into a skeletonized html page. If you need some clean way to call your layout/app.blade.php, I made an example right below :
layout/app.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>#yield('title')</title>
#yield('links')
</head>
<body>
#yield('content')
<!-- Here is the perfect place for the javascript libraries that you think will be used in ANY page -->
<script src="jquery/jquery.min.js"></script> <!-- for example if you use jQuery -->
<script src="bootstrap/js/bootstrap.min.js"></script> <!-- same if you need Bootstrap-Twitter-3 in any pages -->
<!-- And then, your specific scripts are hooked below -->
#yield('scripts')
</body>
</html>
Then, it is as simple as it looks to "inject" your content inside your <body> tag, like following :
selectcr.blade.php (juste an example)
#extends('layout.app')
<!-- Some additionnals css, specific to this page -->
#section('links')
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
#ensection
#section('title')
My awesome title
#endsection
#section('content')
<div class="container">
<div class="row">
<div class="col-lg-12">
<h3>Greetings user !</h3>
</div>
<div class="col-lg-12">
<div class="form">
<input type="text" />
<button type="submit">Go !</button>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script>
alert('This is my custom javascript !');
</script>
#endsection
So, whenever Blade encounters a #section tags, it automatically injects its content right inside the place it belongs, meaning in every #yield that represent this section.
Hope it helps.
Move #yield('javascript') out of the section put if after the #endsection tag, you could also just use #end.
Comment out all scripts within your section Tag also! because this is what the error is saying.
TRY:
All your script code should be inside
#section('scripts') .... #endsection.
And also please close content section before your javascript.
Solved it, I made a special "app.blade.php" just for the specified view and put all my scripts in it.
Not very beautiful, but It's working.

How to show message that user is already registered in html through php?

I have an HTML form in which a user enter his/her email id to register everything is working great it checks the valid email id and also registered the email id ! But when I applied new code to check that the user is already registered or not it didn't work !!
Below is my Html page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sign Up - MOBTRICKS</title>
<!-- CSS -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Lobster">
<link rel='stylesheet' href='http://fonts.googleapis.com/css?family=Lato:400,700'>
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="assets/css/style.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Favicon and touch icons -->
<link rel="shortcut icon" href="assets/ico/fa.png">
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<!-- <script type="text/javascript">
function greeting(){
alert("Welcome ! Your Email : " + document.forms["form"]["email"].value + " has been registered under our records successfully !")
}
</script> -->
</head>
<body>
<!-- Header -->
<div class="container">
<div class="row header">
<div class="col-sm-4 logo">
<h1><a href=#>PQR</a> <span>.</span></h1>
</div>
<div class="col-sm-8 call-us">
<p>Mob: <span>+91-9530803237</span> | email: <span>ab.creations27#gmail.com</span>
</p>
</div>
</div>
</div>
<!-- Coming Soon -->
<div class="coming-soon">
<div class="inner-bg">
<div class="container">
<div class="row">
<div class="col-sm-12">
<center>
<i class="fa fa-cog fa-spin fa-3x fa-fw"></i>
<span class="sr-only">Loading...</span>
<h2>We're Coming Soon</h2>
<p>We are working very hard on the new version of our site. It will bring a lot of new features. Stay tuned!</p>
<div class="timer">
<div class="days-wrapper">
<span class="days"></span>
<br>days
</div>
<div class="hours-wrapper">
<span class="hours"></span>
<br>hours
</div>
<div class="minutes-wrapper">
<span class="minutes"></span>
<br>minutes
</div>
<div class="seconds-wrapper">
<span class="seconds"></span>
<br>seconds
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Content -->
<div class="container">
<div class="row">
<div class="col-sm-12 subscribe">
<h3>Subscribe to our newsletter !!</h3>
<p>Sign up now to our newsletter and you'll be one of the first to know when the site is ready:</p>
<form class="form-inline" role="form" action="assets/subscribe.php" method="post">
<div class="form-group">
<label class="sr-only" for="subscribe-email">Email address</label>
<input type="text" name="email" placeholder="Enter your email..." class="subscribe-email form-control" id="subscribe-email">
</div>
<button type="submit" class="btn">Subscribe</button>
</form>
***
<div class="success-message"></div>
<div class="error-message"></div>***
</div>
</div>
<div class="row">
<div class="col-sm-12 social">
<i class="fa fa-facebook"></i>
<i class="fa fa-twitter"></i>
<a href="https://github.com/ashu271994" data-toggle="tooltip" data-placement="top" title="GitHub">
<i class="fa fa-github"></i>
</a>
<i class="fa fa-google-plus"></i>
<i class="fa fa-pinterest"></i>
<i class="fa fa-envelope-o"></i>
</div>
</div>
</div>
<!-- Footer -->
<footer id="footer">
<ul class="copyright">
<li>© ASHISH BHARWAL
</li>
<li>Credits: AB-Creations
</li>
</ul>
</footer>
<!-- Javascript -->
<script src="assets/js/jquery-1.11.1.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
ipt src="assets/js/jquery.backstretch.min.js"></script>
<script src="assets/js/jquery.countdown.min.js"></script>
<script src="assets/js/scripts.js"></script>
<!--[if lt IE 10]>
<script src="assets/js/placeholder.js"></script>
<![endif]-->
</body>
</html>
Below is my Subscriber.php page
<?php
// Email address verification
function isEmail($email)
{
return (preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]| [[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
}
if ($_POST) {
// Enter the email where you want to receive the notification when someone subscribes
$emailTo = 'ab.creations27#gmail.com';
$subscriber_email = addslashes(trim($_POST['email']));
if (!isEmail($subscriber_email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Insert a valid email address!';
echo json_encode($array);
// $msg="wrong answer";
// echo "<script type='text/javascript'>alert('$msg');</script>";
} else {
$host = "somehostname";
$user = "username";
$pwd = "password";
$db = "demo1";
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$sql_insert = "SELECT * FROM demotable WHERE subs='$subscriber_email'";
$stmt1 = $conn->prepare($sql_insert);
$stmt1->execute();
$result = $stmt1->fetchColumn();
if ($result == 0) {
$sql_insert = "INSERT INTO demotable (subs)
VALUES ('$subscriber_email')";
$stmt = $conn->prepare($sql_insert);
$stmt->execute();
$array = array();
$array['valid'] = 1;
$array['message'] = "Your Email : $subscriber_email has been registered with us ! Thanks for your subscription!";
echo json_encode($array);
} else {
$array = array();
$array['valid'] = 2;
$array['message'] = "You are already registered !!";
echo json_encode($array);
}
}
catch (Exception $e) {
die(var_dump($e));
}
}
}
?>
Now what is happening when I tried to add an invalid email id then it shows Invalid Email id in marked in HTML page but when I added a new user then add the data in my table and show message but in case of the user who is already registered it didn't show any message !! I also tried to make new functions having "echo json_encode($array)"; But this also won't work !! Tell me what am I missing or what's my mistake !! I am trying to sort it from the last 3 days !!
my scripts.js code below
$('.subscribe form').submit(function(e) {
e.preventDefault();
var postdata = $('.subscribe form').serialize();
$.ajax({
type: 'POST',
url: 'assets/subscribe.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 0) {
$('.success-message').hide();
$('.error-message').hide();
$('.error-message').html(json.message);
$('.error-message').fadeIn();
}
else if (json.valid == 1){
$('.error-message').hide();
$('.success-message').hide();
$('.subscribe form').hide();
$('.success-message').html(json.message);
$('.success-message').fadeIn();
}
else {
$('.error-message').hide().empty();
$('.success-message').hide().empty();
$('.subscribe form').hide();
$('.success-message').html(json.message);
$('.success-message').fadeIn();
}
}
});
});
Try changing
$result = $stmt1->fetchColumn();
to
$result = $stmt1->num_rows;
see if that works.
Finally got it working. The error was simple but yet difficult to find. lolz
$sql_insert = "SELECT * FROM demotable WHERE subs='$subscriber_email'";
should be like
** $sql_insert = "SELECT COUNT(*) FROM demotable WHERE subs='$subscriber_email'";**
Thank you all for your views. :)

Update Status in Highcharts

I've been trying to find a way to update the chart data within highcharts every 5 second. I'm collecting data from an MSSQL server using PHP and have been runnin gthis successfully. I'm struggling with the calling of th latest data and passing it through to the chart.
Here is the php file planlivephp.php:
<?php
// CONNECT TO LOCAL SERVER
require_once('server.php');
// DATA TABLE 12a - PLAN DATA POINTS
$tsql12a = "SELECT * FROM AggCurrentPlanUtilStatus";
$stmt12a = sqlsrv_query( $conn, $tsql12a);
$occ = array(0=>'#009900', 1=>'#FF0000'); // GREEN RED
$data12a = "";
while( $row = sqlsrv_fetch_array( $stmt12a, SQLSRV_FETCH_NUMERIC)){
$data12a .= "{name: ";
$data12a .= "'$row[2]',";
$data12a .= " color: '";
$data12a .= $occ[$row[3]];
$data12a .= "', x: $row[6],";
$data12a .= " y: $row[7]";
$data12a .= "},";
}
$data12a = substr($data12a,0,strlen($data12a)-1);
// ECHO STATEMENTS TO CHECK DATA IF WORKING PROPERLY
// echo "$data12a";
// CLOSE THE CONNECTION TO THE SERVER
sqlsrv_free_stmt( $stmt12a);
sqlsrv_close( $conn); // closes the connection
?>
I've then added a getStatus function with a setTimeout of 5 seconds at the begining of the highcharts script to call the php file and load it to the div id.
$(function ) {
getStatus();
});
function getStatus(){
$('#chart1').load('planlivephp.php');
setTimeout("getStatus()",5000);
}
Here is the full code altogether with the javascript feeding the div id "#chart1" in the html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Mosaddek">
<meta name="keyword" content="FlatLab, Dashboard, Bootstrap, Admin, Template, Theme, Responsive, Fluid, Retina">
<link rel="shortcut icon" href="img/favicon.png">
<title>INOVU Dashboard</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-reset.css" rel="stylesheet">
<!--external css-->
<link href="assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
<!--right slidebar-->
<link href="css/slidebars.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="css/style.css" rel="stylesheet">
<link href="css/style-responsive.css" rel="stylesheet" />
<!-- HTML5 shim and Respond.js IE8 support of HTML5 tooltipss and media queries -->
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<section id="container" class="sidebar-closed"> <!-- LEAVE BLANK "" IF YOU WNAT THE MENU TO ALWAYS APPEAR ON OPENNING
<!--header start-->
<header class="header white-bg">
<!--<div class="sidebar-toggle-box">
<div data-original-title="Toggle Navigation" data-placement="right" class="fa fa-bars tooltips"></div>
</div>
<!--logo start-->
<!-- Ino<span>Vu</span> -->
<a class="navbar-brand" href="../index.html"><img src="../VUF/img/inovu_logo.png" alt="" style="height: 26px"></a>
<!--logo end-->
<div class="nav notify-row" id="top_menu">
<!-- DASHBOARD ICON BUTTONS START -->
<ul class="nav top-menu">
<!--home page-->
<li data-original-title="Home" data-placement="right" class="dropdown tooltips">
<a href="../index.html">
<i class="fa fa-home"></i>
</a>
</li>
<!--home page end-->
<!--map page-->
<li data-original-title="Location Map" data-placement="right" class="dropdown tooltips">
<a href="location.php">
<i class="fa fa-map-marker"></i>
</a>
</li>
<!--map page end-->
<!--floor plan page-->
<li data-original-title="Floor Plan" data-placement="right" class="dropdown tooltips">
<a href="plan.php">
<i class="fa fa-file-o"></i>
</a>
</li>
<!--floor plan end-->
<!--dashboard page-->
<li data-original-title="Dashboard" data-placement="right" class="dropdown tooltips">
<a href="dashboard.php">
<i class="fa fa-bar-chart-o"></i>
</a>
</li>
<!--dashboard end-->
</ul>
<!-- DASHBOARD ICON BUTTONS END-->
</div>
<div class="top-nav ">
<ul class="nav pull-right top-menu">
<!--<li>
<input type="text" class="form-control search" placeholder="Search">
</li>-->
<!-- user login dropdown start-->
<li class="dropdown">
<a data-toggle="dropdown" class="dropdown-toggle" href="#">
<img alt="" src="img/avatar1_small.jpg">
<span class="username">Dave Dash</span>
<b class="caret"></b>
</a>
<ul class="dropdown-menu extended logout">
<div class="log-arrow-up"></div>
<li><i class=" fa fa-suitcase"></i>Profile</li>
<li><i class="fa fa-cog"></i> Settings</li>
<li><i class="fa fa-bell-o"></i> Notification</li>
<li><i class="fa fa-key"></i> Log Out</li>
</ul>
</li>
<!-- user login dropdown end -->
</ul>
</div>
</header>
<!--header end-->
<script src="jquery.min.js" type="text/javascript"></script>
<!--main content start-->
<section id="main-content">
<section class="wrapper site-min-height">
<!-- portlet page start-->
<div class="row-fluid" id="draggable_portlets">
<div class="sortable">
<!-- BEGIN Portlet PORTLET-->
<div class="panel">
<header class="panel-heading">HSSMI Floor Plan
<span class="tools pull-right">
</span>
</header>
<div class="panel-body">
<div id="chart1" style="width: 1000px; height: '100%';"></div>
<div id="drag"></div>
<div id="drop"></div>
</div>
</div>
<!-- END Portlet PORTLET-->
</div>
</div>
<!-- page end-->
</section>
</section>
<!--main content end-->
<!--footer start-->
<footer class="site-footer">
<div class="text-center">
© 2015 INOVU
<SCRIPT language="Javascript">
document.write("Refreshed: " + document.lastModified +"");
</SCRIPT>
<a href="#" class="go-top">
<i class="fa fa-angle-up"></i>
</a>
</div>
</footer>
<!--footer end-->
</section>
<!-- js placed at the end of the document so the pages load faster -->
<script src="js/jquery.js"></script>
<script src="assets/jquery-ui/jquery-ui-1.10.1.custom.min.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js"></script>
<script class="include" type="text/javascript" src="js/jquery.dcjqaccordion.2.7.js"></script>
<script src="js/jquery.scrollTo.min.js"></script>
<script src="js/jquery.nicescroll.js" type="text/javascript"></script>
<script src="js/respond.min.js" ></script>
<script src="js/draggable-portlet.js"></script>
<!--right slidebar-->
<script src="js/slidebars.min.js"></script>
<!--common script for all pages-->
<script src="js/common-scripts.js"></script>
<script>
jQuery(document).ready(function() {
DraggablePortlet.init();
});
</script>
<!-- HIGHCHART SCRIPT FILES -->
<!-- <link rel="stylesheet" href="/Highcharts/css/HcHSSMImain.css"> -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="/Highcharts/js/highcharts.js"></script>
<script src="/Highcharts/js/highcharts-more.js"></script>
<script src="/Highcharts/js/modules/heatmap.js"></script>
<script src="/Highcharts/js/modules/drilldown.js"></script>
<script src="/Highcharts/js/modules/exporting.js"></script>
<script src="/Highcharts/js/draggable-points.js"></script>
<script src="/Highcharts/js/export-csvRob.js"></script>
<script type="text/javascript"> // PLAN INDICATING OCCUPIED OR UNOCCUPIED DESKS
$(function ) {
getStatus();
});
function getStatus(){
$('#chart1').load('planlivephp.php');
setTimeout("getStatus()",5000);
}
$('#chart1').highcharts({
chart: {
plotBackgroundImage: '/Highcharts/graphics/HSSMIPLAN.png',
height: 600,
animation: false
},
credits: {
enabled: false
},
title: {
text: null //'HSSMI Occupancy Plan (Live)'
},
xAxis: {
min: 0,
max: 1000,
labels: {enabled:false},
lineColor: 'transparent',
minorTickLength: 0,
tickLength: 0
},
yAxis: {
min: 0,
max: 600,
title: false,
gridLineWidth: 0,
labels: {enabled:false},
lineColor: 'transparent',
},
legend: {
enabled: false
},
plotOptions: {
series: {
cursor: 'ns-resize',
point: {
events: {
drag: function (e) {
$('#drag').html(
'Dragging <b>' + this.series.name + '</b>, <b>' + this.category + '</b> to <b>' + Highcharts.numberFormat(e.newY, 0) + '</b>');
},
drop: function () {
$('#drop').html(
'In <b>' + this.series.name + '</b>, <b>' + this.category + '</b> was set to <b>' + Highcharts.numberFormat(this.y, 0) + '</b>');
}
}
},
//stickyTracking: false
},
},
tooltip: {
borderColor: 'rgb(43, 110, 151)',
formatter: function () {
return 'Sensor: <b>'+ this.point.name + '</b><br>X Value: <b>' +
this.point.x + '<br>Y Value: <b>' + this.point.y +'</b>';
}
},
series: [{
type: 'bubble',
minSize: 25,
maxSize: 25,
cursor: 'pointer',
draggableX: false,
draggableY: false,
data: [<?php echo $data12a?>]
}]
});
$('#getcsv').click(function () {
var csv = "Series;Name;X;Y\n";
$.each(Highcharts.charts[0].series, function(i,s){
$.each(s.points, function(j,p){
csv += s.name + ";" + p.name + ";" + p.x + ";" + p.y + "\n";
});
});
alert(csv);
});
});
</script>
</body>
</html>
Any suggestions or corrections you could put forward.
Thanks
Rob

Jquery: How to make objects inside <div> to hide or show on click?

I want to make a webpage in which three different contents show/hide when a button is clicked. The code is shown below.
I want the same page to show three contents:
only a search bar when button 'search' is clicked,
only the result of the search after a search is done or when the button 'results' is clicked, and
only the visualization of the search when one specific outcome of the results is chosen, or when the button 'visualization' is clicked.
Right now I only know how to show the results in different pages, not in the same one hiding what I don't want.
Code is below.
Thanks
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="docs-assets/ico/favicon.png">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link href="css/jumbotron-narrow.css" rel="stylesheet">
<link href="css/jquery.dataTables.css" rel="stylesheet">
<link rel="shortcut icon" type="image/ico" href="" />
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript" language="javascript" src="js/libs/jquery-2.0.3.min.js"></script>
<script type="text/javascript" language="javascript" src="js/libs/jquery.sprintf.js"></script>
<script type="text/javascript" language="javascript" src="js/libs/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
//xmakeTable("treaty");
});
makeTable = function(query) {
var q = encodeURIComponent(query)
$('#example').dataTable({
"oLanguage": {"sSearch": "Filter results:"},
"bProcessing": true,
"bDestroy":true,
"sAjaxSource": $.sprintf('http://leela.sscnet.ucla.edu/voteview/searchdt?q=%s',q),
"aoColumns":[{"mData":"id", "sWidth": "20px", "sTitle":"ID"},
{"mData":"chamber", "sWidth": "10px", "sTitle":"Chamber"},
{"mData":"date", "sWidth": "85px", "sTitle":"Date"},
{"mData":"yea","sTitle":"Vote","sWidth":"80px"},
{"mData":"descriptionShort", "sWidth": "200px","sTitle":"Description"}],
"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
$('td:eq(0)', nRow).html(
$.sprintf('%s',aData['id'],aData['id'])).attr("title","Click to explore this vote");
$('td:eq(3)', nRow).html(
$.sprintf('%s-%s',aData['yea'],aData['no']));
$('td:eq(4)', nRow).attr("title",aData['description'])
return nRow; }
});
}
searchvotes = function() {
$('#example').empty();
makeTable($('#qqtext').val());
};
</script>
</head>
<body>
<div class="container">
<div class="header">
<ul class="nav nav-pills pull-right">
<li>Home</li>
<li class="active">Search</li>
<li>Contact</li>
</ul>
<h3 class="text-muted">VoteView</h3>
</div>
<div class="jumbotron">
<div class="container">
<div>
<h3 align="center">Search for Roll Calls</h3>
<div class="col-sm-12">
<input type="search" class="form-control" placeholder="Search" id="qqtext" onchange="searchvotes()"></input>
</div>
</div>
<br>
<div>
<div class="table-responsive">
<table id="example" class="table table-striped"></table>
</div>
</div>
<div>
<div class="col-lg-14 col-md-14 portfolio-item" id="example">
</div>
</div>
</div>
</div>
<div align="center">
<button type="button" class="btn btn-primary btn-lg">
<span class="glyphicon glyphicon-search"></span><br><font color="white">Search</font>
</button>
<button type="button" class="btn btn-success btn-lg">
<span class="glyphicon glyphicon-list"></span><br><font color="white">Results</font>
</button>
<button type="button" class="btn btn-warning btn-lg">
<span class="glyphicon glyphicon-eye-open"></span><br><font color="white">Visualize</font>
</button>
</div>
<br>
<hr>
<p></p>
<footer>
<p>Example</p>
</footer>
</div>
</body>
</html>
If one tries a search with this code, the code should show results, but not the way I expect.
Thanks
Probably not the solution but some hint to get there. Given this:
<ul>
<li class="collapsable"><h2>Release 3.0</h2>
<ul>
<li><h3>Allgemeine Übersicht</h3>
<p>Text ....
</li>
</ul>
</li>
....
</ul>
I do:
<script type="text/javascript">
jQuery(document).ready( function () {
jQuery('.collapsable').click(function () {
jQuery(this).children('ul').first().toggle("slow");
});
});
</script>
And
<style>
li.collapsable ul {
display: none;
}
</style>
A Click on the headline opens the <ul> and closes it again on next click (Actually, there is a lot of text in there and thus the list is very long)
Firstly add an Id to your buttons to make things a bit easier
<button id="btnSearch" type="button" class="btn btn-warning btn-lg" />
<button id="btnResult" type="button" class="btn btn-warning btn-lg" />
<button id="btnVisual" type="button" class="btn btn-warning btn-lg" />
then make sure that you have the three mark-up sections on the page wrapped inside it's own div with an Id on each div.
<div id="search">
...
</div>
<div id="result">
...
</div>
<div id="visual">
...
</div>
In your JavaScript, set-up page for the initial conditions and handle the clicks on the buttons as required. In your search and visualisation functions just show and hide the appropriate div(s) for the conditions your require using JQuery's show() and hide() functions.
It may go something like this - just tweaks this snippet as required, to suit your actual scenario.
function reset() {
$('#search').show();
$('#result').hide();
$('#visual').hide();
}
function init() {
var self = this;
// button clicks
$('#search').click(function () {
self.reset();
});
$('#results').click(function () {
self.search();
});
$('#visual').click(function () {
self.visualize();
});
}
function search() {
// Do search and set results table contents
$('#search').hide();
$('#result').show();
}
function visualize() {
// Do visualisation and set content
$('#result').hide();
$('#visual').show();
}
$(document).ready( function () {
this.reset();
this.init();
)};
You need to use toggle() It will hide element if its current status is visible and show if it is currently hidden:
$('.collapsable').click(function () {
$(this).children('ul').first().toggle();
});

Uncaught TypeError implementing Fuelux wizard

I'm trying to implement Fuelux's wizard feature and have hit a brick wall. I am simply trying to achieve a working replica of the live example but keep receiving the error in my console:
Uncaught TypeError: Object [object Object] has no method 'wizard'
I am finding a lot of the documentation a little overwhelming and would appreciate some clarity on the subject in plain [or plainer] English.
My markup is:
<!DOCTYPE html>
<html class="no-js fuelux">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>E-Learning</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/fuelux.min.css">
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="container">
<div id="my-wizard" class="wizard">
<ul class="steps">
<li data-target="#step1" class="active"><span class="badge badge-info">1</span>Step 1<span class="chevron"></span></li>
<li data-target="#step2"><span class="badge">2</span>Step 2<span class="chevron"></span></li>
<li data-target="#step3"><span class="badge">3</span>Step 3<span class="chevron"></span></li>
<li data-target="#step4"><span class="badge">4</span>Step 4<span class="chevron"></span></li>
<li data-target="#step5"><span class="badge">5</span>Step 5<span class="chevron"></span></li>
</ul>
<div class="actions">
<button class="btn btn-mini btn-prev"> <i class="icon-arrow-left"></i>Prev</button>
<button class="btn btn-mini btn-next" data-last="Finish">Next<i class="icon-arrow-right"></i></button>
</div>
</div>
<div class="step-content">
<div class="step-pane active" id="step1">
...
</div>
<div class="step-pane" id="step2">
...
</div>
<div class="step-pane" id="step3">
...
</div>
</div>
</div>
<script src="js/vendor/jquery-1.9.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/require.js"></script>
<script src="js/wizard.js"></script>
<script>
$(document).ready(function(){
$('#my-wizard').on('change', function(e, data) {
console.log('change');
if(data.step===3 && data.direction==='next') {
// return e.preventDefault();
}
});
$('#my-wizard').on('changed', function(e, data) {
console.log('changed');
});
$('#my-wizard').on('finished', function(e, data) {
console.log('finished');
});
$('.btn-prev').on('click', function() {
console.log('prev');
$('#my-wizard').wizard('previous');
});
$('.btn-next').on('click', function() {
console.log('next');
$('#my-wizard').wizard('next','foo');
});
});
</script>
</body>
</html>
So close! For both the CSS and JS since Fuel UX includes Bootstrap you simply include Fuel UX in place of Boostrap and you get all of Bootstrap plus Fuel UX:
<link rel="stylesheet" href="https://fuelcdn.com/fuelux/2.3/css/fuelux.min.css">
<script src="https://fuelcdn.com/fuelux/2.3/loader.min.js"></script>
Your template looks great and with just the above modifications, plus removing a couple of lines that were causing double-processing, this works just as expected. See the full example here:
Gist: https://gist.github.com/adamalex/5412079
Live example: http://bl.ocks.org/adamalex/5412079

Categories

Resources