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

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.

Related

call a js function inside a blade file in laravel

I am following this jQuery tutorial and trying to replicate this inside my laravel project. I cannot call the getMovie() function defined inside movie-info.js to work when movie.blade.php view is loaded. The routes are properly assigned, and I do not get any error but the console print in getMovie() is not accessed. What am I doing wrong?
I used ziggy library to call the named routes.
app.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Movie Info</title>
#routes
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootswatch/4.5.2/cyborg/bootstrap.min.css"
integrity="sha384-nEnU7Ae+3lD52AK+RGNzgieBWMnEfgTbRHIwEvp1XXPdqdO6uLTd/NwXbzboqjc2" crossorigin="anonymous">
<link rel="stylesheet" href="{{ asset('css/dist/movie-info.css') }} ">
</head>
<body>
<nav class="navbar navbar-default>">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="index.html">MovieInfo</a>
</div>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h3 class="text-center">Search for any movie</h3>
<form id="searchForm">
<input type="text" class="form-control" id="searchText" placeholder="Search movie">
</form>
</div>
</div>
<div class="container">
#yield('content')
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="{{ asset('js/dist/vendor.js') }}"></script>
<script src="{{ asset('js/dist/manifest.js') }}"></script>
<script src="{{ asset('js/dist/movie-info.js') }}">
#yield('slug')
</script>
</body>
</html>
index.blade.php
#extends('layouts.app')
#section('content')
<div id="movies" class="row"></div>
#endsection
movie.blade.php
#extends('layouts.app')
#section('content')
<div id="movie" class="row"></div>
#endsection
#section('slug')
getMovie();
#endsection
movie-info.js
import $ from 'jquery';
$(() => {
$('#searchForm').on('submit', (e) => {
let searchText = $('#searchText').val();
console.log(searchText);
getMovies(searchText);
e.preventDefault();
});
$('#movies').on('click', '.movie-details', (e) => {
const elementID = e.target.id;
const imdbid = $('#' + elementID).data('imdbid'); //custom attribute
console.log(elementID, imdbid);
movieSelected(imdbid);
});
});
function getMovies(searchText) {
axios.get('http://www.omdbapi.com?s=' + searchText + '&apikey=thewdb')
.then((response) => {
console.log(response);
let movies = response.data.Search;
let output = "";
$.each(movies, (index, movie) => {
output += `
<div class="col-md-3">
<div class="well text-center">
<img src="${movie.Poster}">
<h5>${movie.Title}</h5>
<a data-imdbid='${movie.imdbID}' class="btn btn-primary movie-details" id="movie_${movie.imdbID}" href="#">Movie Details</a>
</div>
</div>
`;
});
$('#movies').html(output);
})
.catch((err) => {
console.log(err);
});
}
function movieSelected(id) {
sessionStorage.setItem('movieId', id); //pass data from one page to another
window.location.href = route('show-movie-details');
console.log('my route', route('show-movie-details'));
// getMovie();
return false;
}
function getMovie() {
console.log("in get movie");
}
It's because you call getMovie() inside a script tag with src attribute. Just move it to another script tag without src then it will work as expected. Something like:
...
<script src="{{ asset('js/dist/movie-info.js') }}"></script>
<script>
#yield('slug')
</script>
...
You can get more info here: What does a script-Tag with src AND content mean?.

Jquery Ajax submit() not firing in django model form

I've tried looking up online, rewriting the code but the submit() won't fire but when I use a click event, it fire an calls the callback and the ajax() runs. I cannot figure out what's really wrong with the code even after going through so many tutorials and documentation online.
Here's the code:
HTML template with the form
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- site icon -->
<link rel="icon" href="{% static 'img/question.png' %}">
<!-- Bootstrap core CSS -->
<link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<!-- Font Awesome -->
<link href="{% static 'css/font-awesome.min.css' %}" rel="stylesheet">
<!-- Endless -->
<link href="{% static 'css/endless.min.css' %}" rel="stylesheet">
</head>
<body>
<div class="login-wrapper">
<div class="text-center">
<span>
<img src="{% static 'img/question.png' %}" style="height: 100px; width: 100px; border-radius: 50%;">
</span>
</div>
<div class="text-center">
<h2 class="fadeInUp animation-delay8" style="font-weight:bold">
<span class="text-success">CitiSpy User Login</span>
</h2>
</div>
<div class="login-widget animation-delay1">
<div class="panel panel-default">
<div class="panel-heading clearfix">
<div class="pull-left">
<i class="fa fa-lock fa-lg"></i> Login
</div>
</div>
<div class="panel-body">
<div id="login-form-main-message"></div>
<form class="form-login" id="login_form" method="POST">
{% csrf_token %}
<div id="form_content">
{{ form.non_field_errors }}
<div class="form-group">
{{ form.email.errors }}
<label for="{{ form.email.id_for_label }}">{{ form.email.label }}</label>
{{ form.email }}
</div>
<div class="form-group">
{{ form.password.errors }}
<label for="{{ form.password.id_for_label }}">{{ form.password.label }}</label>
{{ form.password }}
</div>
<div class="seperator"></div>
<hr/>
<div class="form-group">
<!-- <button class="btn btn-success btn-sm bounceIn animation-delay5 login-link pull-right" type="submit" id="id_submit">
<i class="fa fa-sign-in"></i>
Login
</button> -->
<a type="submit" class="btn btn-success btn-sm bounceIn animation-delay5 login-link pull-right" id="login_submit" href="#"> -->
<i class="fa fa-sign-in"></i>
Login
</a>
</div>
</div>
</form>
</div>
</div><!-- /panel -->
</div><!-- /login-widget -->
</div><!-- /login-wrapper -->
<!-- Jquery -->
<script src="{% static 'js/jquery-1.10.2.min.js' %}"></script>
<!-- Bootstrap -->
<script src="{% static 'bootstrap/js/bootstrap.js' %}"></script>
<!-- Pace -->
<script src="{% static 'js/uncompressed/pace.js' %}"></script>
<!-- Popup Overlay -->
<script src="{% static 'js/jquery.popupoverlay.min.js' %}"></script>
<!-- Slimscroll -->
<script src="{% static 'js/jquery.slimscroll.min.js' %}"></script>
<!-- Modernizr -->
<script src="{% static 'js/modernizr.min.js' %}"></script>
<!-- Cookie -->
<script src="{% static 'js/jquery.cookie.min.js' %}"></script>
<!-- Endless -->
<script src="{% static 'js/endless/endless.js' %}"></script>
<!--login js-->
<script src="{% static 'js/accounts/login_1.js' %}"></script>
</body>
</html>
JavaScript
$(document).ready(function(){
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var $csrf_token = {
name: "csrfmiddlewaretoken",
value: getCookie('csrftoken')
};
var $myId = $("#login_form >#form_content > .form-group > button").attr('class');
console.log($myId);
$("#login_form").submit(function(event){
console.log("I am in submit");
event.preventDefault();
var $form_data = $(this).serializeArray();
$form_data.push($csrf_token);
$.ajax({
type: 'POST',
data: $form_data,
cache: false,
dataType: 'json',
url: '/accounts/userLogin/',
beforeSend: function(){
$("#login-form-main-message").css("display", "block").html("<div class='alert alert-info'><img height=\"24px;\" src=\"{% static '/images/double-ring.gif' %}\" alt=\"loading\" /> Please wait...</div>");
$("#form_content").css("display", "none");
},
success: function(data){
if (data.status === "ok"){
if (data.to === "verify") {
//redirect to account verification
} else {
if (data.to === "user") {
//redirect to user account
$("#login-form-main-message").css("display", "block").html("<div class='alert alert-info'><img height=\"24px;\" src=\"{% static '/images/double-ring.gif' %}\" alt=\"loading\" /> Success! login you in, please wait...</div>");
$("#form_content").css("display", "none");
}else{
$("#login-form-main-message").css("display", "block").html("<div class='alert alert-info'><img height=\"24px;\" src=\"{% static '/images/double-ring.gif' %}\" alt=\"loading\" /> Success! login you in, please wait...</div>");
$("#form_content").css("display", "none");
location.href = '/em_dept/dashboard/';
}
}
}
},
error:function(xhr,errmsg,err){
console.log("error error error!!!");
console.log(xhr.status + ": " + xhr.responseText);
}
});
// return false;
});
});
The View rendering the form
#method_decorator(csrf_protect, name='post')
class UserLogin(LoginView):
"""docstring for UserLogin"""
template_name = 'accounts/login.html'
# authentication_form = LoginForm()
def get(self, request):
'''a func to work on the request.POST'''
print("getting the form for you ")
form = LoginForm()
return render(request,self.template_name,{'form':form})
def post(self, request):
form = LoginForm(request.POST)
print("go the data for you")
if request.is_ajax():
print("entered form")
if form.is_valid():
print("form valid")
email = form.cleaned_data['email']
try:
user = User.objects.get(email=email)
print("user obj", user)
if user.check_password(form.cleaned_data['password']):
# 0-super admin, 1-dept admin,2-dept staff, 3-end user
print("correct password")
if user.account_type == 4:
if user.last_login == None or user.last_login == '':
to = "verify"
else:
to = "user"
else:
if user.account_type == 2:
to = 'dept_admin'
elif user.account_type == 3:
to = 'dept_staff'
elif user.account_type == 1:
to = 'super_user'
else:
to = None
res = {'status':'ok', 'error':False, 'acc_type':to, 'data':user.email}
else:
print("incorrect password")
res = {'status':'fail', 'error':'incorrect password'}
except Exception as e:
print("User not found!", e)
res = {'status':'fail', 'error':'account not found'}
else:
print("form valid")
res = {'status':'fail', 'error':form.errors}
return JsonResponse(res)
<a type="---" is just a type hinting having submit there does not trigger form submit.
Why is the actual submit button commented out?
<!-- <button class="btn btn-success btn-sm bounceIn animation-delay5 login-link pull-right" type="submit" id="id_submit">
<i class="fa fa-sign-in"></i>
Login
</button> -->```
I would uncomment this and go from there.
try to use on('submit') instead of submit().
What version of jquery do you use ?
it should be <Input type='submit'not<a>thats why your click worked before...

Calling a php file within a html file using 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.

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. :)

Uncaught ReferenceError: 'somevar' is not defined

Am trying to insert some data into mysql through ajax call but while am trying to get the data from my form javascript throws me this error "Uncaught ReferenceError: anjelis is not defined" on the first variable
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>aloooooooooooooo!!!!!!!!!</title>
<link rel="stylesheet" href="bootstrap/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css.css">
<script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.js"></script>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
$(document).ready(function(e){
$.ajaxSetup({cache:false});
setInterval(function(){$('#chatlog').load('logs.php');},1000);
setInterval(function(){$('#user_list').load('user_list.php');},1000);
});
function submitChat(){
var uname=<?php echo $_SESSION['username']?>;
var msg=form.msg.value;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById('chatlog').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET','insert.php?username='+uname+'&msg='+msg,true);
xmlhttp.send();
}
</script>
</head>
The body
<body>
<nav class="navbar navbar-inverse">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">ChatCY</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><?php if(!isset($_SESSION['username'])){echo 'Login/Signin';}else{
echo'Logout';}?></li>
</ul>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="panel panel-default">
<div id="chatlog" class="panel-body"></div>
</div>
</div>
<div class="col-md-2">
<div class="panel panel-default">
<div id="user_list" class="panel-body"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8">
<form class="form-inline">
<form name="form" class="form-group" onsubmit="return false;">
<input type="textarea" class="form-control" name="msg" style="width:90%;"<?php if(!isset($_SESSION['username'])){
echo 'disabled="disabled" placeholder="You must be logged in to chat .."';}?>></input>
<button type="button" class="btn btn-default" name="send" <?php if(!isset($_SESSION['username'])){
echo 'disabled="disabled"';}?> onClick="submitChat();">send</button>
</form>
</form>
</div>
</div>
</div>
There are a lot of issues in your code.
Quotes are missing in the variable. Add quotes here:
var uname = "<?php echo $_SESSION['username']?>";
Session is not started. Start the session using:
session_start();
Try not to mix up both PHP and HTML. Keep it separate. Don't use echo to write the HTML tags.
No <input /> has an ending tag, and there's no <input type="textarea"... It should be replaced with <input type="text".
Use jQuery or some other awesome libraries for doing complex functions like AJAX calls or something. That makes your and dev's life easier, by providing functions for all the browsers and less clutter of code.
$.ajax(function () {
"url": "/",
// Blah Blah
});
You missed the code
session_start(),
well you can do it another way, create a inpu tag in your html
<input type='hidden' id='uname' value="<?php echo $_SESSION['username']?>">
in js
get your id like this
var uname = $('#uname').val();
Missed the quotes -
var uname= "<?php echo $_SESSION['username']?>";
var form = $('form.form-group');
If it is
var uname = somevar;
somevar will be undefined.
You are not passing or defining form to the function or inside the function.

Categories

Resources