AJAX Post sometimes works, sometimes it doesnt, why? - javascript

I have several ajax posts in my pages and i find that somedays they do work correctly:
executes the method in the controller.
doesnt refresh page.
Sometimes it doesnt:
executes the method in the controller.
goes to a blank page.
I dont find a relation of when they work or they dont, it seems random but i hope its not.
I searched several stack overflow posts and articles and still couldnt find the reason hence why i am making this questin. Hope you understand that.
An example of an Ajax call that sometime works and sometimes not:
$(document).ready(function() {
$('form.ajaxaccount').on('submit', function(event) {
event.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: 'POST',
url: '/saveaccount', // This is the url we gave in the route
data: $('form.ajaxaccount').serialize(),
success: function(response){ // What to do if we succeed
var stack_bar_bottom = {"dir1": "up", "dir2": "right", "spacing1": 0, "spacing2": 0};
new PNotify ({
title: "Sucesso",
text: "Editado com sucesso! ",
styling: "bootstrap3",
addclass: "stack-bottomright custom",
nonblock: {
nonblock: true
},
stack: stack_bar_bottom
});
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
var stack_bar_bottom = {"dir1": "up", "dir2": "right", "spacing1": 0, "spacing2": 0};
new PNotify ({
title: "Erro :(",
text: "Os dados inseridos não foram guardados. Tenta novamente",
styling: "bootstrap3",
addclass: "stack-bottomright custom",
nonblock: {
nonblock: true
},
stack: stack_bar_bottom
});
}
});
});
});
FULL 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">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Wolistic</title>
<link href="./css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link href="./css/style.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet">
<script src="https://use.fontawesome.com/a3f24bf03b.js"></script>
<link href="dist/notyf.min.css" rel="stylesheet">
<script src="dist/notyf.min.js"></script>
<link rel="stylesheet" href="{{ asset('vendor/backpack/pnotify/pnotify.custom.min.css') }}">
</head>
<body>
#include('frontoffice.login_popup')
#include('frontoffice.register_popup')
<header>
<div class="top_bar_right">
<div class="container">
<ul>
#if (Auth::guard('web_customer')->guest())
<!--Seller Login and registration Links -->
<li><a id="openloginpopup"> Iniciar Sessão </a></li>
<li><a id="openregisterpopup"> Registar </a></li>
<ul class="lang_switch">
<li>Pt</li>
<li><img src="./img/down_arrow.png" width="9"></li>
</ul>
#else
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
{{ Auth::guard('web_customer')->user()->name }} <span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="{{ url('/customer_logout') }}"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
Logout
</a>
<form id="logout-form" action="{{ url('/customer_logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
</li>
</ul>
</li>
#endif
</ul>
</div>
</div>
<nav id="mainNav" class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1">
<span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i>
</button>
<a class="navbar-brand page-scroll" href="{{ url('/eventos') }}">
<img src="img/wolistic_logo.png" class="logo" alt="Wolistic" title="Wolistic" />
</a>
</div>
<div class="collapse navbar-collapse" id="navbar-collapse-1" class="menu">
<ul class="nav navbar-nav navbar-right">
<li>
<a class="page-scroll" href="#download">Sobre Nós</a>
</li>
<li>
<a class="page-scroll" href="#features">Workshops</a>
</li>
<li>
<a class="page-scroll" href="#contact">Eventos</a>
</li>
<li>
<a class="page-scroll" href="#contact">Voluntariado</a>
</li>
<li>
<a class="page-scroll" href="#contact">Submeter Evento</a>
</li>
</ul>
</div>
</div>
</nav>
<form class="col-md-12 search_form">
<div class="container">
<input type="text" name="search_term" class="search_term" id="search_term" placeholder="O que procuras? (Ex. Permacultura)" />
<select name="event_type" id="event_type" class="event_type" placeholder="Tipo">
<option value="" disabled selected hidden>Tipo</option>
<option>Evento</option>
<option>Workshop</option>
<option>Voluntariado</option>
</select>
<select name="event_local" id="event_local" class="event_local" placeholder="Tipo">
<option value="" disabled selected hidden>Local</option>
<option>Porto</option>
<option>Braga</option>
<option>Lisboa</option>
</select>
<input type="text" name="event_begin_date" class="event_begin_date" id="event_begin_date" placeholder="Data (início)" />
<input type="text" name="event_end_date" class="event_end_date" id="event_end_date" placeholder="Data (fim)" />
<button id="submit" class="search_submit"></button>
</div>
</form>
</header>
<main>
<div class="container">
<div class="breadcrumb">
<span>Início</span> > <span>Perfil</span>
</div>
<div class="profile_title">
A MINHA CONTA
</div>
<div class="row">
<div class="left_sidebar col-md-3 left_aboutus">
<img
#if (is_null($customer->profile_pic))
src="\uploads\{{ $customer->profile_pic }}"
#else
src="./img/default_profile_picture.png"
#endif
class="img-responsive profile_pic" />
<h1 class="profile_name"> {{ $customer->name }} </h1>
<div class="perfil-menu text-left">
<div class="perfil-accordion">
<div class="panel-group" id="accordion">
<div class="panel panel-default notbordered">
<div class="panel-heading active">
<h4 class="panel-title" >
<a class="accordion-perfil-tog-link-main" href="{{ url('/account') }}">Eu sou</a>
</h4>
</div>
</div>
<div class="panel panel-default notbordered">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#1collapse2" aria-expanded="false" class="collapsed">Eu gosto<span class="accordion-perfil-tog-link accordion-perfil-tog-plus"><i class="fa fa-angle-down" aria-hidden="true"></i></span></a>
</h4>
</div>
<div id="1collapse2" class="panel-collapse collapse" aria-expanded="false" style="height: 0px;">
<div class="panel-body">
<ul>
<li>Os meu interesses</li>
<li>Wishlist</li>
</ul>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading ">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#1collapse3" class="collapsed" aria-expanded="false">Eu quero<span class="accordion-perfil-tog-link accordion-perfil-tog-plus"><i class="fa fa-angle-down" aria-hidden="true"></i></span></a>
</h4>
</div>
<div id="1collapse3" class="panel-collapse collapse" aria-expanded="false" style="height: 0px;">
<div class="panel-body">
<ul>
<li>Newsletter</li>
<li>Alterar password</li>
<li>Apagar conta</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<!--
<div class="button_anunciante">EU SOU ANUNCIANTE</div>
-->
<div class="perfil-menu-anunciante text-left">
<div class="perfil-accordion">
<div class="panel-group" id="accordion">
<div class="panel panel-default ">
<div class="panel-heading ">
<h4 class="panel-title">
<a class="accordion-perfil-tog-link-main" href="{{ url('/advertiser') }}">Eu sou anunciante</a>
</h4>
</div>
</div>
<div id="anunciante-options" class="">
<div class="panel panel-default ">
<div class="panel-heading ">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#2collapse2" aria-expanded="false" class="collapsed">Os meus eventos<span class="accordion-perfil-tog-link accordion-perfil-tog-plus"><i class="fa fa-angle-down" aria-hidden="true"></i></span></a>
</h4>
</div>
<div id="2collapse2" class="panel-collapse collapse" aria-expanded="false" style="height: 0px;">
<div class="panel-body">
<ul>
<li> Os meus eventos </li>
<li> Submeter evento </li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="page_content col-md-6 col-md-offset-1">
<div class="separator"></div>
<h3 class="personal_data">DADOS PESSOAIS</h3>
<div class="separator_personal"></div>
{{ Form::open(array('method'=>'post','class'=> 'profile_form ajaxaccount', 'url'=>'/saveaccount')) }}
<div class="form-group">
<label for="exampleInputEmail1"> Nome </label>
<input type="text" name="name" class="form-control" value="{{ $customer->name }}" placeholder="{{ $customer->name }} ">
</div>
<div class="form-group">
<label for="exampleInputEmail1"> Email </label>
<input type="email" name="email" class="form-control" value="{{ $customer->email }}" placeholder="{{ $customer->email }}">
</div>
<div class="form-group">
<label for="exampleInputEmail1"> Telemóvel </label>
<input type="text" name="phone" class="form-control" data-country="PT" value="{{ $customer->phone }}" placeholder="{{ $customer->phone }} ">
</div>
<div class="form-group">
<label for="exampleSelect1">Distrito / região </label>
<select class="form-control" name="districtID" id="exampleSelect1">
#foreach ($districts as $district)
<option value="{{ $district->id }}" > {{ $district->name }} </option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-primary">GUARDAR DADOS</button>
{{Form::close()}}
</div>
</div>
</div>
<div class="separator"></div>
<div class="separator"></div>
<div class="separator"></div>
<div class="separator"></div>
</main>
#include('frontoffice.footer')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js "></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js "></script>
<script src="./js/bootstrap.min.js "></script>
<script src="./js/script.js "></script>
<script src="vendor/backpack/pnotify/pnotify.custom.min.js"></script>
<script>
$(document).ready(function() {
$('form.ajaxaccount').on('submit', function(event) {
event.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: 'POST',
url: '/saveaccount', // This is the url we gave in the route
data: $('form.ajaxaccount').serialize(),
success: function(response){ // What to do if we succeed
var stack_bar_bottom = {"dir1": "up", "dir2": "right", "spacing1": 0, "spacing2": 0};
new PNotify ({
title: "Sucesso",
text: "Editado com sucesso! ",
styling: "bootstrap3",
addclass: "stack-bottomright custom",
nonblock: {
nonblock: true
},
stack: stack_bar_bottom
});
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
var stack_bar_bottom = {"dir1": "up", "dir2": "right", "spacing1": 0, "spacing2": 0};
new PNotify ({
title: "Erro :(",
text: "Os dados inseridos não foram guardados. Tenta novamente",
styling: "bootstrap3",
addclass: "stack-bottomright custom",
nonblock: {
nonblock: true
},
stack: stack_bar_bottom
});
}
});
});
});
</script>
</body>
</html>
FORM from the above page:
{{ Form::open(array('method'=>'post','class'=> 'profile_form ajaxaccount', 'url'=>'/saveaccount')) }}
<div class="form-group">
<label for="exampleInputEmail1"> Nome </label>
<input type="text" name="name" class="form-control" value="{{ $customer->name }}" placeholder="{{ $customer->name }} ">
</div>
<div class="form-group">
<label for="exampleInputEmail1"> Email </label>
<input type="email" name="email" class="form-control" value="{{ $customer->email }}" placeholder="{{ $customer->email }}">
</div>
<div class="form-group">
<label for="exampleInputEmail1"> Telemóvel </label>
<input type="text" name="phone" class="form-control" data-country="PT" value="{{ $customer->phone }}" placeholder="{{ $customer->phone }} ">
</div>
<div class="form-group">
<label for="exampleSelect1">Distrito / região </label>
<select class="form-control" name="districtID" id="exampleSelect1">
#foreach ($districts as $district)
<option value="{{ $district->id }}" > {{ $district->name }} </option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-primary">GUARDAR DADOS</button>
{{Form::close()}}
What could be wrong ?

Related

how to use a mutation inside a component template? VUEX

I'm learning Vue with VUEX and I'm making and small app.
That small app call a json data and print it in a template.
I created a mutation called year(), that mutation get a world of a string and return the result but when I use that mutation inside template {{ year(item.fechaInicio) }} return a empty value.
That's my html code:
<!DOCTYPE html>
<html>
<head>
<title>Vue</title>
<!-- bootstrap 4 CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css">
<!-- fontawesome css -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" rel="stylesheet" type="text/css">
<!-- Tipografía -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i|Roboto+Mono:100,100i,300,300i,400,400i,500,500i,700,700i&display=swap" rel="stylesheet">
<!-- Jquery -->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- cookies jquery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.1/js.cookie.min.js"></script>
<!-- Vue -->
<script src="https://cdn.jsdelivr.net/npm/vue#2/dist/vue.js"></script>
<!-- Vuex -->
<script src="https://unpkg.com/vuex#3.6.0/dist/vuex.js"></script>
<!-- CSS estilos -->
<link href="calendario-2020.css" rel="stylesheet" />
</head>
<body>
<div class="Calendario" id="caja-vue">
<p class="calendario-titulo">Calendario Académico</p>
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item"><a aria-controls="home" aria-selected="true" class="nav-link active" data-toggle="tab" href="#home" id="home-tab" role="tab">Estudiantes</a></li>
</ul>
<!--TAB 1 ESTUDIANTES-->
<div class="tab-content" id="myTabContent">
<div aria-labelledby="home-tab" class="tab-pane fade show active" id="home" role="tabpanel">
<!--Semestres-->
<div class="flex-container">
<div class="Semestre">
<div class="custom-control form-control-lg custom-checkbox"><input class="custom-control-input" id="customCheck1" type="checkbox" /> <label class="custom-control-label" for="customCheck1">Semestre <span class="num">1</span></label></div>
<p>Enero 17-2020<br />
Mayo 15-2020
</p>
</div>
<div class="Semestre">
<div class="custom-control form-control-lg custom-checkbox"><input class="custom-control-input" id="customCheck2" type="checkbox" /> <label class="custom-control-label" for="customCheck2">Semestre <span class="num">2</span></label></div>
<p>Agosto 15-2020<br />
Diciembre 20-2020
</p>
</div>
<div class="Semestre">
<div class="custom-control form-control-lg custom-checkbox"><input class="custom-control-input" id="customCheck3" type="checkbox" /> <label class="custom-control-label" for="customCheck3">Intersemestral</label></div>
<p>Enero 17-2020<br />
Mayo 15-2020
</p>
</div>
<div class="col-lg-12 fechas">
<div class="row">
<div class="col-lg-9"> </div>
<div class="col-lg-3">
<div class="form-group">
<select class="form-control" id="exampleFormControlSelect1">
<option disabled="disabled" selected="selected">Organizar por:</option>
<option>Fecha Inicio</option>
<option>Fecha Final</option>
</select>
</div>
</div>
</div>
</div>
</div>
<!--Formulario de Busqueda-->
<div class="Formulario_calndario">
<div class="row">
<div class="col-lg-4">
<div class="form Formulario_busqueda">
<div class="input-group espacio">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">
<i class="fas fa-search">
<!--icono-->
</i>
</button>
</div>
<input class="form-control" name="search" placeholder="¿Qué estás buscando?" type="text" />
</div>
<div class="form-group">
<select class="form-control" id="exampleFormControlSelect1">
<option disabled="disabled" selected="selected">Tipo de programa</option>
<option>Pregrado</option>
<option>Posgrado</option>
</select>
</div>
<div class="form-group">
<select class="form-control" id="exampleFormControlSelect1">
<option disabled="disabled" selected="selected">Categoria</option>
<option>Cierre académico</option>
<option>Comité de idiomas</option>
<option>Exámenes finales</option>
<option>Homologaciones, reconocimientos y validaciones</option>
<option>Inicio y finalización de clases</option>
<option>Otras actividades de la vida universitaria</option>
<option>Pago de matrículas</option>
<option>Proceso de inducción</option>
<option>Publicación de grupos cancelados</option>
<option>Recesos y vacaciones</option>
<option>Registro de asignaturas</option>
<option>Reporte de notas</option>
<option>Reserva de cupo, re activaciones de cupo y reintegros</option>
<option>Retiro de asignaturas</option>
</select>
</div>
<div class="form-group">
<select class="form-control" id="exampleFormControlSelect1">
<option disabled="disabled" selected="selected">Tipo de programa</option>
<option>Escuela de Administración</option>
<option>Escuela de Medicina y Ciencias de la Salud</option>
<option>Escuela de Ciencias Humanas</option>
<option>Facultad de Economía</option>
<option>Facultad de Jurisprudencia</option>
<option>Facultad de Estudios Internacionales, Políticos y Urbanos</option>
<option>Facultad de Ciencias Naturales</option>
<option>Facultad de Creación</option>
<option>Escuela de Ingeniería, Ciencia y Tecnologí</option>
</select>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">
<i class="fas fa-search">
<!--icono-->
</i>
</button>
</div>
<input class="form-control" name="search" placeholder="Programa" type="text" />
</div>
</div>
<div class="form-group">
<p><a aria-controls="multiCollapseExample1" aria-expanded="false" class="Fecha" data-toggle="collapse" href="#multiCollapseExample1" role="button">Seleccione un mes</a></p>
<div class="row">
<div class="col">
<div class="collapse multi-collapse" id="multiCollapseExample1">
<div class="card card-body"><input class="form-control" id="example-date-input" type="date" value="2011-08-19" /></div>
</div>
</div>
</div>
<div class="form-group">
<p><a aria-controls="multiCollapseExample2" aria-expanded="false" class="Fecha" data-toggle="collapse" href="#multiCollapseExample2" role="button">Seleccione un mes</a></p>
<div class="row">
<div class="col">
<div class="collapse multi-collapse" id="multiCollapseExample2">
<div class="card card-body">
<p>Fecha inicial</p>
<input class="form-control" id="example-date-input" type="date" value="2011-08-19" />
<p>Fecha final</p>
<input class="form-control" id="example-date-input" type="date" value="2011-08-19" />
</div>
</div>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-md-6">
<input class="btn btn-primary" type="submit">Buscar</input>
</div>
<div class="col-md-6">
<input class="btn btn-primary Limpiar" type="submit">Limpiar</input>
</div>
</div>
</div>
</div>
</div>
<actividades></actividades>
</div>
</div>
</div>
</div>
</div>
<script src="codigo.js"></script>
</body>
</html>
That's my javascript code:
//componentes
Vue.component('actividades', {
template: /*html*/
`
<div class="col-lg-8">
<template v-for="item of actividades">
<div class="row Programa-especifico">
<div class="col-md-4 col-lg-4 Fecha">
<div class="row">
<div class="col-md-2 col-lg-2">
<i class="far fa-calendar">
<!--icono-->
</i>
</div>
<div class="col-md-10 col-lg-10 px-5"><strong class="titulo">Marzo 08</strong> <span>Abril 17 2020</span></div>
</div>
<div class="mt-3 txt">
<strong>Tipo de programa</strong> <span>{{ item.tipoPrograma }}</span><br />
<strong>Facultad</strong> <span>{{ item.facultad }}</span><br />
<strong>Programa</strong> <span>{{ item.programa }}</span><br />
<strong>Categoria</strong> <span>{{ item.categoria }}</span>
</div>
</div>
<div class="col-md-8 col-lg-8 Descripcion">
<p class="titulo">{{ item.contenido }}</p>
<!--
<p class="txt">It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p>
-->
<!--
<i class="fas fa-map-marker-alt">
</i>
-->
<!--
<strong>Lugar:</strong> <span class="txt">Universidad del Rosario, Sede, Claustro, Aula Mutis</span><br />
<i class="far fa-calendar">
</i>
-->
<strong>Fecha de inicio:</strong> <span class="txt">
Marzo, de {{ year(item.fechaInicio) }}
</span><br />
<strong>Fecha de cierre:</strong> <span class="txt">12 Marzo, de 2020</span><br />
<!--
<i class="far fa-clock">
</i>
<strong>Hora:</strong> <span class="txt">De 8:00 a.m. a 12:30 p.m</span>
-->
<div class="row">
<div class="col-lg-3 Semestre_uno">{{ item.periodo }}</div>
<div class="col-lg-3 Cerrado">Cerrado</div>
</div>
</div>
</div>
</template>
</div>
`,
computed: {
...Vuex.mapState(['actividades','programas']),
},
methods: {
...Vuex.mapActions(['llamarJson']),
...Vuex.mapMutations(['year'])
}
});
//VueEx
const store = new Vuex.Store({
state: {
actividades: [],
programas: []
},
mutations: {
llamarJsonMutation(state, llamarJsonAction){
state.actividades = llamarJsonAction.Nueva_estructura_proveedor;
state.programas = llamarJsonAction.BD_programas;
},
year(date){
return String(date).substr(8, 2);
}
},
actions: {
llamarJson: async function({ commit }){
const data = await fetch('calendario-2021-prueba.json');
const dataJson = await data.json();
commit('llamarJsonMutation', dataJson);
}
}
});
//Vue
new Vue({
el: '#caja-vue',
store: store,
created() {
this.$store.dispatch('llamarJson');
}
});
Do not return the value in mutation. Mutations are for mutating states in vuex. Instead, add a property to state as year then in the mutaitioner just add :
state.year = String(date).substr(8, 2);
Then in your component and in computed add:
year(){
return this.store.state.year;
}
And now, you can access {{year}} in your template.

Bootstrap radio button isn't working in flask

I am using Bootstrap 4 radio button radio button in a flask application. and below is the snippet I used
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-outline-secondary">
<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="twitter"/> Twitter
</label>
<label class="btn btn-outline-secondary" >
<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="facebook"/> Facebook
</label>
</div>
and the javascript code
<script type="text/javascript">
function toggleElements() {
alert('hurray');
if(document.getElementBId('twitter').checked) {
document.getElementById('twitterrows').style.display = 'block';
document.getElementById('facebookrows').style.display = 'none';
}
if(document.getElementById('facebook').checked) {
document.getElementById('facebookrows').style.display = 'block';
document.getElementById('twitterrows').style.display = 'none';
}
}
</script>
Initially,I tried with simple html radio buttons and was able to trigger Javascript function toggleElements(). However, after replacing the normal radio buttons with the bootstrap radio, nothing is triggered.
Below is the entire html code
{% from 'helper/forms.html' import render_field with context %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sharjah Tourism Search Results</title>
<script src="{{ url_for('static', filename='js/jquery-3.2.1.min.js') }}"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="{{ url_for('static',filename='styles/home.css')}}"/>
<script type="text/javascript">
function toggleElements() {
alert('hurray');
if(document.getElementBId('twitter').checked) {
document.getElementById('twitterrows').style.display = 'block';
document.getElementById('facebookrows').style.display = 'none';
}
if(document.getElementById('facebook').checked) {
document.getElementById('facebookrows').style.display = 'block';
document.getElementById('twitterrows').style.display = 'none';
}
}
</script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="{{ url_for('home')}}"><strong>Search</strong></a>
<button class = "navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent-7"
aria-controls="navbarSupportedContent-7" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent-7">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="{{url_for('add_url')}}">Add<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url_for('file_render')}}">Import</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">
Websites
</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="{{ url_for('list_urls') }}">List</a>
<a class="dropdown-item" href="{{ url_for('list_crawled_websites')}}">Selected</a>
</div>
</li>
</ul>
</div>
</nav>
<!-- Header -->
<div class="container">
<br />
<div class="row">
<!-- Logo -->
<div class="col-sm">
<img class="w-50 h-60" src="{{url_for('static',filename='images/sctda_logo.jpg')}}" />
</div>
<!-- Search Bar -->
<div class="col-sm-5 searchbar">
<form action="{{url_for('fetch_results')}}" method="POST">
<div class="input-group">
<input type="search" placeholder="Search" class="form-control" name="search" id="search" value="{{data['search_term']}}" class="w-75 h-75" required>
<div class="input-group-append">
<button type="submit" class="btn btn-outline-secondary btn-sm"><i class="fa fa-search"></i></button>
</div>
</div>
</form>
</div>
</div>
<div id="container">
<div class="row">
{%set data = data['results'] %}
<div class="col-md-4">
<div class="btn-group-toggle" data-toggle="buttons">
<label class="btn btn-outline-secondary active">
<input type="radio" checked autocomplete="off"> Internal
</label>
</div>
<hr>
{% set internals = data['internal'] %}
{% if internals is defined and internals|length %}
{% for internal in internals %}
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ internal['title'] }}</h5>
<p class="card-text">{{ internal['description'] }}</p>
{{ internal['title'] }}
</div>
</div>
<br/>
{% endfor %}
{% else %}
<div class="card">
<div class="card-body">
<h5 class="card-title">No Records Found</h5>
</div>
</div>
<br/>
{% endif %}
</div>
<div class="col-md-4">
{% set externals = data['external'] %}
{% if externals is defined and externals|length %}
<div class="btn-group-toggle" data-toggle="buttons">
<label class="btn btn-outline-secondary active">
<input type="radio" checked autocomplete="off"> External
</label>
</div>
<hr>
{% for external in externals %}
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ external['title'] }}</h5>
<p class="card-text">{{ external['description'] }}</p>
{{ external['title'] }}
</div>
</div>
<br/>
{% endfor %}
{% else %}
<div class="card">
<div class="card-body">
<h5 class="card-title">No Records Found</h5>
</div>
</div>
<br/>
{% endif %}
</div>
<div class="col-md-4">
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-outline-secondary">
<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="twitter"/> Twitter
</label>
<label class="btn btn-outline-secondary" >
<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="facebook"/> Facebook
</label>
</div>
<hr>
(<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="twitter"/> Twitter,
<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="facebook"/> Facebook)
<div id="twitterrows">
{% set tweets = data['twitter'] %}
{% if tweets is defined and tweets|length %}
{% for tweet in tweets %}
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ tweet['title'] }}</h5>
<p class="card-text">{{ tweet['description'] }}</p>
{{ tweet['title'] }}
</div>
</div>
<br/>
{% endfor %}
{% else %}
<div class="card">
<div class="card-body">
<h5 class="card-title">No Records Found</h5>
</div>
</div>
<br/>
{% endif %}
</div>
<div id="facebookrows">
{% set posts = data['facebook'] %}
{% if posts is defined and posts|length %}
{% for post in posts %}
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ post['title'] }}</h5>
<p class="card-text">{{ post['description'] }}</p>
{{ post['title'] }}
</div>
</div>
<br/>
{% endfor %}
{% else %}
<div class="card">
<div class="card-body">
<h5 class="card-title">No Records Found</h5>
</div>
</div>
<br/>
{% endif %}
</div>
</div>
</div>
</div>
<center>Developed by School of Information Technology Team,Skyline University College</center>
</body>
</html>
I strongly suspect with the order of scripts being called under the head tag. Can someone help me to fix this please.
make sure you have included the correct version of bootstrap. Please check if there is any error in the browser console.
https://getbootstrap.com/docs/4.4/components/input-group/#checkboxes-and-radios.
I am suspecting that the javascript click is not properly binded to the click event.
I fixed it by replacing the three script tags in the above html page with the below
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

How to show data when using API?

Im trying to get data from an API using ajax request. I did it but im not sure how to show the information to the client. I want to search by artist and show their songs. Here is my code and link to the api. Please help me!
https://rapidapi.com/brianiswu/api/genius?endpoint=apiendpoint_d2f41ea4-7d5c-4b2d-826a-807bffa7e78f
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MusicApp</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>
<header>
<div class="container">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="index.html">MusicApp</a>
</div>
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
<li>Lyrics</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-user"></span> Sign Up</li>
<li><span class="glyphicon glyphicon-log-in"></span> Login</li>
</ul>
</div>
</nav>
</div>
</header>
<div class="container">
<div class="row" style="margin-top:30px;">
<div class="col-sm-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Search</h3>
</div>
<div class="panel-body">
<div class="form-group">
<div class="row">
<div class="col-sm-4">
<img class="thumbnail img-responsive" src="images/notes.jpg">
</div>
<div class="col-sm-8">
<input type="checkbox" class="form-check-input" id="sort">
<label class="form-check-label" for="sort">Sort</label>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<label for="artist">Artist:</label>
<textarea class="form-control" rows="1" id="artist"></textarea>
</div>
</div>
</div>
</div>
<div class="panel-footer" style="height:55px;">
<button type="button" id="postComment" class="btn btn-primary pull-right publish"><span
class="glyphicon glyphicon-globe"></span> Search
</button>
</div>
</div>
</div>
<div class="col-sm-8">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Results</h3>
</div>
<ul class="list-group" style="min-height:241px;" id="contentList">
<li class="list-group-item" style="display:none" id="cloneMe">
<div class="row">
<div class="col-sm-2 col-xs-3">
<img src="images/notes.jpg" class="thumbnail img-responsive">
</div>
<div class="col-sm-7 col-xs-6">
<h4>Shakira</h4>
<p id="songName">some result </p>
<p id="lyricsLink">some result</p>
</div>
<div class="col-sm-3 col-xs-3">
<button type="button" class="btn btn-danger pull-right remove-post"><span
class="glyphicon glyphicon-remove"></span><span class="hidden-xs"> Delete</span>
</button>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
$(document).ready(function(){
var api="1f57380a81msh394cf453f4d1e73p1a0276jsnab0cd43f0df7";
$('#postComment').click(function(){
artistName=$('#artist').val();
console.log(artistName);
var settings = {
"async": true,
"crossDomain": true,
"url": "https://genius.p.rapidapi.com/search?q=" + artistName,
"method": "GET",
"headers": {
"x-rapidapi-host": "genius.p.rapidapi.com",
"x-rapidapi-key": "1f57380a81msh394cf453f4d1e73p1a0276jsnab0cd43f0df7"
}
}
$.ajax(settings)
.done(function (response) {
console.log(response.response.hits);
response.response.hits.forEach(r => {
var miniMe = $('#cloneMe').clone();
miniMe.attr('id', r.result.id);
console.log(r.result.header_image_url);
miniMe.find('img').attr('src', r.result.header_image_url);
miniMe.find('h4').text(artistName);
miniMe.find('#songName').html(r.result.full_title);
miniMe.find('#lyricsLink').html(r.result.url);
miniMe.find('button').click(function () {
miniMe.remove();
});
miniMe.find('checkbox').click(function(){
})
miniMe.show();
$('#contentList').append(miniMe);
});
});
return false;
});
});
</script>
</html>
You can iterate through the response with using this as your ajax block;
$.ajax(settings)
.done(function (response) {
// sort the response alphabetically
response.response.hits.sort((a,b) => (a.result.full_title > b.result.full_title) ? 1 : (b.result.full_title > a.result.full_title) ? -1 : 0);
response.response.hits.forEach(r => {
var miniMe = $('#cloneMe').clone();
miniMe.attr('id', r.result.id);
miniMe.find('img').attr('src', r.result.header_image_url);
miniMe.find('h4').text(artistName);
miniMe.find('p').html(r.result.full_title);
miniMe.find('button').click(function () {
miniMe.remove();
});
miniMe.show();
$('#contentList').append(miniMe);
});
});
You can see the working demo in codepen and you can look into this link if you want to learn about sort() function and how it works in JavaScript.

<script type="text/javascript"> failed to load Resourse for internal script

Is the script tag with no src attribute is wrong?
I have written this script tag
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('.select_subject').click(function(){
jQuery('[name=subject_id]').val(jQuery(this).data('subject_id'));
jQuery(this).parents('form').submit();
});
});
</script>
I am getting this error on console Failed to load resource: the server responded with a status of 404 (Not Found). I am unable to understand what is the problem. I have included the jquery core library on header of page. Also there are some other javascripts codes that are included bfore this code but they did not throws any error. I have also attached a screenshot of the console.
Update 1
I tried after removing the type attribute. nothing happens :( .
I have included the jquery library version 1.9.1 in header.
Update 2
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="Bharat">
<title>::Eduesy:: </title>
<meta property="og:title" content="Bharat">
<meta property="og:description" content="Bharat">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
<link type="text/css" rel="stylesheet" href="http://eduesy.fsas.co.in/css/student/web.css?1.0" />
<link type="text/css" rel="stylesheet" href="http://eduesy.fsas.co.in/css/student/app.css" />
<link type="text/css" rel="stylesheet" href="http://eduesy.fsas.co.in/css/student/tooltip.css" />
<link type="text/css" rel="stylesheet" href="http://eduesy.fsas.co.in/css/student/custom.css" />
<link type="text/css" rel="stylesheet" href="http://eduesy.fsas.co.in/css/student/font-awesome.min.css" />
<link href='https://fonts.googleapis.com/css?family=Alegreya:400,700' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="http://eduesy.fsas.co.in/js/student/jquery-1.9.1.min.js"></script>
<script src="https://cdn.ravenjs.com/3.6.1/raven.min.js"></script>
<script type="text/javascript" src="http://eduesy.fsas.co.in/js/student/vendor.js"></script>
<script type="text/javascript" src="http://eduesy.fsas.co.in/js/student/libs.all.min.js"></script>
<script type="text/javascript" src="http://eduesy.fsas.co.in/js/student/app.js"></script>
<script type="text/javascript" src="http://eduesy.fsas.co.in/js/student/tooltip.js"></script>
<script type="text/javascript" src="http://eduesy.fsas.co.in/js/student/tpr.web.min.js"></script>
<script src="http://eduesy.fsas.co.in/js/student/chartist.min.js"></script>
<script>
jQuery(document).ready(function(){
jQuery(window).scroll(function(e) {
if(jQuery(document).scrollTop()>0){
jQuery(".header").addClass('header-fix');
}else{
jQuery(".header").removeClass('header-fix');
}
});
jQuery(window).scroll(function(e) {
if(jQuery(document).scrollTop()>0){
jQuery(".row-blue").addClass('header-fix');
}else{
jQuery(".row-blue").removeClass('header-fix');
}
});
});
</script>
</head>
<body>
<div class="header">
<header>
<div class="cf">
<div class="pTopHeader_dropdown pTopHeader_userDropdown non-selectable fr js-user-dropdown">
<a class="pTopHeader_dropdown_trigger pTopHeader_userDropdown_trigger js-trigger">
<span class="profilename">Welcome Chandu</span> <img class="pTopHeader_userDropdown_thumb " alt="" src="http://eduesy.fsas.co.in/uploadedFiles/student/IMG_20150412_182136 (2) - Copy.jpg"/>
</a>
<ul class="pTopHeader_dropdown_menu pTopHeader_dropdown_menu-right pTopHeader_userDropdown_menu js-dropdown">
<li>
<span class="fa fa-tachometer pTopHeader_dropdown_menu_icon"></span>Profile
</li>
<li>
<span class="fa fa-tachometer pTopHeader_dropdown_menu_icon"></span>Switch Course
</li>
<li>
<span class="fa fa-power-off pTopHeader_dropdown_menu_icon"></span>Logout
</li>
</ul>
</div>
<div class="pTopHeader_contactUpWrapper_trigger ph-16 fr phn-hide">
<a role="button" tabindex="0" class="pTopHeader_btn pTopHeader_appBtn button button-small button-white">Contact Us</a>
<div class="pTopHeader_contactUpWrapper_tooltip">
<div class="contactTooltip">
<div class="cf">
<div class="contactTooltip_item">
<div class="contactTooltip_itemIcon contactTooltip_itemIcon-feedback"></div>
<div class="contactTooltip_title">Share Feedback</div>
<div class="contactTooltip_subtitle">Share your feedback for us. We are continuously working to improve your experience.</div>
<div class="contactTooltip_callUsNo">abc#xyz.com</div>
</div>
<div class="contactTooltip_item">
<div class="contactTooltip_itemIcon contactTooltip_itemIcon-callus"></div>
<div class="contactTooltip_title">Call us</div>
<div class="contactTooltip_subtitle">We are happy to hear from you. We are available from 9am to 6pm on all days.</div>
<div class="contactTooltip_callUsNo">+91 - 1800 123 456</div>
</div>
</div>
<div class="contactTooltip_footer">
<span class="contactTooltip_footer_mapIcon fa fa-map-marker" aria-hidden="true"></span>
<div class="contactTooltip_footer_content">
<div class="contactTooltip_footer_title">Eduesy Online Education </div>
<div class="contactTooltip_footer_text">Mumbai - 400076, India</div>
</div>
</div>
</div>
</div>
</div>
<div class="pTopHeader_contactUpWrapper_trigger ph-16 fr phn-hide notification">
<a class="pTopHeader_btn pTopHeader_appBtn button button-small button-white"><i class="fa fa-bell" aria-hidden="true"></i><span>0</span></a>
</div>
<div class="pTopHeader_contactUpWrapper_trigger ph-16 fr phn-hide btn-buy">
<a class="pTopHeader_btn pTopHeader_appBtn button button-small button-white">Buy</a>
</div>
</div>
</header>
<div class="logo">
<a href="http://eduesy.fsas.co.in/student/lectures/index.php" class="mainSidebar_logoBlock_logo -ajaxify" title="EduEsy" style="width: 176px !important">
<div class="mainSidebar_logoBlock_logo_img" style="background-image: url(http://eduesy.fsas.co.in/images/logo.png)"></div>
</a>
</div>
<div class="mobileMenu">
<div class="mobileMenu_fallbackHeader"></div>
<div class="mobileMenu_hamburger js-hamburger-menu">
<div class="mobileMenu_hamburger_icon">
<span></span>
<span></span>
<span></span>
</div>
</div>
</div>
</div>
<div class="row-blue">
<div class="pull-left">
Admission Taken Date: 29/05/2017
</div>
<div class="pull-right">
Student ID: EDUESY116 <span>|</span> Package Valid till: 25/12/2017
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('.class_slider').click(function(){
jQuery('[name=product_id]').val(jQuery(this).data('product_id'));
jQuery('[name=product_type]').val(jQuery(this).data('product_type'));
jQuery(this).parents('form').submit();
});
});
</script>
<div class="popupbox" id="popuprel_course">
<div id="intabdiv">
<div id="test_tool_modals_wrapper">
<div class="md mdTestPause js-test-pause-modal is-visible" style="overflow-y: auto;">
<div class="close">X</div>
<form action="" method="post">
<div class="obrdV2_container js-modules-container pb-10 ">
<div class="clr"></div>
<div class="obrdV2_module js-module-class js-module profiletype" data-module="profiletype">
<div class="p-20 clickable js-toggle-module">
<div class="obrdV2_module_image obrdV2_module_image-klass fl"></div>
<div class="obrdV2_module_heading js-module-heading">
<div class="title">Choose one of the following</div>
<div class="selectedValue js-selected-value"></div>
</div>
<div class="arrowDown js-arrow-down class" style="display: none;"></div>
<div class="clr"></div>
</div>
<div class="obrdV2_module_body js-module-body visible ">
<div class="col-md-6 col-sm-12">
<div class="item academic"><label><input type="radio" name="profileType" value="academic" id="academic" style="display: none;"> Academic</label></div>
</div>
<div class="col-md-6 col-sm-12">
<div class="item professional"><label><input type="radio" name="profileType" value="professional" id="professional" style="display: none;">Professional Courses</label></div>
</div>
<div class="clr"></div>
</div>
<div class="clr"></div>
</div>
<div class="clr"></div>
<div class="obrdV2_module js-module-class js-module address hide" data-module="address"></div>
<div class="clr"></div>
<div class="submit-row hide">
<div class="obrdV2_module js-module-class js-module submit" data-module="submit">
<div class="obrdV2_module_body js-module-body visible">
<input type="submit" name="switchCourseSubmit" class="btn btn-default" value="Save and Continue">
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.mcustomscrollbar/3.0.6/jquery.mCustomScrollbar.min.css" />
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.mcustomscrollbar/3.0.6/jquery.mCustomScrollbar.concat.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.actual/1.0.19/jquery.actual.min.js"></script>
<script>
$(document).ready(function() {
$('.switch_class').click(function() {
var popupid = $(this).attr('rel');
$('#' + popupid).fadeIn();
$('body').append('<div id="fade"></div>');
$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
var popuptopmargin = ($('#' + popupid).height() + 10) / 2;
var popupleftmargin = ($('#' + popupid).width() + 10) / 2;
$('#' + popupid).css({
'margin-top' : -popuptopmargin,
'margin-left' : -popupleftmargin
});
});
jQuery('body').on('click', '.popupbox .close', function() {
jQuery(this).parents('.popupbox').fadeOut();
jQuery('#fade').fadeOut();
return false;
});
jQuery('.profiletype .js-module-body .item').on('click', function(evt){
if (evt.target.tagName == 'INPUT'){
var profile = jQuery('[name="profileType"]:checked').val();
jQuery.ajax({
url : 'http://eduesy.fsas.co.in/ajax_complete_profile.php',
type : 'post',
data : {action: 'profiletype', profiletype: profile},
beforeSend : function(){
/*do nothing*/
},
success : function(html){
jQuery('.level2').remove();
jQuery('.address').before(html);
}
});
jQuery(".address").addClass('hide');
jQuery('.submit-row').addClass('hide');
}
});
jQuery('.obrdV2_container').on('click', '.classtype', function(evt){
if (evt.target.tagName == 'INPUT'){
var profile = jQuery('[name="classtype"]:checked').val();
jQuery.ajax({
url : 'http://eduesy.fsas.co.in/ajax_complete_profile.php',
type : 'post',
data : {action: 'boardtype', profiletype: profile},
beforeSend : function(){
/*do nothing*/
},
success : function(html){
jQuery('.level3').remove();
jQuery('.address').before(html);
}
});
}
});
jQuery('.obrdV2_container').on('click', '.boardListing', function(evt){
if (evt.target.tagName == 'INPUT'){
var board = jQuery('[name="boardID"]:checked').val();
jQuery.ajax({
url : 'http://eduesy.fsas.co.in/ajax_complete_profile.php',
type : 'post',
data : {action: 'classList', classList: board},
beforeSend : function(){
/*do nothing*/
},
success : function(html){
jQuery('.level4').remove();
jQuery('.address').before(html);
}
});
jQuery(".address").addClass('hide');
jQuery('.submit-row').addClass('hide');
}
});
jQuery('.obrdV2_container').on('click', '.obrdV2_klass', function(evt){
if (evt.target.tagName == 'INPUT'){
jQuery(this).siblings( '.selected').removeClass('selected');
jQuery(this).addClass('selected');
jQuery('.address').removeClass('hide');
jQuery('.submit-row').removeClass('hide');
}
});
jQuery('.obrdV2_container .address').on('change', function(evt){
jQuery('.submit-row').removeClass('hide');
});
(function($){
$(window).on("load",function(){
var modal_ht = jQuery('#popuprel_course .popupbox').actual('height');
jQuery("#popuprel_course #intabdiv").height(modal_ht);
jQuery("#popuprel_course #intabdiv").mCustomScrollbar({
scrollButtons:{enable:true},
theme:"light-thick",
scrollbarPosition:"outside",
updateOnBrowserResize: true,
updateOnContentResize: true
});
});
})(jQuery);
});
</script>
<style type="text/css">
.popupbox .close {
position: absolute;
right: 10px;
top: 8px;
font-size: 20px;
font-weight: bold;
background: #fff;
color: #000;
z-index: 9999999999999999;
border-radius: 50%;
padding: 5px 10px;
cursor: pointer;
opacity: 1;
visibility: visible;
box-sizing: border-box;
}
</style>
<div class="pageContentContainer">
<div id="page_content_wrapper" class="js-page-content-wrapper">
<div class="pHeader js-page-content">
<div class="cf">
<div class="pTopHeader_contactUpWrapper_trigger ph-16 fr phn-hide paging">
<a href="http://eduesy.fsas.co.in/student" >Dashboard</a> » <a href="index.php" >Lecture</a>
» <a href="javascript:void(0);" >HTML JavaScript</a>
</div></div>
<div class="pHeader_content pt-25 pb-20 phn-pb-5 clearfix">
<div class="container">
<h1 class="h1 color-white normal">
Lectures
</h1>
</div>
</div>
<div class="pHeader_tabsWrapper js-page-tabs-wrapper">
<div class="container">
<nav role="navigation">
<ul class="pHeader_tabs">
<li class=""><a data-tab="challenges_home" href="index.php?subject=51" class="-ajaxify -strk" >HTML Basic</a></li> <li class=""><a data-tab="challenges_home" href="index.php?subject=52" class="-ajaxify -strk" >HTML Styles</a></li> <li class="active"><a data-tab="challenges_home" href="index.php?subject=53" class="-ajaxify -strk" >HTML JavaScript</a></li> <li class=""><a data-tab="challenges_home" href="index.php?subject=54" class="-ajaxify -strk" >HTML And XHTML</a></li>
</ul>
</nav>
</div>
</div>
<div class="pHeader_tabsSpacing"></div>
</div>
<div class="container js-page-content">
<div class="coachmarks_icon coachmarks_icon_selectSubject hide js-coachmarks"></div>
</div>
<div class="container pv-30 cf">
<div class="pCol pCol-wide alpha js-pageLearn">
<aside class="pCol pCol-narrow omega phn-mt-40">
<div class="heading heading-bordered h3 bold">Chapters</div>
<div class="cf mt-30 mb-50">
<a href="topic.php?topic=26"><div class="chapterTile tile tile-shadowed select_subject cf js-chapter-tile mb-20 tab-mb-20 phn-mb-15" data-subject_id="19">
<div class="chapterTile_arrowContainer">
<h2 class="chapterTile_title ">HTML File Paths</h2>
<span class="tile_arrow fa fa-angle-right"></span>
</div></div></a>
</div>
</aside>
</div>
<div class="sidebar-common">
<h2>Our mission is to provide a world class education to anyone, anywhere.</h2>
<h3>You will receive inside.</h3>
<ul>
<li><label><img src="http://eduesy.fsas.co.in/images/student/img-video.png" /></label>Video Lecture</li>
<li><label><img src="http://eduesy.fsas.co.in/images/student/img-test-series.png" /></label>Test Series</li>
<li><label><img src="http://eduesy.fsas.co.in/images/student/img-study-material.png" /></label>Study Material</li>
<li><label><img src="http://eduesy.fsas.co.in/images/student/img-doubt-section.png" /></label>Doubt Section</li>
</ul>
</div>
<div class="clr"></div>
</div>
<script>
jQuery(document).ready(function(){
jQuery('.select_subject').click(function(){
jQuery('[name=subject_id]').val(jQuery(this).data('subject_id'));
jQuery(this).parents('form').submit();
});
});
</script>
</div>
<div class="container">
<footer class="footer mv-20">
<ul>
<li>© Eduesy</li>
<span class="footer_dot">•</span>
<li>About</li>
<span class="footer_dot">•</span>
<li>Upgrade</li>
<span class="footer_dot">•</span>
<li>Contact</li>
<span class="footer_dot">•</span>
<li>Terms</li>
<span class="footer_dot">•</span>
<li>Bytes</li>
<span class="footer_dot">•</span>
<li>Blog</li>
</ul>
<div class="clr"></div>
</footer>
</div>
</div>
<div class="mainSidebar js-main-sidebar">
<div class="mainSidebar_switcherBlock js-class-switcher">
<a class="mainSidebar_switcherBlock_switch js-selected-class"> HTML</a>
<div class="mainSidebar_switcherBlock_dropdown js-dropdown">
<form method="post" action="http://eduesy.fsas.co.in/student/lectures/index.php">
<label class="mainSidebar_switcherBlock_option class_slider js-switchOption selected" data-class-title="HTML " data-product_id="47" data-product_type="Course" selected>HTML<div class="mainSidebar_switcherBlock_option_tickMark fa fa-check"></div></label><label class="mainSidebar_switcherBlock_option class_slider js-switchOption " data-class-title="Advance PHP " data-product_id="61" data-product_type="Course" >Advance PHP<div class="mainSidebar_switcherBlock_option_tickMark fa fa-check"></div></label>
<input type="hidden" name="product_id" value="course" />
<input type="hidden" name="product_type" value="47" />
<input type="hidden" name="change_product_type" value="1" />
</form>
</div>
</div>
<nav role="navigation" class="mainSidebar_contentBlock mainSidebar_contentBlock-withSwitcher js-main-sidebar-content-block">
<div class="mainSidebar_sHeading">Study Modules</div>
<ul class="mainSidebar_sNav js-mainSidebar-study">
<li data-tab="learn" class="active open">
<a href="http://eduesy.fsas.co.in/student/lectures/index.php" class="-ajaxify q_tip_w" original-title="Lectures">
<div class="iconWrapper">
<i class="fa fa-file-video-o" aria-hidden="true"></i>
</div>
<span class="arrow fa fa-angle-right"></span>
<div class="label">Lectures</div>
</a>
</li>
<li data-tab="practice" class="">
<a href="http://eduesy.fsas.co.in/student/practice/index.php" class="-ajaxify q_tip_w" original-title="Practice">
<div class="iconWrapper">
<i class="fa fa-book" aria-hidden="true"></i>
</div>
<span class="arrow fa fa-angle-right"></span>
<div class="label">Practice</div>
</a>
</li>
<li data-tab="tests" class="">
<a href="http://eduesy.fsas.co.in/student/tests/index.php" class="js-lhs-ts-link q_tip_w -ajaxify -strk">
<div class="iconWrapper">
<i class="fa fa-pencil-square-o" aria-hidden="true"></i>
</div>
<span class="arrow fa fa-angle-right"></span>
<div class="label">Tests</div>
</a>
</li>
<li data-tab="tests" class=""><div class="iconWrapper"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></div><span class="arrow fa fa-angle-right"></span><div class="label">Exam</div></li>
<li data-tab="doubts" class="">
<a href="http://eduesy.fsas.co.in/student/doubt/index.php"
class="-strk -ajaxify q_tip_w js-startDoc">
<div class="iconWrapper">
<i class="fa fa-weixin" aria-hidden="true"></i>
</div>
<span class="arrow fa fa-angle-right"></span>
<div class="label">Doubts</div>
</a>
</li>
<li data-tab="challenges" class="">
<a href="http://eduesy.fsas.co.in/student/challenges/index.php" class="-ajaxify q_tip_w">
<div class="iconWrapper">
<i class="fa fa-gamepad" aria-hidden="true"></i>
</div>
<span class="arrow fa fa-angle-right"></span>
<div class="label">Challenges</div>
</a>
</li>
</ul>
<div class="mainSidebar_sHeading">My Profile</div>
<ul class="mainSidebar_sNav js-mainSidebar-compare">
<li data-tab="dashboard" class="">
<a href="http://eduesy.fsas.co.in/student/dashboard/index.php" class="-ajaxify q_tip_w" original-title="Dashboard">
<div class="iconWrapper">
<i class="fa fa-tachometer" aria-hidden="true"></i>
</div>
<span class="arrow fa fa-angle-right"></span>
<div class="label">Dashboard</div>
</a>
</li>
<li data-tab="my_bookmarks" class="">
<a href="http://eduesy.fsas.co.in/student/placement/index.php" class="-ajaxify -bookmarks q_tip_w">
<div class="iconWrapper">
<i class="fa fa-star-half-o" aria-hidden="true"></i>
</div>
<span class="arrow fa fa-angle-right"></span>
<div class="label">Placement</div>
</a>
</li>
<li data-tab="achievements" class="">
<a href="http://eduesy.fsas.co.in/student/achievement/index.php" class="-ajaxify q_tip_w">
<div class="iconWrapper">
<i class="fa fa-trophy" aria-hidden="true"></i>
</div>
<span class="arrow fa fa-angle-right"></span>
<div class="label">Achievements</div>
</a>
</li>
<li data-tab="leaderboard" class="">
<a href="http://eduesy.fsas.co.in/student/leaderboard/index.php" class="-ajaxify -strk q_tip_w">
<div class="iconWrapper">
<i class="fa fa-bar-chart" aria-hidden="true"></i>
</div>
<span class="arrow fa fa-angle-right"></span>
<div class="label">Leaderboard</div>
</a>
</li>
</ul>
<div class="mainSidebar_sHeading">Study Tools</div>
<footer class="mainSidebar_footer mv-20">
<ul class="cf">
<li>© Eduesy</li>
<span class="mainSidebar_footer_dot">•</span>
<li>About</li>
<span class="mainSidebar_footer_dot">•</span>
<li>
Discuss
</li>
<span class="mainSidebar_footer_dot">•</span>
<li>Blog</li>
<span class="mainSidebar_footer_dot">•</span>
<li>Terms</li>
</ul>
</footer>
</nav>
</div>
</body>
</html>
ShowMsg('Access denied ! ! !'); Access denied ! ! !

how to hide some content after user logged in header

I want to hide login and sign up box and button after user login. I have tried but it won't work. Here are my codes
header.php
<!DOCTYPE HTML>
<html>
<head>
<title>My Play a Entertainment Category Flat Bootstrap Responsive Website Template | Home :: w3layouts</title>
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!-- bootstrap -->
<link href="css/bootstrap.min.css" rel='stylesheet' type='text/css' media="all" />
<!-- //bootstrap -->
<link href="css/dashboard.css" rel="stylesheet">
<!-- Custom Theme files -->
<link href="css/style.css" rel='stylesheet' type='text/css' media="all" />
<script src="js/jquery-1.11.1.min.js"></script>
<!--start-smoth-scrolling-->
</head>
<body>
<?php
session_start();
if(!isset($_SESSION["sess_email"])){
?>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"><h1><img src="images/logo.png" alt="" /></h1></a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<div class="top-search">
<form class="navbar-form navbar-right">
<input type="text" class="form-control" placeholder="Search...">
<input type="submit" value=" ">
</form>
</div>
<div class="header-top-right">
<div class="file">
Upload
</div>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"><h1><img src="images/logo.png" alt="" /></h1></a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<div class="top-search">
<form class="navbar-form navbar-right">
<input type="text" class="form-control" placeholder="Search...">
<input type="submit" value=" ">
</form>
</div>
<div class="header-top-right">
<div class="file">
Upload
</div>
<div class="signin">
Sign Up
<!-- pop-up-box -->
<script type="text/javascript" src="js/modernizr.custom.min.js"></script>
<link href="css/popuo-box.css" rel="stylesheet" type="text/css" media="all" />
<script src="js/jquery.magnific-popup.js" type="text/javascript"></script>
<!--//pop-up-box -->
<div id="small-dialog2" class="mfp-hide">
<h3>Create Account</h3>
<div class="social-sits">
<div class="facebook-button">
Connect with Facebook
</div>
<div class="chrome-button">
Connect with Google
</div>
<div class="button-bottom">
<p>Already have an account? Login</p>
</div>
</div>
<div class="signup">
<form action="addnewuser.php" " method="post">
<input type="text" name="username" class="email" placeholder="username" autocomplete="off"/>
<input type="text" name="email" class="email" placeholder="Email" required="required" pattern="([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?" title="Enter a valid email"/>
<input type="password" name="password" required="required" pattern=".{6,}" title="Minimum 6 characters required" autocomplete="off"/>
<input type="text" name="mnumber" class="email" placeholder="Mobile Number" maxlength="10" pattern="[1-9]{1}\d{9}" title="Enter a valid mobile number" />
<br><input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
<br>
<input type="submit" value="Signup" name="submit" />
</form>
</div>
<div class="clearfix"> </div>
</div>
<script>
$(document).ready(function() {
$('.popup-with-zoom-anim').magnificPopup({
type: 'inline',
fixedContentPos: false,
fixedBgPos: true,
overflowY: 'auto',
closeBtnInside: true,
preloader: false,
midClick: true,
removalDelay: 300,
mainClass: 'my-mfp-zoom-in'
});
});
</script>
</div>
<div class="signin">
Sign In
<div id="small-dialog" class="mfp-hide">
<h3>Login</h3>
<div class="social-sits">
<div class="facebook-button">
Connect with Facebook
</div>
<div class="chrome-button">
Connect with Google
</div>
<div class="button-bottom">
<p>New account? Signup</p>
</div>
</div>
<div class="signup">
<form action="login1.php" method="post">
<input type="text" name="email" class="email" placeholder="Email" required="required" pattern="([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?" title="Enter a valid email"/>
<input type="password" name="password" required="required" pattern=".{6,}" title="Minimum 6 characters required" autocomplete="off"/>
<input type="submit" value="Login" name="submit" />
</form>
<div class="forgot">
Forgot password ?
</div>
</div>
<div class="clearfix"> </div>
</div>
</div>
<div class="clearfix"> </div>
</div>
</div>
<div class="clearfix"> </div>
</div>
</nav>
<?php } else { ?>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"><h1><img src="images/logo.png" alt="" /></h1></a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<div class="top-search">
<form class="navbar-form navbar-right">
<input type="text" class="form-control" placeholder="Search...">
<input type="submit" value=" ">
</form>
</div>
<div class="header-top-right">
<div class="file">
Upload
</div>
<?=$_SESSION['sess_email'];?>Logout
<?php
}
?>
index.php
<?php include 'includes/header.php';?>
<!-- /header -->
<div class="col-sm-3 col-md-2 sidebar">
<div class="top-navigation">
<div class="t-menu">MENU</div>
<div class="t-img">
<img src="images/lines.png" alt="" />
</div>
<div class="clearfix"> </div>
</div>
<div class="drop-navigation drop-navigation">
<ul class="nav nav-sidebar">
<li class="active"><span class="glyphicon glyphicon-home" aria-hidden="true"></span>Home</li>
<li><span class="glyphicon glyphicon-home glyphicon-blackboard" aria-hidden="true"></span>TV Shows</li>
<li><span class="glyphicon glyphicon-home glyphicon-hourglass" aria-hidden="true"></span>History</li>
<li><span class="glyphicon glyphicon-film" aria-hidden="true"></span>Movies<span class="glyphicon glyphicon-menu-down" aria-hidden="true"></span></li>
<ul class="cl-effect-2">
<li>English</li>
<li>Chinese</li>
<li>Hindi</li>
</ul>
<!-- script-for-menu -->
<script>
$( "li a.menu1" ).click(function() {
$( "ul.cl-effect-2" ).slideToggle( 300, function() {
// Animation complete.
});
});
</script>
<li><span class="glyphicon glyphicon-film glyphicon-king" aria-hidden="true"></span>Sports<span class="glyphicon glyphicon-menu-down" aria-hidden="true"></span></li>
<ul class="cl-effect-1">
<li>Football</li>
<li>Cricket</li>
<li>Tennis</li>
<li>Shattil</li>
</ul>
<!-- script-for-menu -->
<script>
$( "li a.menu" ).click(function() {
$( "ul.cl-effect-1" ).slideToggle( 300, function() {
// Animation complete.
});
});
</script>
<li><span class="glyphicon glyphicon-music" aria-hidden="true"></span>Songs</li>
<li><span class="glyphicon glyphicon-envelope" aria-hidden="true"></span>News</li>
</ul>
<!-- script-for-menu -->
<script>
$( ".top-navigation" ).click(function() {
$( ".drop-navigation" ).slideToggle( 300, function() {
// Animation complete.
});
});
</script>
<div class="side-bottom">
<div class="side-bottom-icons">
<ul class="nav2">
<li> </li>
<li> </li>
<li> </li>
<li> </li>
</ul>
</div>
</div>
</div>
</div>
</div>
<?php include 'includes/footer.php';?>
login.php
<?php
if(isset($_POST["submit"])){
if(!empty($_POST['email']) && !empty($_POST['password'])) {
$email=$_POST['email'];
$password=$_POST['password'];
$con=mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('site1') or die("cannot select DB");
$query=mysql_query("SELECT * FROM user WHERE email='".$email."' AND password='".$password."'");
$numrows=mysql_num_rows($query);
if($numrows!=0)
{
while($row=mysql_fetch_assoc($query))
{
$dbemail=$row['email'];
$dbpassword=$row['password'];
}
if($email == $dbemail && $password == $dbpassword)
{
session_start();
$_SESSION['sess_email']=$email;
/* Redirect browser */
header("Location: index.php");
}
} else {
echo "Invalid email or password!";
}
} else {
echo "All fields are required!";
}
}
?>
There is something with your session_start(). These need to be on top of each file you are using the session handler. If you don't put session_start() on top, the headers won't be sent to the browser.
So your files would look like:
Header.php
<?php
session_start(); # This need to be on top, when using sessions!
?>
<!DOCTYPE HTML>
<html>
<head>
Login.php
<?php
session_start(); # This need to be on top, when using sessions!
if(isset($_POST["submit"])){
In headers.php check if $_SESSION['sess_email'] variable is not empty. If empty then display the login button.
start at the top of your page with
<?php
session_start();
//after you started the session create the rest of your page
?>
<!DOCTYPE HTML>
<html>
<head>
then at login.php you , again, start with
<?php
session_start();
at the top of your page
then create a if statement:
if(isset($_POST["submit"])){
//disable the login / signup button(s) here
//for example:
$logged_in = true;
} else $logged_in = false;
then create a jQuery function like this:
<script>
var logged_in = '<?php echo $logged_in ; ?>';
if(logged_in === "true") {
$(".signin").hide();
} else {
$(".signin").show();
}
</script>
or in javascript
<script>
var logged_in = '<?php echo $logged_in ; ?>';
if(logged_in === "true") {
document.getElementsByClassName("signin").style.visibility = "hidden";
} else {
document.getElementsByClassName("signin").style.visibility = "visible";
}
</script>

Categories

Resources